[jboss-cvs] JBoss Messaging SVN: r3748 - in branches/Branch_Stable: src/etc/xmdesc and 17 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Wed Feb 20 16:44:11 EST 2008


Author: timfox
Date: 2008-02-20 16:44:11 -0500 (Wed, 20 Feb 2008)
New Revision: 3748

Added:
   branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/RotatingID.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/RotatingIDTest.java
Removed:
   branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGenerator.java
   branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGeneratorFactory.java
Modified:
   branches/Branch_Stable/src/etc/server/default/deploy/mssql-persistence-service.xml
   branches/Branch_Stable/src/etc/server/default/deploy/mysql-persistence-service.xml
   branches/Branch_Stable/src/etc/server/default/deploy/oracle-persistence-service.xml
   branches/Branch_Stable/src/etc/server/default/deploy/postgresql-persistence-service.xml
   branches/Branch_Stable/src/etc/server/default/deploy/sybase-persistence-service.xml
   branches/Branch_Stable/src/etc/xmdesc/JDBCPersistenceManager-xmbean.xml
   branches/Branch_Stable/src/main/org/jboss/jms/client/container/ConnectionAspect.java
   branches/Branch_Stable/src/main/org/jboss/jms/client/container/ProducerAspect.java
   branches/Branch_Stable/src/main/org/jboss/jms/client/container/StateCreationAspect.java
   branches/Branch_Stable/src/main/org/jboss/jms/client/state/ConnectionState.java
   branches/Branch_Stable/src/main/org/jboss/jms/message/JBossMessage.java
   branches/Branch_Stable/src/main/org/jboss/jms/server/ServerPeer.java
   branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerConnectionEndpoint.java
   branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerSessionEndpoint.java
   branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/PersistenceManager.java
   branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/Queue.java
   branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/ChannelSupport.java
   branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/JDBCPersistenceManager.java
   branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/tx/TransactionRepository.java
   branches/Branch_Stable/src/main/org/jboss/messaging/core/jmx/JDBCPersistenceManagerService.java
   branches/Branch_Stable/tests/build.xml
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/MessagingTestCase.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/JDBCPersistenceManagerTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/MessagingQueueTestBase.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/PostOfficeTestBase.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/PagingStateTestBase.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/SingleChannel_ReloadTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/ConnectionTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusterConnectionManagerTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusteringTestBase.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DisableLoadBalancingAndFailoverTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DistributedTopicTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/FailoverTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/GroupManagementTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LargeClusterTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LoadBalancingTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MergeQueueTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MultiThreadFailoverTest.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/aop/PoisonInterceptor.java
   branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/container/ServiceContainer.java
Log:
http://jira.jboss.org/jira/browse/JBMESSAGING-1233


Modified: branches/Branch_Stable/src/etc/server/default/deploy/mssql-persistence-service.xml
===================================================================
--- branches/Branch_Stable/src/etc/server/default/deploy/mssql-persistence-service.xml	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/etc/server/default/deploy/mssql-persistence-service.xml	2008-02-20 21:44:11 UTC (rev 3748)
@@ -12,27 +12,31 @@
 
    <!-- Persistence Manager MBean configuration
        ======================================== -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.JDBCPersistenceManagerService"
       name="jboss.messaging:service=PersistenceManager"
       xmbean-dd="xmdesc/JDBCPersistenceManager-xmbean.xml">
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
+
       <!-- The datasource to use for the persistence manager -->
-        
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-      
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
-      <!-- If true then will use JDBC batch updates -->
-      
-      <attribute name="UsingBatchUpdates">true</attribute>
-      
+
+      <!-- If true then we will automatically detect and reject duplicate messages sent during failover -->
+
+      <attribute name="DetectDuplicates">true</attribute>
+
+      <!-- The size of the id cache to use when detecting duplicate messages -->
+
+      <attribute name="IDCacheSize">500</attribute>
+
       <attribute name="SqlProperties"><![CDATA[
    CREATE_DUAL=CREATE TABLE JBM_DUAL (DUMMY INTEGER, PRIMARY KEY (DUMMY))
    CREATE_MESSAGE_REFERENCE=CREATE TABLE JBM_MSG_REF (MESSAGE_ID BIGINT, CHANNEL_ID BIGINT, TRANSACTION_ID BIGINT, STATE CHAR(1), ORD BIGINT, PAGE_ORD BIGINT, DELIVERY_COUNT INT, SCHED_DELIVERY BIGINT, PRIMARY KEY(MESSAGE_ID, CHANNEL_ID))
@@ -44,6 +48,7 @@
    CREATE_MESSAGE=CREATE TABLE JBM_MSG (MESSAGE_ID BIGINT, RELIABLE CHAR(1), EXPIRATION BIGINT, TIMESTAMP BIGINT, PRIORITY TINYINT, TYPE TINYINT, HEADERS IMAGE, PAYLOAD IMAGE, PRIMARY KEY (MESSAGE_ID))
    CREATE_TRANSACTION=CREATE TABLE JBM_TX (NODE_ID INTEGER, TRANSACTION_ID BIGINT, BRANCH_QUAL VARBINARY(254), FORMAT_ID INT, GLOBAL_TXID VARBINARY(254), PRIMARY KEY (TRANSACTION_ID))
    CREATE_COUNTER=CREATE TABLE JBM_COUNTER (NAME VARCHAR(255), NEXT_ID BIGINT, PRIMARY KEY(NAME))
+   CREATE_ID_CACHE=CREATE TABLE JBM_ID_CACHE (NODE_ID INTEGER, CNTR INTEGER, JBM_ID VARCHAR(255), PRIMARY KEY(NODE_ID, CNTR))
    INSERT_DUAL=INSERT INTO JBM_DUAL VALUES (1)
    CHECK_DUAL=SELECT 1 FROM JBM_DUAL
    INSERT_MESSAGE_REF=INSERT INTO JBM_MSG_REF (CHANNEL_ID, MESSAGE_ID, TRANSACTION_ID, STATE, ORD, PAGE_ORD, DELIVERY_COUNT, SCHED_DELIVERY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -59,17 +64,16 @@
    LOAD_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, SCHED_DELIVERY FROM JBM_MSG_REF WHERE STATE = 'C' AND CHANNEL_ID = ? ORDER BY ORD
    UPDATE_REFS_NOT_PAGED=UPDATE JBM_MSG_REF SET PAGE_ORD = NULL WHERE PAGE_ORD BETWEEN ? AND ? AND CHANNEL_ID=?
    SELECT_MIN_MAX_PAGE_ORD=SELECT MIN(PAGE_ORD), MAX(PAGE_ORD) FROM JBM_MSG_REF WHERE CHANNEL_ID = ?
-   SELECT_EXISTS_REF_MESSAGE_ID=SELECT MESSAGE_ID FROM JBM_MSG_REF WHERE MESSAGE_ID = ?
-   UPDATE_DELIVERY_COUNT=UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ? 
-   UPDATE_CHANNEL_ID=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE CHANNEL_ID = ?   
-   MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?    
+   UPDATE_DELIVERY_COUNT=UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
+   UPDATE_CHANNEL_ID=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE CHANNEL_ID = ?
+   MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
    LOAD_MESSAGES=SELECT MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, HEADERS, PAYLOAD, TYPE FROM JBM_MSG
    INSERT_MESSAGE=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    INSERT_MESSAGE_CONDITIONAL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE) SELECT ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    UPDATE_MESSAGE_4CONDITIONAL=UPDATE JBM_MSG SET HEADERS=?, PAYLOAD=? WHERE MESSAGE_ID=?
-   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)   
+   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    MESSAGE_ID_COLUMN=MESSAGE_ID
-   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)   
+   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)
    INSERT_TRANSACTION=INSERT INTO JBM_TX (NODE_ID, TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID) VALUES(?, ?, ?, ?, ?)
    DELETE_TRANSACTION=DELETE FROM JBM_TX WHERE NODE_ID = ? AND TRANSACTION_ID = ?
    SELECT_PREPARED_TRANSACTIONS=SELECT TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID FROM JBM_TX WHERE NODE_ID = ?
@@ -80,69 +84,72 @@
    INSERT_COUNTER=INSERT INTO JBM_COUNTER (NAME, NEXT_ID) VALUES (?, ?)
    SELECT_ALL_CHANNELS=SELECT DISTINCT(CHANNEL_ID) FROM JBM_MSG_REF
    UPDATE_TX=UPDATE JBM_TX SET NODE_ID=? WHERE NODE_ID=?
+   UPDATE_ID_IN_CACHE=UPDATE JBM_ID_CACHE SET JBM_ID = ? WHERE NODE_ID = ? AND CNTR = ?
+   INSERT_ID_IN_CACHE=INSERT INTO JBM_ID_CACHE (NODE_ID, CNTR, JBM_ID) VALUES (?, ?, ?)
+   LOAD_ID_CACHE=SELECT CNTR, JBM_ID FROM JBM_ID_CACHE WHERE NODE_ID = ?
       ]]></attribute>
-      
+
       <!-- The maximum number of parameters to include in a prepared statement -->
-      
+
       <attribute name="MaxParams">500</attribute>
-           
+
    </mbean>
 
    <!-- Messaging Post Office MBean configuration
         ========================================= -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.MessagingPostOfficeService"
       name="jboss.messaging:service=PostOffice"
       xmbean-dd="xmdesc/MessagingPostOffice-xmbean.xml">
-      
+
       <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
-                 
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
-      <!-- The name of the post office -->      
-      
+
+      <!-- The name of the post office -->
+
       <attribute name="PostOfficeName">JMS post office</attribute>
-      
-      <!-- The datasource used by the post office to access it's binding information -->      
-            
+
+      <!-- The datasource used by the post office to access it's binding information -->
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-            
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
 CREATE_POSTOFFICE_TABLE=CREATE TABLE JBM_POSTOFFICE (POSTOFFICE_NAME VARCHAR(255), NODE_ID SMALLINT, QUEUE_NAME VARCHAR(255), COND VARCHAR(1023), SELECTOR VARCHAR(1023), CHANNEL_ID INTEGER, CLSTERED CHAR(1), ALL_NODES CHAR(1), PRIMARY KEY(POSTOFFICE_NAME, NODE_ID, QUEUE_NAME))
 INSERT_BINDING=INSERT INTO JBM_POSTOFFICE (POSTOFFICE_NAME, NODE_ID, QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLSTERED, ALL_NODES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
 DELETE_BINDING=DELETE FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=? AND QUEUE_NAME=?
 LOAD_BINDINGS=SELECT QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLSTERED, ALL_NODES FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=?
-      ]]></attribute>        
-      
+      ]]></attribute>
+
       <!-- This post office is clustered. If you don't want a clustered post office then set to false -->
-      
+
       <attribute name="Clustered">true</attribute>
-      
+
       <!-- All the remaining properties only have to be specified if the post office is clustered.
            You can safely comment them out if your post office is non clustered -->
-      
-      <!-- The JGroups group name that the post office will use -->      
-            
+
+      <!-- The JGroups group name that the post office will use -->
+
       <attribute name="GroupName">${jboss.messaging.groupname:MessagingPostOffice}</attribute>
-     
-      <!-- Max time to wait for state to arrive when the post office joins the cluster -->            
-      
+
+      <!-- Max time to wait for state to arrive when the post office joins the cluster -->
+
       <attribute name="StateTimeout">30000</attribute>
-      
-      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->            
-      
+
+      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->
+
       <attribute name="CastTimeout">30000</attribute>
-       
-      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->               
-      
-      <!-- By default we use the TCP stack for data -->                  
-      <attribute name="DataChannelConfig">      
+
+      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->
+
+      <!-- By default we use the TCP stack for data -->
+      <attribute name="DataChannelConfig">
          <config>
             <TCP start_port="7900"
                  loopback="true"
@@ -163,10 +170,10 @@
 		         mcast_port="${jboss.messaging.datachanneludpport:45567}"
 		         ip_ttl="${jboss.messaging.ipttl:8}"
 		         num_initial_members="2"
-		         num_ping_requests="1"/>                     
+		         num_ping_requests="1"/>
             <MERGE2 max_interval="100000"
                     down_thread="false" up_thread="false" min_interval="20000"/>
-            <FD_SOCK down_thread="false" up_thread="false"/>            
+            <FD_SOCK down_thread="false" up_thread="false"/>
             <VERIFY_SUSPECT timeout="1500" down_thread="false" up_thread="false"/>
             <pbcast.NAKACK max_xmit_size="60000"
                            use_mcast_xmit="false" gc_lag="0"
@@ -180,11 +187,11 @@
                         down_thread="false" up_thread="false"
                         join_retry_timeout="2000" shun="false"
                         view_bundling="true"/>
-        </config>        
+        </config>
       </attribute>
-      
-      <!-- JGroups stack configuration to use for the control channel - used for control messages -->         
-              
+
+      <!-- JGroups stack configuration to use for the control channel - used for control messages -->
+
       <!-- We use udp stack for the control channel -->
       <attribute name="ControlChannelConfig">
          <config>
@@ -230,24 +237,24 @@
             <pbcast.STATE_TRANSFER down_thread="false" up_thread="false" use_flush="true" flush_timeout="3000"/>
             <pbcast.FLUSH down_thread="false" up_thread="false" timeout="20000" auto_flush_conf="false"/>
         </config>
-     </attribute>	
-   </mbean>    
-   
+     </attribute>
+   </mbean>
+
    <!-- Messaging JMS User Manager MBean config
         ======================================= -->
-   
+
    <mbean code="org.jboss.jms.server.plugin.JDBCJMSUserManagerService"
       name="jboss.messaging:service=JMSUserManager"
       xmbean-dd="xmdesc/JMSUserManager-xmbean.xml">
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
 CREATE_USER_TABLE=CREATE TABLE JBM_USER (USER_ID VARCHAR(32) NOT NULL, PASSWD VARCHAR(32) NOT NULL, CLIENTID VARCHAR(128), PRIMARY KEY(USER_ID))
 CREATE_ROLE_TABLE=CREATE TABLE JBM_ROLE (ROLE_ID VARCHAR(32) NOT NULL, USER_ID VARCHAR(32) NOT NULL, PRIMARY KEY(USER_ID, ROLE_ID))

Modified: branches/Branch_Stable/src/etc/server/default/deploy/mysql-persistence-service.xml
===================================================================
--- branches/Branch_Stable/src/etc/server/default/deploy/mysql-persistence-service.xml	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/etc/server/default/deploy/mysql-persistence-service.xml	2008-02-20 21:44:11 UTC (rev 3748)
@@ -12,38 +12,43 @@
 
    <!-- Persistence Manager MBean configuration
        ======================================== -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.JDBCPersistenceManagerService"
       name="jboss.messaging:service=PersistenceManager"
       xmbean-dd="xmdesc/JDBCPersistenceManager-xmbean.xml">
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
+
       <!-- The datasource to use for the persistence manager -->
-                    
-      <attribute name="DataSource">java:/DefaultDS</attribute>      
-      
+
+      <attribute name="DataSource">java:/DefaultDS</attribute>
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-                  
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
-      <!-- If true then will use JDBC batch updates -->
-                  
-      <attribute name="UsingBatchUpdates">true</attribute>
-      
+
+      <!-- If true then we will automatically detect and reject duplicate messages sent during failover -->
+
+      <attribute name="DetectDuplicates">true</attribute>
+
+      <!-- The size of the id cache to use when detecting duplicate messages -->
+
+      <attribute name="IDCacheSize">500</attribute>
+
       <attribute name="SqlProperties"><![CDATA[
    CREATE_DUAL=CREATE TABLE JBM_DUAL (DUMMY INTEGER, PRIMARY KEY (DUMMY)) ENGINE = INNODB
-   CREATE_MESSAGE_REFERENCE=CREATE TABLE JBM_MSG_REF (MESSAGE_ID BIGINT, CHANNEL_ID BIGINT, TRANSACTION_ID BIGINT, STATE CHAR(1), ORD BIGINT, PAGE_ORD BIGINT, DELIVERY_COUNT INTEGER, SCHED_DELIVERY BIGINT, PRIMARY KEY(MESSAGE_ID, CHANNEL_ID)) ENGINE = INNODB   
-   CREATE_IDX_MESSAGE_REF_TX=CREATE INDEX JBM_MSG_REF_TX ON JBM_MSG_REF (TRANSACTION_ID, STATE)   
+   CREATE_MESSAGE_REFERENCE=CREATE TABLE JBM_MSG_REF (MESSAGE_ID BIGINT, CHANNEL_ID BIGINT, TRANSACTION_ID BIGINT, STATE CHAR(1), ORD BIGINT, PAGE_ORD BIGINT, DELIVERY_COUNT INTEGER, SCHED_DELIVERY BIGINT, PRIMARY KEY(MESSAGE_ID, CHANNEL_ID)) ENGINE = INNODB
+   CREATE_IDX_MESSAGE_REF_TX=CREATE INDEX JBM_MSG_REF_TX ON JBM_MSG_REF (TRANSACTION_ID, STATE)
    CREATE_IDX_MESSAGE_REF_ORD=CREATE INDEX JBM_MSG_REF_ORD ON JBM_MSG_REF (ORD)
    CREATE_IDX_MESSAGE_REF_PAGE_ORD=CREATE INDEX JBM_MSG_REF_PAGE_ORD ON JBM_MSG_REF (PAGE_ORD)
    CREATE_IDX_MESSAGE_REF_MESSAGE_ID=CREATE INDEX JBM_MSG_REF_MESSAGE_ID ON JBM_MSG_REF (MESSAGE_ID)
-   CREATE_IDX_MESSAGE_REF_SCHED_DELIVERY=CREATE INDEX JBM_MSG_REF_SCHED_DELIVERY ON JBM_MSG_REF (SCHED_DELIVERY)      
-   CREATE_MESSAGE=CREATE TABLE JBM_MSG (MESSAGE_ID BIGINT, RELIABLE CHAR(1), EXPIRATION BIGINT, TIMESTAMP BIGINT, PRIORITY TINYINT, TYPE TINYINT, HEADERS MEDIUMBLOB, PAYLOAD LONGBLOB, PRIMARY KEY (MESSAGE_ID)) ENGINE = INNODB  
+   CREATE_IDX_MESSAGE_REF_SCHED_DELIVERY=CREATE INDEX JBM_MSG_REF_SCHED_DELIVERY ON JBM_MSG_REF (SCHED_DELIVERY)
+   CREATE_MESSAGE=CREATE TABLE JBM_MSG (MESSAGE_ID BIGINT, RELIABLE CHAR(1), EXPIRATION BIGINT, TIMESTAMP BIGINT, PRIORITY TINYINT, TYPE TINYINT, HEADERS MEDIUMBLOB, PAYLOAD LONGBLOB, PRIMARY KEY (MESSAGE_ID)) ENGINE = INNODB
    CREATE_TRANSACTION=CREATE TABLE JBM_TX (NODE_ID INTEGER, TRANSACTION_ID BIGINT, BRANCH_QUAL VARBINARY(254), FORMAT_ID INTEGER, GLOBAL_TXID VARBINARY(254), PRIMARY KEY (TRANSACTION_ID)) ENGINE = INNODB
    CREATE_COUNTER=CREATE TABLE JBM_COUNTER (NAME VARCHAR(255), NEXT_ID BIGINT, PRIMARY KEY(NAME)) ENGINE = INNODB
+   CREATE_ID_CACHE=CREATE TABLE JBM_ID_CACHE (NODE_ID INTEGER, CNTR INTEGER, JBM_ID VARCHAR(255), PRIMARY KEY(NODE_ID, CNTR))
    INSERT_DUAL=INSERT INTO JBM_DUAL VALUES (1)
    CHECK_DUAL=SELECT 1 FROM JBM_DUAL
    INSERT_MESSAGE_REF=INSERT INTO JBM_MSG_REF (CHANNEL_ID, MESSAGE_ID, TRANSACTION_ID, STATE, ORD, PAGE_ORD, DELIVERY_COUNT, SCHED_DELIVERY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -56,10 +61,9 @@
    ROLLBACK_MESSAGE_REF2=UPDATE JBM_MSG_REF SET STATE='C', TRANSACTION_ID = NULL WHERE TRANSACTION_ID=? AND STATE='-'
    LOAD_PAGED_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, PAGE_ORD, SCHED_DELIVERY FROM JBM_MSG_REF WHERE CHANNEL_ID = ? AND PAGE_ORD BETWEEN ? AND ? ORDER BY PAGE_ORD
    LOAD_UNPAGED_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, SCHED_DELIVERY FROM JBM_MSG_REF WHERE STATE = 'C' AND CHANNEL_ID = ? AND PAGE_ORD IS NULL ORDER BY ORD
-   LOAD_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, SCHED_DELIVERY FROM JBM_MSG_REF WHERE STATE = 'C' AND CHANNEL_ID = ? ORDER BY ORD     
+   LOAD_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, SCHED_DELIVERY FROM JBM_MSG_REF WHERE STATE = 'C' AND CHANNEL_ID = ? ORDER BY ORD
    UPDATE_REFS_NOT_PAGED=UPDATE JBM_MSG_REF SET PAGE_ORD = NULL WHERE PAGE_ORD BETWEEN ? AND ? AND CHANNEL_ID=?
    SELECT_MIN_MAX_PAGE_ORD=SELECT MIN(PAGE_ORD), MAX(PAGE_ORD) FROM JBM_MSG_REF WHERE CHANNEL_ID = ?
-   SELECT_EXISTS_REF_MESSAGE_ID=SELECT MESSAGE_ID FROM JBM_MSG_REF WHERE MESSAGE_ID = ?
    UPDATE_DELIVERY_COUNT=UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
    UPDATE_CHANNEL_ID=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE CHANNEL_ID = ?
    MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
@@ -67,9 +71,9 @@
    INSERT_MESSAGE=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    INSERT_MESSAGE_CONDITIONAL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE) SELECT ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    UPDATE_MESSAGE_4CONDITIONAL=UPDATE JBM_MSG SET HEADERS=?, PAYLOAD=? WHERE MESSAGE_ID=?
-   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)   
-   MESSAGE_ID_COLUMN=MESSAGE_ID   
-   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)      
+   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
+   MESSAGE_ID_COLUMN=MESSAGE_ID
+   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)
    INSERT_TRANSACTION=INSERT INTO JBM_TX (NODE_ID, TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID) VALUES(?, ?, ?, ?, ?)
    DELETE_TRANSACTION=DELETE FROM JBM_TX WHERE NODE_ID = ? AND TRANSACTION_ID = ?
    SELECT_PREPARED_TRANSACTIONS=SELECT TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID FROM JBM_TX WHERE NODE_ID = ?
@@ -80,69 +84,72 @@
    INSERT_COUNTER=INSERT INTO JBM_COUNTER (NAME, NEXT_ID) VALUES (?, ?)
    SELECT_ALL_CHANNELS=SELECT DISTINCT(CHANNEL_ID) FROM JBM_MSG_REF
    UPDATE_TX=UPDATE JBM_TX SET NODE_ID=? WHERE NODE_ID=?
+   UPDATE_ID_IN_CACHE=UPDATE JBM_ID_CACHE SET JBM_ID = ? WHERE NODE_ID = ? AND CNTR = ?
+   INSERT_ID_IN_CACHE=INSERT INTO JBM_ID_CACHE (NODE_ID, CNTR, JBM_ID) VALUES (?, ?, ?)
+   LOAD_ID_CACHE=SELECT CNTR, JBM_ID FROM JBM_ID_CACHE WHERE NODE_ID = ?
       ]]></attribute>
-      
+
       <!-- The maximum number of parameters to include in a prepared statement -->
-                  
+
       <attribute name="MaxParams">500</attribute>
-           
+
    </mbean>
 
    <!-- Messaging Post Office MBean configuration
         ========================================= -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.MessagingPostOfficeService"
       name="jboss.messaging:service=PostOffice"
       xmbean-dd="xmdesc/MessagingPostOffice-xmbean.xml">
-      
+
       <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
-                
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
-      <!-- The name of the post office -->                  
-      
+
+      <!-- The name of the post office -->
+
       <attribute name="PostOfficeName">JMS post office</attribute>
-      
-      <!-- The datasource used by the post office to access it's binding information -->                     
-      
+
+      <!-- The datasource used by the post office to access it's binding information -->
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-                        
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
 CREATE_POSTOFFICE_TABLE=CREATE TABLE JBM_POSTOFFICE (POSTOFFICE_NAME VARCHAR(255), NODE_ID INTEGER, QUEUE_NAME VARCHAR(255), COND VARCHAR(1023), SELECTOR VARCHAR(1023), CHANNEL_ID BIGINT, CLUSTERED CHAR(1), ALL_NODES CHAR(1), PRIMARY KEY(POSTOFFICE_NAME, NODE_ID, QUEUE_NAME)) ENGINE = INNODB
 INSERT_BINDING=INSERT INTO JBM_POSTOFFICE (POSTOFFICE_NAME, NODE_ID, QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
 DELETE_BINDING=DELETE FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=? AND QUEUE_NAME=?
 LOAD_BINDINGS=SELECT QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=?
       ]]></attribute>
-      
+
       <!-- This post office is clustered. If you don't want a clustered post office then set to false -->
-      
+
       <attribute name="Clustered">true</attribute>
-      
+
       <!-- All the remaining properties only have to be specified if the post office is clustered.
            You can safely comment them out if your post office is non clustered -->
-      
-      <!-- The JGroups group name that the post office will use -->            
-      
+
+      <!-- The JGroups group name that the post office will use -->
+
       <attribute name="GroupName">${jboss.messaging.groupname:MessagingPostOffice}</attribute>
-      
-      <!-- Max time to wait for state to arrive when the post office joins the cluster -->            
-                  
+
+      <!-- Max time to wait for state to arrive when the post office joins the cluster -->
+
       <attribute name="StateTimeout">300000</attribute>
-      
-      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->            
-                  
+
+      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->
+
       <attribute name="CastTimeout">300000</attribute>
-      
-      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster --> 
-                   
-      <!-- By default we use the TCP stack for data -->                  
-      <attribute name="DataChannelConfig">      
+
+      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->
+
+      <!-- By default we use the TCP stack for data -->
+      <attribute name="DataChannelConfig">
          <config>
             <TCP start_port="7900"
                  loopback="true"
@@ -158,15 +165,15 @@
                  use_send_queues="false"
                  sock_conn_timeout="300"
                  skip_suspected_members="true"/>
-            <MPING timeout="4000"		        
+            <MPING timeout="4000"
 		         mcast_addr="${jboss.messaging.datachanneludpaddress:228.6.6.6}"
 		         mcast_port="${jboss.messaging.datachanneludpport:45567}"
 		         ip_ttl="${jboss.messaging.ipttl:8}"
 		         num_initial_members="2"
-		         num_ping_requests="1"/>                     
+		         num_ping_requests="1"/>
             <MERGE2 max_interval="100000"
                     down_thread="false" up_thread="false" min_interval="20000"/>
-            <FD_SOCK down_thread="false" up_thread="false"/>            
+            <FD_SOCK down_thread="false" up_thread="false"/>
             <VERIFY_SUSPECT timeout="1500" down_thread="false" up_thread="false"/>
             <pbcast.NAKACK max_xmit_size="60000"
                            use_mcast_xmit="false" gc_lag="0"
@@ -180,11 +187,11 @@
                         down_thread="false" up_thread="false"
                         join_retry_timeout="2000" shun="false"
                         view_bundling="true"/>
-        </config>        
+        </config>
       </attribute>
-      
-      <!-- JGroups stack configuration to use for the control channel - used for control messages -->         
-              
+
+      <!-- JGroups stack configuration to use for the control channel - used for control messages -->
+
       <!-- We use udp stack for the control channel -->
       <attribute name="ControlChannelConfig">
          <config>
@@ -230,13 +237,13 @@
             <pbcast.STATE_TRANSFER down_thread="false" up_thread="false" use_flush="true" flush_timeout="3000"/>
             <pbcast.FLUSH down_thread="false" up_thread="false" timeout="20000" auto_flush_conf="false"/>
         </config>
-     </attribute>	   
-      
+     </attribute>
+
    </mbean>
-   
+
    <!-- Messaging JMS User Manager MBean config
         ======================================= -->
-      
+
    <mbean code="org.jboss.jms.server.plugin.JDBCJMSUserManagerService"
       name="jboss.messaging:service=JMSUserManager"
       xmbean-dd="xmdesc/JMSUserManager-xmbean.xml">

Modified: branches/Branch_Stable/src/etc/server/default/deploy/oracle-persistence-service.xml
===================================================================
--- branches/Branch_Stable/src/etc/server/default/deploy/oracle-persistence-service.xml	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/etc/server/default/deploy/oracle-persistence-service.xml	2008-02-20 21:44:11 UTC (rev 3748)
@@ -12,33 +12,37 @@
 
    <!-- Persistence Manager MBean configuration
        ======================================== -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.JDBCPersistenceManagerService"
       name="jboss.messaging:service=PersistenceManager"
       xmbean-dd="xmdesc/JDBCPersistenceManager-xmbean.xml">
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
+
       <!-- The datasource to use for the persistence manager -->
-                    
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-                  
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
-      <!-- If true then will use JDBC batch updates -->
-                  
-      <attribute name="UsingBatchUpdates">true</attribute>
-      
+
+      <!-- If true then we will automatically detect and reject duplicate messages sent during failover -->
+
+      <attribute name="DetectDuplicates">true</attribute>
+
+      <!-- The size of the id cache to use when detecting duplicate messages -->
+
+      <attribute name="IDCacheSize">500</attribute>
+
       <!-- Some databases don't support inserting blobs using INSERT INTO ... SELECT FROM -->
-      
+
       <attribute name="SupportsBlobOnSelect">false</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
-   CREATE_DUAL=CREATE TABLE JBM_DUAL (DUMMY INTEGER, PRIMARY KEY (DUMMY))   
+   CREATE_DUAL=CREATE TABLE JBM_DUAL (DUMMY INTEGER, PRIMARY KEY (DUMMY))
    CREATE_MESSAGE_REFERENCE=CREATE TABLE JBM_MSG_REF (MESSAGE_ID INTEGER, CHANNEL_ID INTEGER, TRANSACTION_ID INTEGER, STATE CHAR(1), ORD INTEGER, PAGE_ORD INTEGER, DELIVERY_COUNT INTEGER, SCHED_DELIVERY INTEGER, PRIMARY KEY(MESSAGE_ID, CHANNEL_ID))
    CREATE_IDX_MESSAGE_REF_TX=CREATE INDEX JBM_MSG_REF_TX ON JBM_MSG_REF (TRANSACTION_ID, STATE)
    CREATE_IDX_MESSAGE_REF_ORD=CREATE INDEX JBM_MSG_REF_ORD ON JBM_MSG_REF (ORD)
@@ -48,6 +52,7 @@
    CREATE_MESSAGE=CREATE TABLE JBM_MSG (MESSAGE_ID INTEGER, RELIABLE CHAR(1), EXPIRATION INTEGER, TIMESTAMP INTEGER, PRIORITY INTEGER, TYPE INTEGER, HEADERS BLOB, PAYLOAD BLOB, PRIMARY KEY (MESSAGE_ID))
    CREATE_TRANSACTION=CREATE TABLE JBM_TX (NODE_ID INTEGER, TRANSACTION_ID INTEGER, BRANCH_QUAL RAW(254), FORMAT_ID INTEGER, GLOBAL_TXID RAW(254), PRIMARY KEY (TRANSACTION_ID))
    CREATE_COUNTER=CREATE TABLE JBM_COUNTER (NAME VARCHAR2(255), NEXT_ID INTEGER, PRIMARY KEY(NAME))
+   CREATE_ID_CACHE=CREATE TABLE JBM_ID_CACHE (NODE_ID INTEGER, CNTR INTEGER, JBM_ID VARCHAR2(255), PRIMARY KEY(NODE_ID, CNTR))
    INSERT_DUAL=INSERT INTO JBM_DUAL VALUES (1)
    CHECK_DUAL=SELECT 1 FROM JBM_DUAL
    INSERT_MESSAGE_REF=INSERT INTO JBM_MSG_REF (CHANNEL_ID, MESSAGE_ID, TRANSACTION_ID, STATE, ORD, PAGE_ORD, DELIVERY_COUNT, SCHED_DELIVERY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -63,17 +68,16 @@
    LOAD_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, SCHED_DELIVERY FROM JBM_MSG_REF WHERE STATE = 'C' AND CHANNEL_ID = ? ORDER BY ORD
    UPDATE_REFS_NOT_PAGED=UPDATE JBM_MSG_REF SET PAGE_ORD = NULL WHERE PAGE_ORD BETWEEN ? AND ? AND CHANNEL_ID=?
    SELECT_MIN_MAX_PAGE_ORD=SELECT MIN(PAGE_ORD), MAX(PAGE_ORD) FROM JBM_MSG_REF WHERE CHANNEL_ID = ?
-   SELECT_EXISTS_REF_MESSAGE_ID=SELECT MESSAGE_ID FROM JBM_MSG_REF WHERE MESSAGE_ID = ?
-   UPDATE_DELIVERY_COUNT=UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ? 
+   UPDATE_DELIVERY_COUNT=UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
    UPDATE_CHANNEL_ID=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE CHANNEL_ID = ?
-   MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ? 
+   MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
    LOAD_MESSAGES=SELECT MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, HEADERS, PAYLOAD, TYPE FROM JBM_MSG
    INSERT_MESSAGE=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    INSERT_MESSAGE_CONDITIONAL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE) SELECT ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    UPDATE_MESSAGE_4CONDITIONAL=UPDATE JBM_MSG SET HEADERS=?, PAYLOAD=? WHERE MESSAGE_ID=?
-   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)   
+   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    MESSAGE_ID_COLUMN=MESSAGE_ID
-   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)   
+   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)
    INSERT_TRANSACTION=INSERT INTO JBM_TX (NODE_ID, TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID) VALUES(?, ?, ?, ?, ?)
    DELETE_TRANSACTION=DELETE FROM JBM_TX WHERE NODE_ID = ? AND TRANSACTION_ID = ?
    SELECT_PREPARED_TRANSACTIONS=SELECT TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID FROM JBM_TX WHERE NODE_ID = ?
@@ -84,69 +88,72 @@
    INSERT_COUNTER=INSERT INTO JBM_COUNTER (NAME, NEXT_ID) VALUES (?, ?)
    SELECT_ALL_CHANNELS=SELECT DISTINCT(CHANNEL_ID) FROM JBM_MSG_REF
    UPDATE_TX=UPDATE JBM_TX SET NODE_ID=? WHERE NODE_ID=?
+   UPDATE_ID_IN_CACHE=UPDATE JBM_ID_CACHE SET JBM_ID = ? WHERE NODE_ID = ? AND CNTR = ?
+   INSERT_ID_IN_CACHE=INSERT INTO JBM_ID_CACHE (NODE_ID, CNTR, JBM_ID) VALUES (?, ?, ?)
+   LOAD_ID_CACHE=SELECT CNTR, JBM_ID FROM JBM_ID_CACHE WHERE NODE_ID = ?
       ]]></attribute>
-      
+
       <!-- The maximum number of parameters to include in a prepared statement -->
-                  
+
       <attribute name="MaxParams">500</attribute>
-       
+
    </mbean>
 
    <!-- Messaging Post Office MBean configuration
         ========================================= -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.MessagingPostOfficeService"
       name="jboss.messaging:service=PostOffice"
       xmbean-dd="xmdesc/MessagingPostOffice-xmbean.xml">
-            
+
       <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
-      <!-- The name of the post office -->      
-                  
+
+      <!-- The name of the post office -->
+
       <attribute name="PostOfficeName">JMS post office</attribute>
-      
-      <!-- The datasource used by the post office to access it's binding information -->      
-                    
+
+      <!-- The datasource used by the post office to access it's binding information -->
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
-      <!-- If true will attempt to create tables and indexes on every start-up -->                  
-      
+
+      <!-- If true will attempt to create tables and indexes on every start-up -->
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
 CREATE_POSTOFFICE_TABLE=CREATE TABLE JBM_POSTOFFICE (POSTOFFICE_NAME VARCHAR2(255), NODE_ID INTEGER, QUEUE_NAME VARCHAR2(255), COND VARCHAR2(1023), SELECTOR VARCHAR2(1023), CHANNEL_ID INTEGER, CLUSTERED CHAR(1), ALL_NODES CHAR(1), PRIMARY KEY(POSTOFFICE_NAME, NODE_ID, QUEUE_NAME))
 INSERT_BINDING=INSERT INTO JBM_POSTOFFICE (POSTOFFICE_NAME, NODE_ID, QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
 DELETE_BINDING=DELETE FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=? AND QUEUE_NAME=?
 LOAD_BINDINGS=SELECT QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=?
       ]]></attribute>
-      
+
 	  <!-- This post office is clustered. If you don't want a clustered post office then set to false -->
-      
+
       <attribute name="Clustered">true</attribute>
-      
+
       <!-- All the remaining properties only have to be specified if the post office is clustered.
            You can safely comment them out if your post office is non clustered -->
-      
-      <!-- The JGroups group name that the post office will use -->          
-      
+
+      <!-- The JGroups group name that the post office will use -->
+
       <attribute name="GroupName">${jboss.messaging.groupname:MessagingPostOffice}</attribute>
-     
-      <!-- Max time to wait for state to arrive when the post office joins the cluster -->            
-                  
+
+      <!-- Max time to wait for state to arrive when the post office joins the cluster -->
+
       <attribute name="StateTimeout">30000</attribute>
-      
-      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->            
-                  
+
+      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->
+
       <attribute name="CastTimeout">30000</attribute>
-      
-      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->               
-      
-      <!-- By default we use the TCP stack for data -->                  
-      <attribute name="DataChannelConfig">      
+
+      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->
+
+      <!-- By default we use the TCP stack for data -->
+      <attribute name="DataChannelConfig">
          <config>
             <TCP start_port="7900"
                  loopback="true"
@@ -162,15 +169,15 @@
                  use_send_queues="false"
                  sock_conn_timeout="300"
                  skip_suspected_members="true"/>
-            <MPING timeout="4000"	
+            <MPING timeout="4000"
 		         mcast_addr="${jboss.messaging.datachanneludpaddress:228.6.6.6}"
 		         mcast_port="${jboss.messaging.datachanneludpport:45567}"
 		         ip_ttl="${jboss.messaging.ipttl:8}"
 		         num_initial_members="2"
-		         num_ping_requests="1"/>                     
+		         num_ping_requests="1"/>
             <MERGE2 max_interval="100000"
                     down_thread="false" up_thread="false" min_interval="20000"/>
-            <FD_SOCK down_thread="false" up_thread="false"/>            
+            <FD_SOCK down_thread="false" up_thread="false"/>
             <VERIFY_SUSPECT timeout="1500" down_thread="false" up_thread="false"/>
             <pbcast.NAKACK max_xmit_size="60000"
                            use_mcast_xmit="false" gc_lag="0"
@@ -184,11 +191,11 @@
                         down_thread="false" up_thread="false"
                         join_retry_timeout="2000" shun="false"
                         view_bundling="true"/>
-        </config>        
+        </config>
       </attribute>
-      
-      <!-- JGroups stack configuration to use for the control channel - used for control messages -->         
-              
+
+      <!-- JGroups stack configuration to use for the control channel - used for control messages -->
+
       <!-- We use udp stack for the control channel -->
       <attribute name="ControlChannelConfig">
          <config>
@@ -234,24 +241,24 @@
             <pbcast.STATE_TRANSFER down_thread="false" up_thread="false" use_flush="true" flush_timeout="3000"/>
             <pbcast.FLUSH down_thread="false" up_thread="false" timeout="20000" auto_flush_conf="false"/>
         </config>
-     </attribute>   
+     </attribute>
    </mbean>
-   
+
    <!-- Messaging JMS User Manager MBean config
         ======================================= -->
-      
+
    <mbean code="org.jboss.jms.server.plugin.JDBCJMSUserManagerService"
       name="jboss.messaging:service=JMSUserManager"
       xmbean-dd="xmdesc/JMSUserManager-xmbean.xml">
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
 CREATE_USER_TABLE=CREATE TABLE JBM_USER (USER_ID VARCHAR2(32) NOT NULL, PASSWD VARCHAR2(32) NOT NULL, CLIENTID VARCHAR2(128), PRIMARY KEY(USER_ID))
 CREATE_ROLE_TABLE=CREATE TABLE JBM_ROLE (ROLE_ID VARCHAR2(32) NOT NULL, USER_ID VARCHAR2(32) NOT NULL, PRIMARY KEY(USER_ID, ROLE_ID))

Modified: branches/Branch_Stable/src/etc/server/default/deploy/postgresql-persistence-service.xml
===================================================================
--- branches/Branch_Stable/src/etc/server/default/deploy/postgresql-persistence-service.xml	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/etc/server/default/deploy/postgresql-persistence-service.xml	2008-02-20 21:44:11 UTC (rev 3748)
@@ -12,27 +12,31 @@
 
    <!-- Persistence Manager MBean configuration
        ======================================== -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.JDBCPersistenceManagerService"
       name="jboss.messaging:service=PersistenceManager"
       xmbean-dd="xmdesc/JDBCPersistenceManager-xmbean.xml">
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
+
       <!-- The datasource to use for the persistence manager -->
-                    
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-                  
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
-      <!-- If true then will use JDBC batch updates -->
-                  
-      <attribute name="UsingBatchUpdates">true</attribute>
-      
+
+      <!-- If true then we will automatically detect and reject duplicate messages sent during failover -->
+
+      <attribute name="DetectDuplicates">true</attribute>
+
+      <!-- The size of the id cache to use when detecting duplicate messages -->
+
+      <attribute name="IDCacheSize">500</attribute>
+
       <attribute name="SqlProperties"><![CDATA[
    CREATE_DUAL=CREATE TABLE JBM_DUAL (DUMMY INTEGER, PRIMARY KEY (DUMMY))
    CREATE_MESSAGE_REFERENCE=CREATE TABLE JBM_MSG_REF (MESSAGE_ID BIGINT, CHANNEL_ID BIGINT, TRANSACTION_ID BIGINT, STATE CHAR(1), ORD BIGINT, PAGE_ORD BIGINT, DELIVERY_COUNT INTEGER, SCHED_DELIVERY BIGINT, PRIMARY KEY(MESSAGE_ID, CHANNEL_ID))
@@ -41,9 +45,10 @@
    CREATE_IDX_MESSAGE_REF_PAGE_ORD=CREATE INDEX JBM_MSG_REF_PAGE_ORD ON JBM_MSG_REF (PAGE_ORD)
    CREATE_IDX_MESSAGE_REF_MESSAGE_ID=CREATE INDEX JBM_MSG_REF_MESSAGE_ID ON JBM_MSG_REF (MESSAGE_ID)
    CREATE_IDX_MESSAGE_REF_SCHED_DELIVERY=CREATE INDEX JBM_MSG_REF_SCHED_DELIVERY ON JBM_MSG_REF (SCHED_DELIVERY)
-   CREATE_MESSAGE=CREATE TABLE JBM_MSG (MESSAGE_ID BIGINT, RELIABLE CHAR(1), EXPIRATION BIGINT, TIMESTAMP BIGINT, PRIORITY SMALLINT, TYPE SMALLINT, HEADERS BYTEA, PAYLOAD BYTEA, PRIMARY KEY (MESSAGE_ID))   
+   CREATE_MESSAGE=CREATE TABLE JBM_MSG (MESSAGE_ID BIGINT, RELIABLE CHAR(1), EXPIRATION BIGINT, TIMESTAMP BIGINT, PRIORITY SMALLINT, TYPE SMALLINT, HEADERS BYTEA, PAYLOAD BYTEA, PRIMARY KEY (MESSAGE_ID))
    CREATE_TRANSACTION=CREATE TABLE JBM_TX (NODE_ID INTEGER, TRANSACTION_ID BIGINT, BRANCH_QUAL BYTEA, FORMAT_ID INTEGER, GLOBAL_TXID BYTEA, PRIMARY KEY (TRANSACTION_ID))
    CREATE_COUNTER=CREATE TABLE JBM_COUNTER (NAME VARCHAR(255), NEXT_ID BIGINT, PRIMARY KEY(NAME))
+   CREATE_ID_CACHE=CREATE TABLE JBM_ID_CACHE (NODE_ID INTEGER, CNTR INTEGER, JBM_ID VARCHAR(255), PRIMARY KEY(NODE_ID, CNTR))
    INSERT_DUAL=INSERT INTO JBM_DUAL VALUES (1)
    CHECK_DUAL=SELECT 1 FROM JBM_DUAL
    INSERT_MESSAGE_REF=INSERT INTO JBM_MSG_REF (CHANNEL_ID, MESSAGE_ID, TRANSACTION_ID, STATE, ORD, PAGE_ORD, DELIVERY_COUNT, SCHED_DELIVERY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -59,7 +64,6 @@
    LOAD_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, SCHED_DELIVERY FROM JBM_MSG_REF WHERE STATE = 'C' AND CHANNEL_ID = ? ORDER BY ORD
    UPDATE_REFS_NOT_PAGED=UPDATE JBM_MSG_REF SET PAGE_ORD = NULL WHERE PAGE_ORD BETWEEN ? AND ? AND CHANNEL_ID=?
    SELECT_MIN_MAX_PAGE_ORD=SELECT MIN(PAGE_ORD), MAX(PAGE_ORD) FROM JBM_MSG_REF WHERE CHANNEL_ID = ?
-   SELECT_EXISTS_REF_MESSAGE_ID=SELECT MESSAGE_ID FROM JBM_MSG_REF WHERE MESSAGE_ID = ?
    UPDATE_DELIVERY_COUNT=UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
    UPDATE_CHANNEL_ID=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE CHANNEL_ID = ?
    MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
@@ -67,9 +71,9 @@
    INSERT_MESSAGE=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    INSERT_MESSAGE_CONDITIONAL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE) SELECT ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    UPDATE_MESSAGE_4CONDITIONAL=UPDATE JBM_MSG SET HEADERS=?, PAYLOAD=? WHERE MESSAGE_ID=?
-   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)   
+   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    MESSAGE_ID_COLUMN=MESSAGE_ID
-   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)   
+   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)
    INSERT_TRANSACTION=INSERT INTO JBM_TX (NODE_ID, TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID) VALUES(?, ?, ?, ?, ?)
    DELETE_TRANSACTION=DELETE FROM JBM_TX WHERE NODE_ID = ? AND TRANSACTION_ID = ?
    SELECT_PREPARED_TRANSACTIONS=SELECT TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID FROM JBM_TX WHERE NODE_ID = ?
@@ -80,80 +84,83 @@
    INSERT_COUNTER=INSERT INTO JBM_COUNTER (NAME, NEXT_ID) VALUES (?, ?)
    SELECT_ALL_CHANNELS=SELECT DISTINCT(CHANNEL_ID) FROM JBM_MSG_REF
    UPDATE_TX=UPDATE JBM_TX SET NODE_ID=? WHERE NODE_ID=?
+   UPDATE_ID_IN_CACHE=UPDATE JBM_ID_CACHE SET JBM_ID = ? WHERE NODE_ID = ? AND CNTR = ?
+   INSERT_ID_IN_CACHE=INSERT INTO JBM_ID_CACHE (NODE_ID, CNTR, JBM_ID) VALUES (?, ?, ?)
+   LOAD_ID_CACHE=SELECT CNTR, JBM_ID FROM JBM_ID_CACHE WHERE NODE_ID = ?
       ]]></attribute>
-      
+
       <!-- The maximum number of parameters to include in a prepared statement -->
-                  
+
       <attribute name="MaxParams">500</attribute>
-      
+
    </mbean>
 
    <!-- Messaging Post Office MBean configuration
         ========================================= -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.MessagingPostOfficeService"
       name="jboss.messaging:service=PostOffice"
       xmbean-dd="xmdesc/MessagingPostOffice-xmbean.xml">
-      
+
       <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
-      <!-- The name of the post office -->      
-                  
+
+      <!-- The name of the post office -->
+
       <attribute name="PostOfficeName">JMS post office</attribute>
-      
-      <!-- The datasource used by the post office to access it's binding information -->                        
-      
+
+      <!-- The datasource used by the post office to access it's binding information -->
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
-      <!-- If true will attempt to create tables and indexes on every start-up -->              
-      
+
+      <!-- If true will attempt to create tables and indexes on every start-up -->
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
 CREATE_POSTOFFICE_TABLE=CREATE TABLE JBM_POSTOFFICE (POSTOFFICE_NAME VARCHAR(255), NODE_ID INTEGER, QUEUE_NAME VARCHAR(255), COND VARCHAR(1023), SELECTOR VARCHAR(1023), CHANNEL_ID BIGINT, CLUSTERED CHAR(1), ALL_NODES CHAR(1), PRIMARY KEY(POSTOFFICE_NAME, NODE_ID, QUEUE_NAME))
 INSERT_BINDING=INSERT INTO JBM_POSTOFFICE (POSTOFFICE_NAME, NODE_ID, QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
 DELETE_BINDING=DELETE FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=? AND QUEUE_NAME=?
 LOAD_BINDINGS=SELECT QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLUSTERED, ALL_NODES FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=?
       ]]></attribute>
-      
+
 	  <!-- This post office is clustered. If you don't want a clustered post office then set to false -->
-      
+
       <attribute name="Clustered">true</attribute>
-      
+
       <!-- All the remaining properties only have to be specified if the post office is clustered.
            You can safely comment them out if your post office is non clustered -->
-      
-      <!-- The JGroups group name that the post office will use -->          
-      
+
+      <!-- The JGroups group name that the post office will use -->
+
       <attribute name="GroupName">${jboss.messaging.groupname:MessagingPostOffice}</attribute>
-      
-      <!-- Max time to wait for state to arrive when the post office joins the cluster -->                        
-      
+
+      <!-- Max time to wait for state to arrive when the post office joins the cluster -->
+
       <attribute name="StateTimeout">30000</attribute>
-      
-      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->                        
-      
+
+      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->
+
       <attribute name="CastTimeout">30000</attribute>
-      
+
       <!-- Max number of concurrent replications -->
-      
+
       <attribute name="MaxConcurrentReplications">50</attribute>
-                  
-      <!-- 
-      <attribute name="ChannelFactoryName">jgroups.mux:name=Multiplexer</attribute>      
+
+      <!--
+      <attribute name="ChannelFactoryName">jgroups.mux:name=Multiplexer</attribute>
       <attribute name="ControlChannelName">udp-sync</attribute>
       <attribute name="DataChannelName">udp</attribute>
       <attribute name="ChannelPartitionName">${jboss.partition.name:DefaultPartition}-JMS</attribute>
       -->
-      
-      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->               
-      
-      <!-- By default we use the TCP stack for data -->                  
-      <attribute name="DataChannelConfig">      
+
+      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->
+
+      <!-- By default we use the TCP stack for data -->
+      <attribute name="DataChannelConfig">
          <config>
             <TCP start_port="7900"
                  loopback="true"
@@ -169,15 +176,15 @@
                  use_send_queues="false"
                  sock_conn_timeout="300"
                  skip_suspected_members="true"/>
-            <MPING timeout="4000"		     
+            <MPING timeout="4000"
 		         mcast_addr="${jboss.messaging.datachanneludpaddress:228.6.6.6}"
 		         mcast_port="${jboss.messaging.datachanneludpport:45567}"
 		         ip_ttl="${jboss.messaging.ipttl:8}"
 		         num_initial_members="2"
-		         num_ping_requests="1"/>                     
+		         num_ping_requests="1"/>
             <MERGE2 max_interval="100000"
                     down_thread="false" up_thread="false" min_interval="20000"/>
-            <FD_SOCK down_thread="false" up_thread="false"/>            
+            <FD_SOCK down_thread="false" up_thread="false"/>
             <VERIFY_SUSPECT timeout="1500" down_thread="false" up_thread="false"/>
             <pbcast.NAKACK max_xmit_size="60000"
                            use_mcast_xmit="false" gc_lag="0"
@@ -191,11 +198,11 @@
                         down_thread="false" up_thread="false"
                         join_retry_timeout="2000" shun="false"
                         view_bundling="true"/>
-        </config>        
+        </config>
       </attribute>
-      
-      <!-- JGroups stack configuration to use for the control channel - used for control messages -->         
-              
+
+      <!-- JGroups stack configuration to use for the control channel - used for control messages -->
+
       <!-- We use udp stack for the control channel -->
       <attribute name="ControlChannelConfig">
          <config>
@@ -241,12 +248,12 @@
             <pbcast.STATE_TRANSFER down_thread="false" up_thread="false" use_flush="true" flush_timeout="3000"/>
             <pbcast.FLUSH down_thread="false" up_thread="false" timeout="20000" auto_flush_conf="false"/>
         </config>
-     </attribute>	
+     </attribute>
    </mbean>
-   
+
    <!-- Messaging JMS User Manager MBean config
         ======================================= -->
-      
+
    <mbean code="org.jboss.jms.server.plugin.JDBCJMSUserManagerService"
       name="jboss.messaging:service=JMSUserManager"
       xmbean-dd="xmdesc/JMSUserManager-xmbean.xml">

Modified: branches/Branch_Stable/src/etc/server/default/deploy/sybase-persistence-service.xml
===================================================================
--- branches/Branch_Stable/src/etc/server/default/deploy/sybase-persistence-service.xml	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/etc/server/default/deploy/sybase-persistence-service.xml	2008-02-20 21:44:11 UTC (rev 3748)
@@ -11,33 +11,37 @@
 <server>
 
    <!-- Persistence Manager MBean configuration
-       ======================================== -->   
+       ======================================== -->
 
    <mbean code="org.jboss.messaging.core.jmx.JDBCPersistenceManagerService"
       name="jboss.messaging:service=PersistenceManager"
       xmbean-dd="xmdesc/JDBCPersistenceManager-xmbean.xml">
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-            
+
       <!-- The datasource to use for the persistence manager -->
-                                
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-                  
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
-      <!-- If true then will use JDBC batch updates -->
-                  
-      <attribute name="UsingBatchUpdates">true</attribute>
-      
+
+      <!-- If true then we will automatically detect and reject duplicate messages sent during failover -->
+
+      <attribute name="DetectDuplicates">true</attribute>
+
+      <!-- The size of the id cache to use when detecting duplicate messages -->
+
+      <attribute name="IDCacheSize">500</attribute>
+
       <!-- If true then will add a trailing byte to all byte arrays otherwise Sybase truncates them
            Only known to be necessary for Sybase -->
-                  
+
       <attribute name="UsingTrailingByte">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
    CREATE_DUAL=CREATE TABLE JBM_DUAL (DUAL_DUMMY INTEGER, PRIMARY KEY (DUAL_DUMMY))
    CREATE_MESSAGE_REFERENCE=CREATE TABLE JBM_MSG_REF (MESSAGE_ID DECIMAL(19, 0), CHANNEL_ID DECIMAL(19, 0), TRANSACTION_ID DECIMAL(19, 0) NULL, STATE CHAR(1), ORD DECIMAL(19, 0), PAGE_ORD DECIMAL(19, 0) NULL, DELIVERY_COUNT INTEGER, SCHED_DELIVERY DECIMAL(19, 0), PRIMARY KEY(MESSAGE_ID, CHANNEL_ID))
@@ -49,6 +53,7 @@
    CREATE_MESSAGE=CREATE TABLE JBM_MSG (MESSAGE_ID DECIMAL(19, 0), RELIABLE CHAR(1), EXPIRATION DECIMAL(19, 0), TIMESTAMP DECIMAL(19, 0), PRIORITY TINYINT, TYPE TINYINT, HEADERS IMAGE NULL, PAYLOAD IMAGE NULL, PRIMARY KEY (MESSAGE_ID))
    CREATE_TRANSACTION=CREATE TABLE JBM_TX (NODE_ID INTEGER, TRANSACTION_ID DECIMAL(19, 0), BRANCH_QUAL VARBINARY(254) NULL, FORMAT_ID INTEGER NULL, GLOBAL_TXID VARBINARY(254) NULL, PRIMARY KEY (TRANSACTION_ID))
    CREATE_COUNTER=CREATE TABLE JBM_COUNTER (NAME VARCHAR(255), NEXT_ID DECIMAL(19, 0), PRIMARY KEY(NAME))
+   CREATE_ID_CACHE=CREATE TABLE JBM_ID_CACHE (NODE_ID INTEGER, CNTR INTEGER, JBM_ID VARCHAR(255), PRIMARY KEY(NODE_ID, CNTR))
    INSERT_DUAL=INSERT INTO JBM_DUAL VALUES (1)
    CHECK_DUAL=SELECT 1 FROM JBM_DUAL
    INSERT_MESSAGE_REF=INSERT INTO JBM_MSG_REF (CHANNEL_ID, MESSAGE_ID, TRANSACTION_ID, STATE, ORD, PAGE_ORD, DELIVERY_COUNT, SCHED_DELIVERY) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -64,17 +69,16 @@
    LOAD_REFS=SELECT MESSAGE_ID, DELIVERY_COUNT, SCHED_DELIVERY FROM JBM_MSG_REF WHERE STATE = 'C' AND CHANNEL_ID = ? ORDER BY ORD
    UPDATE_REFS_NOT_PAGED=UPDATE JBM_MSG_REF SET PAGE_ORD = NULL WHERE PAGE_ORD BETWEEN ? AND ? AND CHANNEL_ID=?
    SELECT_MIN_MAX_PAGE_ORD=SELECT MIN(PAGE_ORD), MAX(PAGE_ORD) FROM JBM_MSG_REF WHERE CHANNEL_ID = ?
-   SELECT_EXISTS_REF_MESSAGE_ID=SELECT MESSAGE_ID FROM JBM_MSG_REF WHERE MESSAGE_ID = ?
    UPDATE_DELIVERY_COUNT=UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
    UPDATE_CHANNEL_ID=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE CHANNEL_ID = ?
-   MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ? 
+   MOVE_REFERENCE=UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?
    LOAD_MESSAGES=SELECT MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, HEADERS, PAYLOAD, TYPE FROM JBM_MSG
    INSERT_MESSAGE=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    INSERT_MESSAGE_CONDITIONAL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE) SELECT ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
    UPDATE_MESSAGE_4CONDITIONAL=UPDATE JBM_MSG SET HEADERS=?, PAYLOAD=? WHERE MESSAGE_ID=?
-   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)   
-   MESSAGE_ID_COLUMN=MESSAGE_ID   
-   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)   
+   INSERT_MESSAGE_CONDITIONAL_FULL=INSERT INTO JBM_MSG (MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, PRIORITY, TYPE, HEADERS, PAYLOAD) SELECT ?, ?, ?, ?, ?, ?, ?, ? FROM JBM_DUAL WHERE NOT EXISTS (SELECT MESSAGE_ID FROM JBM_MSG WHERE MESSAGE_ID = ?)
+   MESSAGE_ID_COLUMN=MESSAGE_ID
+   DELETE_MESSAGE=DELETE FROM JBM_MSG WHERE MESSAGE_ID = ? AND NOT EXISTS (SELECT JBM_MSG_REF.MESSAGE_ID FROM JBM_MSG_REF WHERE JBM_MSG_REF.MESSAGE_ID = ?)
    INSERT_TRANSACTION=INSERT INTO JBM_TX (NODE_ID, TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID) VALUES(?, ?, ?, ?, ?)
    DELETE_TRANSACTION=DELETE FROM JBM_TX WHERE NODE_ID = ? AND TRANSACTION_ID = ?
    SELECT_PREPARED_TRANSACTIONS=SELECT TRANSACTION_ID, BRANCH_QUAL, FORMAT_ID, GLOBAL_TXID FROM JBM_TX WHERE NODE_ID = ?
@@ -85,69 +89,72 @@
    INSERT_COUNTER=INSERT INTO JBM_COUNTER (NAME, NEXT_ID) VALUES (?, ?)
    SELECT_ALL_CHANNELS=SELECT DISTINCT(CHANNEL_ID) FROM JBM_MSG_REF
    UPDATE_TX=UPDATE JBM_TX SET NODE_ID=? WHERE NODE_ID=?
+   UPDATE_ID_IN_CACHE=UPDATE JBM_ID_CACHE SET JBM_ID = ? WHERE NODE_ID = ? AND CNTR = ?
+   INSERT_ID_IN_CACHE=INSERT INTO JBM_ID_CACHE (NODE_ID, CNTR, JBM_ID) VALUES (?, ?, ?)
+   LOAD_ID_CACHE=SELECT CNTR, JBM_ID FROM JBM_ID_CACHE WHERE NODE_ID = ?
       ]]></attribute>
-      
+
       <!-- The maximum number of parameters to include in a prepared statement -->
-                  
+
       <attribute name="MaxParams">500</attribute>
-      
+
    </mbean>
 
    <!-- Messaging Post Office MBean configuration
         ========================================= -->
-   
+
    <mbean code="org.jboss.messaging.core.jmx.MessagingPostOfficeService"
       name="jboss.messaging:service=PostOffice"
       xmbean-dd="xmdesc/MessagingPostOffice-xmbean.xml">
-      
+
       <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
-      
+
       <depends>jboss.jca:service=DataSourceBinding,name=DefaultDS</depends>
-      
+
       <depends optional-attribute-name="TransactionManager">jboss:service=TransactionManager</depends>
-      
-      <!-- The name of the post office -->      
-                  
+
+      <!-- The name of the post office -->
+
       <attribute name="PostOfficeName">JMS post office</attribute>
-      
-      <!-- The datasource used by the post office to access it's binding information -->                              
-      
+
+      <!-- The datasource used by the post office to access it's binding information -->
+
       <attribute name="DataSource">java:/DefaultDS</attribute>
-      
+
       <!-- If true will attempt to create tables and indexes on every start-up -->
-                        
+
       <attribute name="CreateTablesOnStartup">true</attribute>
-      
+
       <attribute name="SqlProperties"><![CDATA[
 CREATE_POSTOFFICE_TABLE=CREATE TABLE JBM_POSTOFFICE (POSTOFFICE_NAME VARCHAR(255), NODE_ID SMALLINT, QUEUE_NAME VARCHAR(255), COND VARCHAR(1023), SELECTOR VARCHAR(1023) NULL, CHANNEL_ID INTEGER, CLSTERED CHAR(1), ALL_NODES CHAR(1), PRIMARY KEY(POSTOFFICE_NAME, NODE_ID, QUEUE_NAME))
 INSERT_BINDING=INSERT INTO JBM_POSTOFFICE (POSTOFFICE_NAME, NODE_ID, QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLSTERED, ALL_NODES) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
 DELETE_BINDING=DELETE FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=? AND QUEUE_NAME=?
 LOAD_BINDINGS=SELECT QUEUE_NAME, COND, SELECTOR, CHANNEL_ID, CLSTERED, ALL_NODES FROM JBM_POSTOFFICE WHERE POSTOFFICE_NAME=? AND NODE_ID=?
       ]]></attribute>
-      
+
 	  <!-- This post office is clustered. If you don't want a clustered post office then set to false -->
-      
+
       <attribute name="Clustered">true</attribute>
-      
+
       <!-- All the remaining properties only have to be specified if the post office is clustered.
            You can safely comment them out if your post office is non clustered -->
-      
-      <!-- The JGroups group name that the post office will use -->         
-      
+
+      <!-- The JGroups group name that the post office will use -->
+
       <attribute name="GroupName">${jboss.messaging.groupname:MessagingPostOffice}</attribute>
-     
-      <!-- Max time to wait for state to arrive when the post office joins the cluster -->            
-                  
+
+      <!-- Max time to wait for state to arrive when the post office joins the cluster -->
+
       <attribute name="StateTimeout">30000</attribute>
-      
-      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->            
-                  
+
+      <!-- Max time to wait for a synchronous call to node members using the MessageDispatcher -->
+
       <attribute name="CastTimeout">30000</attribute>
-      
-      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->               
-      
-      <!-- By default we use the TCP stack for data -->                  
-      <attribute name="DataChannelConfig">      
+
+      <!-- JGroups stack configuration for the data channel - used for sending data across the cluster -->
+
+      <!-- By default we use the TCP stack for data -->
+      <attribute name="DataChannelConfig">
          <config>
             <TCP start_port="7900"
                  loopback="true"
@@ -163,15 +170,15 @@
                  use_send_queues="false"
                  sock_conn_timeout="300"
                  skip_suspected_members="true"/>
-            <MPING timeout="4000"		
+            <MPING timeout="4000"
 		         mcast_addr="${jboss.messaging.datachanneludpaddress:228.6.6.6}"
 		         mcast_port="${jboss.messaging.datachanneludpport:45567}"
 		         ip_ttl="${jboss.messaging.ipttl:8}"
 		         num_initial_members="2"
-		         num_ping_requests="1"/>                     
+		         num_ping_requests="1"/>
             <MERGE2 max_interval="100000"
                     down_thread="false" up_thread="false" min_interval="20000"/>
-            <FD_SOCK down_thread="false" up_thread="false"/>            
+            <FD_SOCK down_thread="false" up_thread="false"/>
             <VERIFY_SUSPECT timeout="1500" down_thread="false" up_thread="false"/>
             <pbcast.NAKACK max_xmit_size="60000"
                            use_mcast_xmit="false" gc_lag="0"
@@ -185,11 +192,11 @@
                         down_thread="false" up_thread="false"
                         join_retry_timeout="2000" shun="false"
                         view_bundling="true"/>
-        </config>        
+        </config>
       </attribute>
-      
-      <!-- JGroups stack configuration to use for the control channel - used for control messages -->         
-              
+
+      <!-- JGroups stack configuration to use for the control channel - used for control messages -->
+
       <!-- We use udp stack for the control channel -->
       <attribute name="ControlChannelConfig">
          <config>
@@ -235,12 +242,12 @@
             <pbcast.STATE_TRANSFER down_thread="false" up_thread="false" use_flush="true" flush_timeout="3000"/>
             <pbcast.FLUSH down_thread="false" up_thread="false" timeout="20000" auto_flush_conf="false"/>
         </config>
-     </attribute>	
+     </attribute>
    </mbean>
-   
+
    <!-- Messaging JMS User Manager MBean config
         ======================================= -->
-      
+
    <mbean code="org.jboss.jms.server.plugin.JDBCJMSUserManagerService"
       name="jboss.messaging:service=JMSUserManager"
       xmbean-dd="xmdesc/JMSUserManager-xmbean.xml">

Modified: branches/Branch_Stable/src/etc/xmdesc/JDBCPersistenceManager-xmbean.xml
===================================================================
--- branches/Branch_Stable/src/etc/xmdesc/JDBCPersistenceManager-xmbean.xml	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/etc/xmdesc/JDBCPersistenceManager-xmbean.xml	2008-02-20 21:44:11 UTC (rev 3748)
@@ -28,49 +28,61 @@
       <name>TransactionManager</name>
       <type>javax.management.ObjectName</type>
    </attribute>
-     
+
    <attribute access="read-write" getMethod="isCreateTablesOnStartup" setMethod="setCreateTablesOnStartup">
       <description>Should database tables be created on startup?</description>
       <name>CreateTablesOnStartup</name>
       <type>boolean</type>
    </attribute>
-   
+
    <attribute access="read-write" getMethod="isUsingBatchUpdates" setMethod="setUsingBatchUpdates">
       <description>Should JDBC batch updates be used?</description>
       <name>UsingBatchUpdates</name>
       <type>boolean</type>
-   </attribute>  
-   
+   </attribute>
+
    <attribute access="read-write" getMethod="isUsingBinaryStream" setMethod="setUsingBinaryStream">
       <description>Should binary stream be used for accessing message headers / body ?</description>
       <name>UsingBinaryStream</name>
       <type>boolean</type>
-   </attribute>    
-   
+   </attribute>
+
    <attribute access="read-write" getMethod="isUsingTrailingByte" setMethod="setUsingTrailingByte">
       <description>Should a trailing byte be added to VARBINARY columns - this would be true for databases such as Sybase which would otherwise truncate trailing zeros</description>
       <name>UsingTrailingByte</name>
       <type>boolean</type>
-   </attribute>    
-   
+   </attribute>
+
    <attribute access="read-write" getMethod="getSqlProperties" setMethod="setSqlProperties">
       <description>DML and DDL overrides</description>
       <name>SqlProperties</name>
       <type>java.lang.String</type>
-   </attribute>    
-   
+   </attribute>
+
    <attribute access="read-write" getMethod="getMaxParams" setMethod="setMaxParams">
       <description>The max number of params to be used in a generated PreparedStatement</description>
       <name>MaxParams</name>
       <type>int</type>
-   </attribute> 
-   
+   </attribute>
+
    <attribute access="read-write" getMethod="isSupportsBlobOnSelect" setMethod="setSupportsBlobOnSelect">
       <description>Some databases don't support binding blobs on select clauses</description>
       <name>SupportsBlobOnSelect</name>
       <type>boolean</type>
-   </attribute>     
+   </attribute>
 
+   <attribute access="read-write" getMethod="isDetectDuplicates" setMethod="setDetectDuplicates">
+      <description>Detect duplicate message sends on failover? There is some performance hit for doing this</description>
+      <name>DetectDuplicates</name>
+      <type>boolean</type>
+   </attribute>
+
+   <attribute access="read-write" getMethod="getIDCacheSize" setMethod="setIDCacheSize">
+      <description>The ID cache size to use when detecting duplicate message sends</description>
+      <name>IDCacheSize</name>
+      <type>int</type>
+   </attribute>
+
    <!-- Managed operations -->
 
    <operation>

Modified: branches/Branch_Stable/src/main/org/jboss/jms/client/container/ConnectionAspect.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/client/container/ConnectionAspect.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/client/container/ConnectionAspect.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -32,7 +32,6 @@
 import org.jboss.jms.client.remoting.ConsolidatedRemotingConnectionListener;
 import org.jboss.jms.client.remoting.JMSRemotingConnection;
 import org.jboss.jms.client.state.ConnectionState;
-import org.jboss.jms.message.MessageIdGeneratorFactory;
 import org.jboss.jms.tx.ResourceManagerFactory;
 
 /**
@@ -190,9 +189,6 @@
 	      // Finished with the connection - we need to shutdown callback server
 	      remotingConnection.stop();
 	       
-	      // Remove reference to message ID generator
-	      MessageIdGeneratorFactory.instance.checkInGenerator(state.getServerID());
-	      
 	      // And to resource manager
 	      ResourceManagerFactory.instance.checkInResourceManager(state.getServerID());
    	}

Modified: branches/Branch_Stable/src/main/org/jboss/jms/client/container/ProducerAspect.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/client/container/ProducerAspect.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/client/container/ProducerAspect.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -21,6 +21,8 @@
   */
 package org.jboss.jms.client.container;
 
+import java.util.UUID;
+
 import javax.jms.BytesMessage;
 import javax.jms.Destination;
 import javax.jms.InvalidDestinationException;
@@ -184,8 +186,6 @@
       // Generate the message id
       ConnectionState connectionState = (ConnectionState)sessionState.getParent();
 
-      long id = -1;
-
       JBossMessage messageToSend;
       boolean foreign = false;
 
@@ -240,15 +240,6 @@
 
          m.setJMSDestination(destination);
          
-         if (keepID)
-         {
-            id = proxy.getMessage().getMessageID();
-         }
-
-         //The following line executed on the proxy should cause a copy to occur
-         //if it is necessary
-         proxy.setJMSMessageID(null);
-
          //Get the underlying message
          messageToSend = proxy.getMessage();
 
@@ -259,11 +250,11 @@
 
       if (!keepID)
       {
-         id = connectionState.getIdGenerator().getId((ConnectionDelegate)connectionState.getDelegate());
+         String id = "ID:JBM-" + UUID.randomUUID().toString();
+         
+         messageToSend.setJMSMessageID(id);
       }
       
-      messageToSend.setMessageId(id);
-            
       // This only really used for BytesMessages and StreamMessages to reset their state
       messageToSend.doBeforeSend(); 
       

Modified: branches/Branch_Stable/src/main/org/jboss/jms/client/container/StateCreationAspect.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/client/container/StateCreationAspect.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/client/container/StateCreationAspect.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -42,8 +42,6 @@
 import org.jboss.jms.delegate.CreateConnectionResult;
 import org.jboss.jms.delegate.ProducerDelegate;
 import org.jboss.jms.destination.JBossDestination;
-import org.jboss.jms.message.MessageIdGenerator;
-import org.jboss.jms.message.MessageIdGeneratorFactory;
 import org.jboss.logging.Logger;
 import org.jboss.messaging.util.Version;
 
@@ -107,13 +105,9 @@
             throw new IllegalStateException("Connection version is null");
          }
 
-         // We have one message id generator per unique server
-         MessageIdGenerator idGenerator =
-            MessageIdGeneratorFactory.instance.checkOutGenerator(serverID);
-
          ConnectionState connectionState =
             new ConnectionState(serverID, connectionDelegate,
-                                remotingConnection, versionToUse, idGenerator);
+                                remotingConnection, versionToUse);
 
          listener.setConnectionState(connectionState);
           

Modified: branches/Branch_Stable/src/main/org/jboss/jms/client/state/ConnectionState.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/client/state/ConnectionState.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/client/state/ConnectionState.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -31,7 +31,6 @@
 import org.jboss.jms.client.remoting.JMSRemotingConnection;
 import org.jboss.jms.delegate.ConnectionDelegate;
 import org.jboss.jms.delegate.ConnectionFactoryDelegate;
-import org.jboss.jms.message.MessageIdGenerator;
 import org.jboss.jms.tx.ResourceManager;
 import org.jboss.jms.tx.ResourceManagerFactory;
 import org.jboss.logging.Logger;
@@ -75,7 +74,6 @@
 
    private JMSRemotingConnection remotingConnection;
    private ResourceManager resourceManager;
-   private MessageIdGenerator idGenerator;
 
    // Cached by the connection state in case ClusteringAspect needs to re-try establishing
    // connection on a different node
@@ -94,8 +92,7 @@
 
    public ConnectionState(int serverID, ConnectionDelegate delegate,
                           JMSRemotingConnection remotingConnection,
-                          Version versionToUse,
-                          MessageIdGenerator gen)
+                          Version versionToUse)
       throws Exception
    {
       super(null, (DelegateSupport)delegate);
@@ -112,7 +109,6 @@
       // to per connection.
       this.resourceManager = ResourceManagerFactory.instance.checkOutResourceManager(serverID);
 
-      this.idGenerator = gen;
       this.serverID = serverID;
    }
 
@@ -149,7 +145,6 @@
       ConnectionState newState = (ConnectionState)ns;
 
       remotingConnection = newState.remotingConnection;
-      idGenerator = newState.idGenerator;
       serverID = newState.serverID;
       versionToUse = newState.versionToUse;
 
@@ -186,11 +181,6 @@
       return resourceManager;
    }
 
-   public MessageIdGenerator getIdGenerator()
-   {
-      return idGenerator;
-   }
-
    public JMSRemotingConnection getRemotingConnection()
    {
       return remotingConnection;

Modified: branches/Branch_Stable/src/main/org/jboss/jms/message/JBossMessage.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/message/JBossMessage.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/message/JBossMessage.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -278,8 +278,6 @@
 
    protected transient String connectionID;
    
-   protected transient String jmsMessageID;
-   
    //Optimisation - we could just store this as a header like everything else - but we store
    //As an attribute so we can prevent an extra lookup on the server
    private long scheduledDeliveryTime;
@@ -381,19 +379,7 @@
    
    public String getJMSMessageID()
    {
-      if (jmsMessageID == null)
-      {
-         String headerID = (String)headers.get(JBM_MESSAGE_ID);
-         if (headerID == null)
-         {
-            jmsMessageID = "ID:JBM-" + messageID;
-         }
-         else
-         {
-            jmsMessageID = headerID;
-         }
-      }
-      return jmsMessageID;
+      return (String)headers.get(JBM_MESSAGE_ID);
    }
 
    public void setJMSMessageID(String jmsMessageID) throws JMSException
@@ -402,15 +388,7 @@
       {
          throw new JMSException("JMSMessageID must start with ID:");
       }
-      if (jmsMessageID == null)
-      {
-         headers.remove(JBM_MESSAGE_ID);
-      }
-      else
-      {
-         headers.put(JBM_MESSAGE_ID, jmsMessageID);
-      }
-      this.jmsMessageID = jmsMessageID;
+      headers.put(JBM_MESSAGE_ID, jmsMessageID);
    }
 
    public long getJMSTimestamp() throws JMSException

Deleted: branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGenerator.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGenerator.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGenerator.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -1,99 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2005, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.jms.message;
-
-import javax.jms.JMSException;
-
-import org.jboss.jms.delegate.ConnectionEndpoint;
-import org.jboss.jms.delegate.IDBlock;
-import org.jboss.logging.Logger;
-
-/**
- * 
- * A MessageIdGenerator.
- * 
- * @author <a href="tim.fox at jboss.com">Tim Fox</a>
- * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
- * @version <tt>$Revision$</tt>
- *
- * $Id$
- */
-public class MessageIdGenerator
-{
-   // Constants -----------------------------------------------------
-
-   private static final Logger log = Logger.getLogger(MessageIdGenerator.class);
-
-   // Static --------------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   private boolean trace = log.isTraceEnabled();
-
-   protected long high = -1;
-   protected long nextID;
-   protected int blockSize;
-
-   // Constructors --------------------------------------------------
-
-   public MessageIdGenerator(int blockSize)  throws JMSException
-   {
-      this.blockSize = blockSize;
-   }
-
-   // Public --------------------------------------------------------
-
-   protected void getNextBlock(ConnectionEndpoint connection) throws JMSException
-   {
-      IDBlock block = connection.getIdBlock(blockSize);
-
-      nextID = block.getLow();
-      high = block.getHigh();
-
-      if (trace) { log.trace("Got block of IDs from server, low=" + nextID + " high=" + high); }
-   }
-
-   public synchronized long getId(ConnectionEndpoint connection) throws JMSException
-   {
-      if (nextID == high + 1)
-      {
-         getNextBlock(connection);
-      }
-
-      long id = nextID;
-      
-      if (log.isTraceEnabled()) { log.trace("Getting next message id=" + id); }
-      
-      nextID++;
-
-      return id;
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-   
-}

Deleted: branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGeneratorFactory.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGeneratorFactory.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/message/MessageIdGeneratorFactory.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -1,145 +0,0 @@
-/*
-  * JBoss, Home of Professional Open Source
-  * Copyright 2005, JBoss Inc., and individual contributors as indicated
-  * by the @authors tag. See the copyright.txt in the distribution for a
-  * full listing of individual contributors.
-  *
-  * This is free software; you can redistribute it and/or modify it
-  * under the terms of the GNU Lesser General Public License as
-  * published by the Free Software Foundation; either version 2.1 of
-  * the License, or (at your option) any later version.
-  *
-  * This software is distributed in the hope that it will be useful,
-  * but WITHOUT ANY WARRANTY; without even the implied warranty of
-  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  * Lesser General Public License for more details.
-  *
-  * You should have received a copy of the GNU Lesser General Public
-  * License along with this software; if not, write to the Free
-  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-  */
-package org.jboss.jms.message;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.jms.JMSException;
-
-import org.jboss.logging.Logger;
-
-/**
- * This class manages instances of MessageIdGenerator. It ensures there is one instance per instance
- * of JMS server as specified by the server id.
- *
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * @version <tt>$Revision$</tt>
- *
- * $Id$
- */
-public class MessageIdGeneratorFactory
-{
-   // Constants -----------------------------------------------------
-
-   private static final Logger log = Logger.getLogger(MessageIdGeneratorFactory.class);
-
-   public static MessageIdGeneratorFactory instance = new MessageIdGeneratorFactory();
-
-   //TODO Make configurable
-   private static final int BLOCK_SIZE = 512;
-
-   // Static --------------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   private Map holders;
-
-   // Constructors --------------------------------------------------
-
-   private MessageIdGeneratorFactory()
-   {
-      holders = new HashMap();
-   }
-
-   // Public --------------------------------------------------------
-
-   public synchronized boolean containsMessageIdGenerator(int serverId)
-   {
-      return holders.containsKey(new Integer(serverId));
-   }
-
-   public synchronized MessageIdGenerator checkOutGenerator(int serverId)
-      throws JMSException
-   {
-      Integer in = new Integer(serverId);
-      
-      Holder h = (Holder)holders.get(in);
-
-      if (h == null)
-      {
-         h = new Holder(new MessageIdGenerator(BLOCK_SIZE));
-         holders.put(in, h);
-      }
-      else
-      {
-         h.refCount++;
-      }
-
-      log.trace("checked out MessageIdGenerator for " + serverId +
-                ", reference count is " + h.refCount);
-
-      return h.generator;
-   }
-
-   public synchronized void checkInGenerator(int serverId)
-   {
-      Integer in = new Integer(serverId);
-      
-      Holder h = (Holder)holders.get(in);
-
-      if (h == null)
-      {
-         throw new IllegalArgumentException("Cannot find generator for serverid:" + serverId);
-      }
-
-      h.refCount--;
-
-      if (h.refCount == 0)
-      {
-         holders.remove(in);
-         log.trace("checked in and removed MessageIdGenerator for " + serverId);
-      }
-      else
-      {
-         log.trace("checked in MessageIdGenerator for " + serverId +
-                   ", reference count is " + h.refCount);
-      }
-   }
-
-   public synchronized void clear()
-   {
-      holders.clear();
-      log.trace("cleared MessageIdGeneratorFactory");
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-
-   private class Holder
-   {
-      private Holder(MessageIdGenerator gen)
-      {
-         this.generator = gen;
-      }
-
-      MessageIdGenerator generator;
-
-      int refCount = 1;
-   }
-
-}

Modified: branches/Branch_Stable/src/main/org/jboss/jms/server/ServerPeer.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/server/ServerPeer.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/server/ServerPeer.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -21,7 +21,28 @@
   */
 package org.jboss.jms.server;
 
-import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap;
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayWriter;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import javax.management.Attribute;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.transaction.xa.Xid;
+
 import org.jboss.aop.AspectXmlLoader;
 import org.jboss.jms.server.connectionfactory.ConnectionFactoryJNDIMapper;
 import org.jboss.jms.server.connectionmanager.SimpleConnectionManager;
@@ -36,12 +57,19 @@
 import org.jboss.jms.server.security.SecurityMetadataStore;
 import org.jboss.jms.wireformat.JMSWireFormat;
 import org.jboss.logging.Logger;
-import org.jboss.messaging.core.contract.*;
+import org.jboss.messaging.core.contract.Binding;
+import org.jboss.messaging.core.contract.ClusterNotifier;
+import org.jboss.messaging.core.contract.MemoryManager;
+import org.jboss.messaging.core.contract.MessageStore;
+import org.jboss.messaging.core.contract.PersistenceManager;
+import org.jboss.messaging.core.contract.PostOffice;
 import org.jboss.messaging.core.contract.Queue;
+import org.jboss.messaging.core.contract.Replicator;
 import org.jboss.messaging.core.impl.DefaultClusterNotifier;
 import org.jboss.messaging.core.impl.FailoverWaiter;
 import org.jboss.messaging.core.impl.IDManager;
 import org.jboss.messaging.core.impl.JDBCPersistenceManager;
+import org.jboss.messaging.core.impl.RotatingID;
 import org.jboss.messaging.core.impl.clusterconnection.ClusterConnectionManager;
 import org.jboss.messaging.core.impl.memory.SimpleMemoryManager;
 import org.jboss.messaging.core.impl.message.SimpleMessageStore;
@@ -57,18 +85,7 @@
 import org.jboss.util.JBossStringBuilder;
 import org.w3c.dom.Element;
 
-import javax.management.Attribute;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.transaction.xa.Xid;
-import java.io.ByteArrayOutputStream;
-import java.io.CharArrayWriter;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.util.*;
+import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap;
 
 /**
  * A JMS server peer.
@@ -77,7 +94,7 @@
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @author <a href="mailto:juha at jboss.org">Juha Lindfors</a>
  * @author <a href="mailto:aslak at conduct.no">Aslak Knutsen</a>
- * 
+ *
  * @version <tt>$Revision$</tt>
  *
  * $Id$
@@ -113,26 +130,26 @@
 
    // Default is 1 minute
    private long failoverStartTimeout = 60 * 1000;
-   
+
    // Default is 5 minutes
    private long failoverCompleteTimeout = 5 * 60 * 1000;
-   
+
    private Map sessions;
-   
+
    private long defaultRedeliveryDelay;
-   
+
    private long messageCounterSamplePeriod = 10000;
-   
+
    private int defaultMessageCounterHistoryDayLimit;
-   
+
    private String clusterPullConnectionFactoryName;
-   
+
    private boolean useXAForMessagePull;
-   
+
    private boolean defaultPreserveOrdering;
-   
+
    private long recoverDeliveriesTimeout = 5 * 60 * 1000;
-   
+
    private String suckerPassword = SecurityMetadataStore.DEFAULT_SUCKER_USER_PASSWORD;
 
    /** The server aop xml configuration */
@@ -142,10 +159,10 @@
 
    //Global override for strict behaviour
    private boolean strictTck;
-   
+
    //From a system property - this overrides
    private boolean strictTckProperty;
-        
+
    // wired components
 
    private DestinationJNDIMapper destinationJNDIMapper;
@@ -156,13 +173,13 @@
    private ConnectorManager connectorManager;
    private IDManager messageIDManager;
    private IDManager channelIDManager;
-   private IDManager transactionIDManager;
-   private MemoryManager memoryManager;  
+   private MemoryManager memoryManager;
    private MessageStore messageStore;
    private MessageCounterManager messageCounterManager;
    private ClusterConnectionManager clusterConnectionManager;
    private ClusterNotifier clusterNotifier;
-   private FailoverWaiter failoverWaiter;   
+   private FailoverWaiter failoverWaiter;
+   private RotatingID messageIDMgr;
 
    // plugins
 
@@ -174,10 +191,10 @@
 
    protected ObjectName jmsUserManagerObjectName;
    protected JMSUserManager jmsUserManager;
-   
+
    protected ObjectName defaultDLQObjectName;
    protected Queue defaultDLQ;
-   
+
    protected ObjectName defaultExpiryQueueObjectName;
    protected Queue defaultExpiryQueue;
 
@@ -186,7 +203,7 @@
    {
       // Some wired components need to be started here
       version = Version.instance();
-      
+
       sessions = new ConcurrentReaderHashMap();
 
       started = false;
@@ -204,7 +221,7 @@
          {
             return;
          }
-         
+
          if (serverPeerID < 0)
          {
             throw new IllegalStateException("ServerPeerID not set");
@@ -228,29 +245,29 @@
          jmsUserManager = (JMSUserManager)JMXAccessor.getJMXAttributeOverSecurity(mbeanServer, jmsUserManagerObjectName, "Instance");
 
          strictTckProperty = "true".equalsIgnoreCase(System.getProperty("jboss.messaging.stricttck"));
-         
+
          // We get references to some plugins lazily to avoid problems with circular MBean
          // dependencies
 
          // Create the wired components
          messageIDManager = new IDManager("MESSAGE_ID", 4096, persistenceManager);
          channelIDManager = new IDManager("CHANNEL_ID", 10, persistenceManager);
-         transactionIDManager = new IDManager("TRANSACTION_ID", 1024, persistenceManager);
          destinationJNDIMapper = new DestinationJNDIMapper(this);
          connFactoryJNDIMapper = new ConnectionFactoryJNDIMapper(this);
-         connectionManager = new SimpleConnectionManager();         
+         connectionManager = new SimpleConnectionManager();
          connectorManager = new SimpleConnectorManager();
          memoryManager = new SimpleMemoryManager();
          messageStore = new SimpleMessageStore();
+         messageIDMgr = new RotatingID(serverPeerID);
          txRepository =
-            new TransactionRepository(persistenceManager, messageStore, transactionIDManager);
+            new TransactionRepository(persistenceManager, messageStore, serverPeerID);
          messageCounterManager = new MessageCounterManager(messageCounterSamplePeriod);
-                
-         clusterNotifier = new DefaultClusterNotifier();      
+
+         clusterNotifier = new DefaultClusterNotifier();
          clusterNotifier.registerListener(connectionManager);
          clusterNotifier.registerListener(connFactoryJNDIMapper);
          failoverWaiter = new FailoverWaiter(serverPeerID, failoverStartTimeout, failoverCompleteTimeout, txRepository);
-         clusterNotifier.registerListener(failoverWaiter);         
+         clusterNotifier.registerListener(failoverWaiter);
 
          // Allow the securityStore to default to the SecurityMetadataStore impl
          if (securityStore == null)
@@ -263,7 +280,7 @@
          if (suckerPassword == null)
       	{
          	suckerPassword = SecurityMetadataStore.DEFAULT_SUCKER_USER_PASSWORD;
-      	}   
+      	}
          if (clusterPullConnectionFactoryName != null)
          {
 	         clusterConnectionManager = new ClusterConnectionManager(useXAForMessagePull, serverPeerID,
@@ -271,12 +288,11 @@
 	         		                                                  SecurityStore.SUCKER_USER, suckerPassword);
 	         clusterNotifier.registerListener(clusterConnectionManager);
          }
-         
+
          // Start the wired components
 
          messageIDManager.start();
          channelIDManager.start();
-         transactionIDManager.start();
          destinationJNDIMapper.start();
          connFactoryJNDIMapper.start();
          connectionManager.start();
@@ -288,23 +304,23 @@
          {
             clusterConnectionManager.start();
          }
-         
+
          // Note we do not start the message counter manager by default. This must be done
          // explicitly by the user by calling enableMessageCounters(). This is because message
          // counter history takes up growing memory to store the stats and could theoretically
          // eventually cause the server to run out of RAM
-         
+
          txRepository.loadPreparedTransactions();
-         
-         JMSWireFormat wf = new JMSWireFormat();         
-         MarshalFactory.addMarshaller("jms", wf, wf);      
-         
+
+         JMSWireFormat wf = new JMSWireFormat();
+         MarshalFactory.addMarshaller("jms", wf, wf);
+
          //Now everything is started we can tell the invocation handler to start handling invocations
          //We do this right at the end otherwise it can start handling invocations before we are properly started
          JMSServerInvocationHandler.setClosed(false);
 
          started = true;
-         
+
          log.info("JBoss Messaging " + getVersion().getProviderVersion() + " server [" +
             getServerPeerID()+ "] started");
       }
@@ -324,9 +340,9 @@
          }
 
          log.info(this + " is Stopping. NOTE! Stopping the server peer cleanly will NOT cause failover to occur");
-         
+
          started = false;
-         
+
          //Tell the invocation handler we are closed - this is so we don't attempt to handle
          //any invocations when we are in a partial closing down state - which can give strange
          //"object not found with id" exceptions and stuff like that
@@ -337,9 +353,7 @@
          messageIDManager.stop();
          messageIDManager = null;
          channelIDManager.stop();
-         channelIDManager = null;
-         transactionIDManager.stop();
-         transactionIDManager = null;
+         channelIDManager = null;;
          destinationJNDIMapper.stop();
          destinationJNDIMapper = null;
          connFactoryJNDIMapper.stop();
@@ -362,7 +376,7 @@
          }
          clusterConnectionManager = null;
          postOffice = null;
-         
+
          unloadServerAOPConfig();
 
          // TODO unloadClientAOPConfig();
@@ -380,7 +394,7 @@
    // JMX Attributes -------------------------------------------------------------------------------
 
    // Plugins
-   
+
    public synchronized ObjectName getPersistenceManager()
    {
       return persistenceManagerObjectName;
@@ -391,7 +405,7 @@
       if (started)
       {
          log.warn("Cannot set persistence manager on server peer when server peer is started");
-         return;         
+         return;
       }
       persistenceManagerObjectName = on;
    }
@@ -406,7 +420,7 @@
       if (started)
       {
          log.warn("Cannot set post office on server peer when server peer is started");
-         return;         
+         return;
       }
       postOfficeObjectName = on;
    }
@@ -421,11 +435,11 @@
       if (started)
       {
          log.warn("Cannot set jms user manager on server peer when server peer is started");
-         return;         
+         return;
       }
       jmsUserManagerObjectName = on;
    }
-   
+
    public synchronized ObjectName getDefaultDLQ()
    {
       return defaultDLQObjectName;
@@ -435,7 +449,7 @@
    {
       defaultDLQObjectName = on;
    }
-   
+
    public synchronized ObjectName getDefaultExpiryQueue()
    {
       return defaultExpiryQueueObjectName;
@@ -444,15 +458,15 @@
    public synchronized void setDefaultExpiryQueue(ObjectName on)
    {
       this.defaultExpiryQueueObjectName = on;
-   }     
-      
+   }
+
    // Instance access
 
    public Object getInstance()
    {
       return this;
    }
-   
+
    //read only JMX attributes
 
    public String getJMSVersion()
@@ -489,7 +503,7 @@
    {
       return version.getProviderMinorVersion();
    }
-   
+
    //Read - write attributes
 
    public SecurityStore getSecurityStore()
@@ -505,22 +519,22 @@
    {
       return this.failoverStartTimeout;
    }
-   
+
    public synchronized void setFailoverStartTimeout(long timeout)
    {
       this.failoverStartTimeout = timeout;
    }
-   
+
    public synchronized long getFailoverCompleteTimeout()
    {
       return this.failoverCompleteTimeout;
    }
-   
+
    public synchronized void setFailoverCompleteTimeout(long timeout)
    {
       this.failoverCompleteTimeout = timeout;
    }
-   
+
    public synchronized int getDefaultMaxDeliveryAttempts()
    {
       return defaultMaxDeliveryAttempts;
@@ -530,7 +544,7 @@
    {
       this.defaultMaxDeliveryAttempts = attempts;
    }
-   
+
    public synchronized long getMessageCounterSamplePeriod()
    {
       return messageCounterSamplePeriod;
@@ -542,45 +556,45 @@
       {
          throw new IllegalArgumentException("Cannot set MessageCounterSamplePeriod < 1000 ms");
       }
-      
+
       if (messageCounterManager != null && newPeriod != messageCounterSamplePeriod)
       {
          messageCounterManager.reschedule(newPeriod);
-      }            
-      
+      }
+
       this.messageCounterSamplePeriod = newPeriod;
    }
-   
+
    public synchronized long getDefaultRedeliveryDelay()
    {
       return defaultRedeliveryDelay;
    }
-   
+
    public synchronized void setDefaultRedeliveryDelay(long delay)
    {
       this.defaultRedeliveryDelay = delay;
    }
-   
+
    public synchronized int getDefaultMessageCounterHistoryDayLimit()
    {
       return defaultMessageCounterHistoryDayLimit;
    }
-   
+
    public void setDefaultMessageCounterHistoryDayLimit(int limit)
    {
       if (limit < -1)
       {
          limit = -1;
       }
-      
+
       this.defaultMessageCounterHistoryDayLimit = limit;
    }
-   
+
    public String getClusterPullConnectionFactoryName()
    {
    	return clusterPullConnectionFactoryName;
    }
-   
+
    public void setClusterPullConnectionFactoryName(String name)
    {
       if (started)
@@ -589,47 +603,47 @@
       }
    	this.clusterPullConnectionFactoryName = name;
    }
-   
+
    public boolean isUseXAForMessagePull()
    {
    	return useXAForMessagePull;
    }
-   
+
    public void setUseXAForMessagePull(boolean useXA) throws Exception
    {
       if (started)
       {
          throw new IllegalStateException("Cannot set UseXAForMessagePull while the service is running");
       }
-      
-   	this.useXAForMessagePull = useXA;   	
+
+   	this.useXAForMessagePull = useXA;
    }
-   
+
    public boolean isDefaultPreserveOrdering()
    {
    	return defaultPreserveOrdering;
    }
-   
+
    public void setDefaultPreserveOrdering(boolean preserve) throws Exception
    {
       if (started)
       {
          throw new IllegalStateException("Cannot set DefaultPreserveOrdering while the service is running");
       }
-      
+
    	this.defaultPreserveOrdering = preserve;
    }
-   
+
    public long getRecoverDeliveriesTimeout()
    {
    	return this.recoverDeliveriesTimeout;
    }
-   
+
    public void setRecoverDeliveriesTimeout(long timeout)
    {
    	this.recoverDeliveriesTimeout = timeout;
    }
-   
+
    public synchronized void setServerPeerID(int serverPeerID)
    {
       if (started)
@@ -652,7 +666,7 @@
    {
       return defaultQueueJNDIContext;
    }
-   
+
    public synchronized void setDefaultQueueJNDIContext(String defaultQueueJNDIContext)
    {
       if (started)
@@ -677,46 +691,51 @@
 
       this.defaultTopicJNDIContext = defaultTopicJNDIContext;
    }
-   
+
    public synchronized void setSuckerPassword(String password)
    {
    	if (started)
       {
          throw new IllegalStateException("Cannot set SuckerPassword while the service is running");
       }
-   	
+
    	if (password == null)
    	{
    		throw new IllegalArgumentException("SuckerPassword cannot be null");
    	}
-   	
+
    	this.suckerPassword = password;
    }
-   
+
    public void setStrictTck(boolean strictTck)
    {
    	this.strictTck = strictTck || strictTckProperty;
    }
-   
+
    public boolean isStrictTck()
    {
    	return strictTck || strictTckProperty;
    }
-   
+
    public void enableMessageCounters()
-   {      
+   {
       messageCounterManager.start();
    }
-   
+
    public void disableMessageCounters()
    {
       messageCounterManager.stop();
-      
+
       messageCounterManager.resetAllCounters();
-      
+
       messageCounterManager.resetAllCounterHistories();
    }
-   
+
+   public RotatingID getMessageIDMgr()
+   {
+      return messageIDMgr;
+   }
+
    // JMX Operations -------------------------------------------------------------------------------
 
    public String deployQueue(String name, String jndiName) throws Exception
@@ -747,14 +766,14 @@
    {
       try
       {
-         return destroyDestination(true, name);        
+         return destroyDestination(true, name);
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMXInvocation(t, this + " destroyQueue");
       }
    }
-   
+
    public boolean undeployQueue(String name) throws Exception
    {
       try
@@ -802,7 +821,7 @@
          throw ExceptionUtil.handleJMXInvocation(t, this + " destroyTopic");
       }
    }
-   
+
    public boolean undeployTopic(String name) throws Exception
    {
       try
@@ -826,11 +845,11 @@
          throw ExceptionUtil.handleJMXInvocation(t, this + " getDestinations");
       }
    }
-   
+
    public List getMessageCounters() throws Exception
    {
       Collection counters = messageCounterManager.getMessageCounters();
-      
+
       return new ArrayList(counters);
    }
 
@@ -882,11 +901,11 @@
       // needed during output of last module data string
 
       Iterator iter = counters.iterator();
-      
+
       while (iter.hasNext())
       {
          MessageCounter counter = (MessageCounter)iter.next();
-         
+
          // get counter data
          StringTokenizer tokens = new StringTokenizer(counter.getCounterAsString(), ",");
 
@@ -1016,12 +1035,12 @@
    {
       messageCounterManager.resetAllCounters();
    }
-   
+
    public void resetAllMessageCounterHistories()
    {
       messageCounterManager.resetAllCounterHistories();
    }
-   
+
    public List retrievePreparedTransactions()
    {
       return txRepository.getPreparedTransactions();
@@ -1074,7 +1093,7 @@
    }
 
    // Public ---------------------------------------------------------------------------------------
-   
+
    public void resetAllSuckers()
    {
       if (this.clusterConnectionManager != null)
@@ -1082,17 +1101,17 @@
          clusterConnectionManager.resetAllSuckers();
       }
    }
-     
+
    public byte[] getClientAOPStack()
    {
       return clientAOPStack;
    }
-   
+
    public MessageCounterManager getMessageCounterManager()
    {
       return messageCounterManager;
    }
-   
+
    public IDManager getMessageIDManager()
    {
       return messageIDManager;
@@ -1102,22 +1121,22 @@
    {
       return channelIDManager;
    }
-   
+
    public ServerSessionEndpoint getSession(String sessionID)
    {
       return (ServerSessionEndpoint)sessions.get(sessionID);
    }
-   
+
    public Collection getSessions()
    {
    	return sessions.values();
    }
-   
+
    public void addSession(String id, ServerSessionEndpoint session)
    {
-      sessions.put(id, session);      
+      sessions.put(id, session);
    }
-   
+
    public void removeSession(String id)
    {
       if (sessions.remove(id) == null)
@@ -1129,43 +1148,43 @@
    public synchronized Queue getDefaultDLQInstance() throws Exception
    {
       Queue dlq = null;
-      
+
       if (defaultDLQObjectName != null)
-      { 
+      {
          ManagedQueue dest = null;
 
          // This can be null... JMXAccessor will return null if InstanceNotFoundException is caught
          dest = (ManagedQueue) JMXAccessor.getJMXAttributeOverSecurity(getServer(), defaultDLQObjectName, "Instance");
 
          if (dest != null && dest.getName() != null)
-         {            
+         {
             Binding binding = postOffice.getBindingForQueueName(dest.getName());
-            
+
             if (binding == null)
             {
             	throw new IllegalStateException("Cannot find binding for queue " + dest.getName());
             }
-            
+
             Queue queue = binding.queue;
-            
+
             if (queue.isActive())
             {
             	dlq = queue;
             }
          }
       }
-      
+
       return dlq;
    }
-   
+
    public synchronized Queue getDefaultExpiryQueueInstance() throws Exception
    {
       Queue expiryQueue = null;
-      
+
       if (defaultExpiryQueueObjectName != null)
       {
          ManagedQueue dest = null;
-         
+
          try
          {
 
@@ -1177,26 +1196,26 @@
          }
 
          if (dest != null && dest.getName() != null)
-         {            
+         {
          	Binding binding = postOffice.getBindingForQueueName(dest.getName());
-            
+
             if (binding == null)
             {
             	throw new IllegalStateException("Cannot find binding for queue " + dest.getName());
             }
-            
-            Queue queue = binding.queue;            
-         	
+
+            Queue queue = binding.queue;
+
             if (queue.isActive())
             {
             	expiryQueue = queue;
             }
          }
       }
-      
+
       return expiryQueue;
    }
-      
+
    public TransactionRepository getTxRepository()
    {
       return txRepository;
@@ -1274,25 +1293,25 @@
          if (postOffice.isClustered())
          {
             Replicator rep = (Replicator)postOffice;
-            
-            connFactoryJNDIMapper.injectReplicator(rep);          
-            
+
+            connFactoryJNDIMapper.injectReplicator(rep);
+
             // Also inject into the cluster connection manager
-            
+
             if (this.clusterConnectionManager != null)
             {
                this.clusterConnectionManager.injectPostOffice(postOffice);
-               
+
                this.clusterConnectionManager.injectReplicator((Replicator)postOffice);
             }
-            
+
             this.connectionManager.injectReplicator((Replicator)postOffice);
-            
+
             ((MessagingPostOffice)postOffice).injectServerPeer(this);
          }
-         
+
          // Also need to inject into txRepository
-         txRepository.injectPostOffice(postOffice);                          
+         txRepository.injectPostOffice(postOffice);
       }
       return postOffice;
    }
@@ -1301,7 +1320,7 @@
    {
    	return clusterNotifier;
    }
-   
+
    public FailoverWaiter getFailoverWaiter()
    {
    	return failoverWaiter;
@@ -1427,22 +1446,22 @@
 
       return deployDestinationInternal(destinationMBeanConfig, on, jndiName, false, -1, -1, -1);
    }
-   
+
    private String deployDestination(boolean isQueue, String name, String jndiName, int fullSize,
             int pageSize, int downCacheSize) throws Exception
    {
-      //    
+      //
       //    TODO - THIS IS A TEMPORARY IMPLEMENTATION; WILL BE REPLACED WITH INTEGRATION-CONSISTENT ONE
       //    TODO - if I find a way not using UnifiedClassLoader3 directly, then get rid of
       //    <path refid="jboss.jmx.classpath"/> from jms/build.xml dependentmodule.classpath
-      //    
-   	
+      //
+
       String destType = isQueue ? "Queue" : "Topic";
       String className = "org.jboss.jms.server.destination." + destType + "Service";
-      
+
       String ons ="jboss.messaging.destination:service="+ destType + ",name=" + name;
       ObjectName on = new ObjectName(ons);
-      
+
       String destinationMBeanConfig =
          "<mbean code=\"" + className + "\" " +
          "       name=\"" + ons + "\" " +
@@ -1454,7 +1473,7 @@
          "    <attribute name=\"PageSize\">" + pageSize + "</attribute>" +
          "    <attribute name=\"DownCacheSize\">" + downCacheSize + "</attribute>" +
          "</mbean>";
-      
+
       return deployDestinationInternal(destinationMBeanConfig, on, jndiName, true, fullSize,
                pageSize, downCacheSize);
    }
@@ -1465,7 +1484,7 @@
    {
    	log.trace("Deploying destination" + destinationMBeanConfig + " jndiName: " + jndiName +
 			       "fullSize: " + fullSize + " pageSize: " + pageSize + " downCacheSize: " + downCacheSize);
-     	
+
       MBeanServer mbeanServer = getServer();
 
       Element element = Util.stringToElement(destinationMBeanConfig);
@@ -1506,8 +1525,8 @@
       return (String)JMXAccessor.getJMXAttributeOverSecurity(mbeanServer, on, "JNDIName");
    }
 
-   
 
+
    /*
     * Undeploy the MBean but don't delete the underlying data
     */
@@ -1535,7 +1554,7 @@
       mbeanServer.unregisterMBean(on);
       return true;
    }
-   
+
    /*
     * Undeploy the MBean and delete the underlying data
     */
@@ -1552,45 +1571,45 @@
       {
          return false;
       }
-      
-      JMSCondition condition = new JMSCondition(isQueue, name);  
-      
+
+      JMSCondition condition = new JMSCondition(isQueue, name);
+
       Collection queues = postOffice.getQueuesForCondition(condition, true);
-      
+
       Iterator iter = queues.iterator();
-      
-      while (iter.hasNext())            
+
+      while (iter.hasNext())
       {
          Queue queue = (Queue)iter.next();
-         
+
          queue.removeAllReferences();
       }
-                       
+
       //undeploy the mbean
       if (!undeployDestination(isQueue, name))
       {
          return false;
       }
-            
+
       //Unbind the destination's queues
-      
-      while (iter.hasNext())            
+
+      while (iter.hasNext())
       {
          Queue queue = (Queue)iter.next();
-         
+
          queue.removeAllReferences();
-         
+
          //Durable subs need to be removed on all nodes
          boolean all = !isQueue && queue.isRecoverable();
-         
+
          postOffice.removeBinding(queue.getName(), all);
       }
-      
+
       return true;
    }
-   
 
+
    // Inner classes --------------------------------------------------------------------------------
-   
-  
+
+
 }

Modified: branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerConnectionEndpoint.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerConnectionEndpoint.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerConnectionEndpoint.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -75,7 +75,7 @@
 
 /**
  * Concrete implementation of ConnectionEndpoint.
- * 
+ *
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @version <tt>$Revision$</tt>
@@ -85,9 +85,9 @@
 public class ServerConnectionEndpoint implements ConnectionEndpoint
 {
    // Constants ------------------------------------------------------------------------------------
-   
+
    private static final Logger log = Logger.getLogger(ServerConnectionEndpoint.class);
-   
+
    // Static ---------------------------------------------------------------------------------------
 
    private static boolean trace = log.isTraceEnabled();
@@ -128,7 +128,7 @@
    private int defaultTempQueuePageSize;
    private int defaultTempQueueDownCacheSize;
    private int dupsOKBatchSize;
-   
+
    private ServerConnectionFactoryEndpoint cfendpoint;
 
    private byte usingVersion;
@@ -158,28 +158,28 @@
       this.serverPeer = serverPeer;
 
       this.cfendpoint = cfendpoint;
-      
+
       sm = serverPeer.getSecurityManager();
       tr = serverPeer.getTxRepository();
       cm = serverPeer.getConnectionManager();
       ms = serverPeer.getMessageStore();
       postOffice = serverPeer.getPostOfficeInstance();
- 
+
       started = false;
 
       this.id = GUIDGenerator.generateGUID();
       this.clientID = clientID;
       this.prefetchSize = prefetchSize;
-      
+
       this.defaultTempQueueFullSize = defaultTempQueueFullSize;
       this.defaultTempQueuePageSize = defaultTempQueuePageSize;
       this.defaultTempQueueDownCacheSize = defaultTempQueueDownCacheSize;
-      
+
       this.dupsOKBatchSize = dupsOKBatchSize;
 
       sessions = new HashMap();
       temporaryDestinations = new HashSet();
-      
+
       this.username = username;
       this.password = password;
 
@@ -187,31 +187,31 @@
       {
          this.failedNodeID = new Integer(failedNodeID);
       }
-      
+
       this.remotingClientSessionID = remotingSessionID;
-      
+
       this.jmsClientVMID = clientVMID;
-      this.usingVersion = versionToUse; 
-      
+      this.usingVersion = versionToUse;
+
       this.serverPeer.getConnectionManager().
          registerConnection(jmsClientVMID, remotingClientSessionID, this);
-      
+
       this.callbackHandler = callbackHandler;
-      
+
       Client callbackClient = callbackHandler.getCallbackClient();
-      
+
       if (callbackClient != null)
       {
          // TODO not sure if this is the best way to do this, but the callbackClient needs to have
          //      its "subsystem" set, otherwise remoting cannot find the associated
          //      ServerInvocationHandler on the callback server
          callbackClient.setSubsystem(CallbackManager.JMS_CALLBACK_SUBSYSTEM);
-         
+
          // We explictly set the Marshaller since otherwise remoting tries to resolve the marshaller
          // every time which is very slow - see org.jboss.remoting.transport.socket.ProcessInvocation
          // This can make a massive difference on performance. We also do this in
          // JMSRemotingConnection.setupConnection
-         
+
          callbackClient.setMarshaller(new JMSWireFormat());
          callbackClient.setUnMarshaller(new JMSWireFormat());
       }
@@ -223,7 +223,7 @@
    }
 
    // ConnectionDelegate implementation ------------------------------------------------------------
-   
+
    public SessionDelegate createSessionDelegate(boolean transacted,
                                                 int acknowledgmentMode,
                                                 boolean isXA)
@@ -234,55 +234,55 @@
          log.trace(this + " creating " + (transacted ? "transacted" : "non transacted") +
             " session, " + Util.acknowledgmentMode(acknowledgmentMode) + ", " +
             (isXA ? "XA": "non XA"));
-         
+
          if (closed)
          {
             throw new IllegalStateException("Connection is closed");
          }
-                  
+
          String sessionID = GUIDGenerator.generateGUID();
-           
+
          // create the corresponding server-side session endpoint and register it with this
          // connection endpoint instance
-         
+
          //Note we only replicate transacted and client acknowledge sessions.
          ServerSessionEndpoint ep = new ServerSessionEndpoint(sessionID, this,
          		                     transacted || acknowledgmentMode == Session.CLIENT_ACKNOWLEDGE);
-         
+
          synchronized (sessions)
          {
             sessions.put(sessionID, ep);
          }
-         
+
          SessionAdvised advised;
-         
+
          // Need to synchronized to prevent a deadlock
          // See http://jira.jboss.com/jira/browse/JBMESSAGING-797
          synchronized (AspectManager.instance())
-         {       
+         {
             advised = new SessionAdvised(ep);
          }
-         
+
          SessionAdvised sessionAdvised = advised;
-         
+
          serverPeer.addSession(sessionID, ep);
 
          Dispatcher.instance.registerTarget(sessionID, sessionAdvised);
 
          log.trace("created and registered " + ep);
-         
+
          ClientSessionDelegate d = new ClientSessionDelegate(sessionID, dupsOKBatchSize);
 
          log.trace("created " + d);
-         
+
          return d;
       }
       catch (Throwable t)
       {
-         throw ExceptionUtil.handleJMSInvocation(t, this + " createSessionDelegate");         
+         throw ExceptionUtil.handleJMSInvocation(t, this + " createSessionDelegate");
       }
    }
-         
+
    public String getClientID() throws JMSException
    {
       try
@@ -296,9 +296,9 @@
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " getClientID");
-      }  
+      }
    }
-   
+
    public void setClientID(String clientID) throws JMSException
    {
       try
@@ -312,7 +312,7 @@
          {
             //For failover we must allow setting client id since this will occur
             //on failover of connection
-            
+
             throw new IllegalStateException("Cannot set clientID, already set as " + this.clientID);
          }
 
@@ -323,9 +323,9 @@
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " setClientID");
-      } 
+      }
    }
-      
+
    public void start() throws JMSException
    {
       try
@@ -340,9 +340,9 @@
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " start");
-      } 
-   }   
-   
+      }
+   }
+
    public synchronized void stop() throws JMSException
    {
       try
@@ -351,94 +351,94 @@
          {
             throw new IllegalStateException("Connection is closed");
          }
-         
+
          setStarted(false);
-         
+
          log.trace("Connection " + id + " stopped");
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " stop");
-      } 
+      }
    }
-   
+
    public void close() throws JMSException
-   {      
+   {
       try
       {
          if (trace) { log.trace(this + " close()"); }
-         
+
          if (closed)
          {
             log.warn("Connection is already closed");
             return;
          }
-   
+
          //We clone to avoid deadlock http://jira.jboss.org/jira/browse/JBMESSAGING-836
          Map sessionsClone;
          synchronized (sessions)
          {
             sessionsClone = new HashMap(sessions);
          }
-         
+
          for(Iterator i = sessionsClone.values().iterator(); i.hasNext(); )
          {
             ServerSessionEndpoint sess = (ServerSessionEndpoint)i.next();
-   
+
             sess.localClose();
          }
-         
+
          sessions.clear();
-                  
+
          synchronized (temporaryDestinations)
          {
             for(Iterator i = temporaryDestinations.iterator(); i.hasNext(); )
             {
                JBossDestination dest = (JBossDestination)i.next();
-   
+
                if (dest.isQueue())
-               {     
+               {
                	// Temporary queues must be unbound on ALL nodes of the cluster
-               	
-               	postOffice.removeBinding(dest.getName(), postOffice.isClustered());               	
+
+               	postOffice.removeBinding(dest.getName(), postOffice.isClustered());
                }
                else
                {
                   //No need to unbind - this will already have happened, and removeAllReferences
                   //will have already been called when the subscriptions were closed
-                  //which always happens before the connection closed (depth first close)     
+                  //which always happens before the connection closed (depth first close)
                	//note there are no durable subs on a temporary topic
-               	
+
                	//Sanity check
-               	
+
                   Collection queues = serverPeer.getPostOfficeInstance().getQueuesForCondition(new JMSCondition(false, dest.getName()), true);
-               	
+
                   if (!queues.isEmpty())
                   {
                      // This should never happen
                      throw new IllegalStateException("Cannot delete temporary destination if it has consumer(s)");
                   }
                }
-               
-               // 
+
+               //
                // Remove temporary destination from the DestinationManager (JBMESSAGING-1215)
                //
                DestinationManager dm = serverPeer.getDestinationManager();
-               
+
                ManagedDestination mDest = dm.getDestination(dest.getName(), dest.isQueue());
                if (dm == null)
                {
                   throw new InvalidDestinationException("No such destination: " + dest);
                }
-               
+
                dm.unregisterDestination(mDest);
             }
-            
+
             temporaryDestinations.clear();
          }
-   
+
          cm.unregisterConnection(jmsClientVMID, remotingClientSessionID);
-   
+
          Dispatcher.instance.unregisterTarget(id, this);
 
          closed = true;
@@ -446,16 +446,16 @@
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " close");
-      } 
+      }
    }
-   
+
    public long closing(long sequence) throws JMSException
-   {                  
-      log.trace(this + " closing (noop)");    
-      
+   {
+      log.trace(this + " closing (noop)");
+
       return -1;
    }
-   
+
    public void closeCallbackClient()
    {
       try
@@ -473,60 +473,60 @@
 
    public void sendTransaction(TransactionRequest request,
                                boolean checkForDuplicates) throws JMSException
-   {    
+   {
       try
-      {      
+      {
          if (closed)
          {
             throw new IllegalStateException("Connection is closed");
          }
-                              
+
          if (request.getRequestType() == TransactionRequest.ONE_PHASE_COMMIT_REQUEST)
          {
             if (trace) { log.trace(this + " received ONE_PHASE_COMMIT request"); }
-            
+
             Transaction tx = tr.createTransaction();
             processTransaction(request.getState(), tx, checkForDuplicates);
             tx.commit();
-         }        
+         }
          else if (request.getRequestType() == TransactionRequest.TWO_PHASE_PREPARE_REQUEST)
-         {                        
+         {
             if (trace) { log.trace(this + " received TWO_PHASE_COMMIT prepare request"); }
-            
+
             Transaction tx = tr.createTransaction(request.getXid());
             processTransaction(request.getState(), tx, checkForDuplicates);
-            tx.prepare();            
+            tx.prepare();
          }
          else if (request.getRequestType() == TransactionRequest.TWO_PHASE_COMMIT_REQUEST)
-         {   
+         {
             if (trace) { log.trace(this + " received TWO_PHASE_COMMIT commit request"); }
-             
-            Transaction tx = tr.getPreparedTx(request.getXid());            
+
+            Transaction tx = tr.getPreparedTx(request.getXid());
             if (trace) { log.trace("Committing " + tx); }
-            tx.commit();   
+            tx.commit();
          }
          else if (request.getRequestType() == TransactionRequest.TWO_PHASE_ROLLBACK_REQUEST)
          {
             if (trace) { log.trace(this + " received TWO_PHASE_COMMIT rollback request"); }
-             
+
             // for 2pc rollback - we just don't cancel any messages back to the channel; this is
             // driven from the client side.
-             
+
             Transaction tx =  tr.getPreparedTx(request.getXid());
 
             if (trace) { log.trace(this + " rolling back " + tx); }
 
             tx.rollback();
-         }      
-                 
+         }
+
          if (trace) { log.trace(this + " processed transaction successfully"); }
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " sendTransaction");
-      } 
+      }
    }
-   
+
    /**
     * Get array of XA transactions in prepared state-
     * This would be used by the transaction manager in recovery or by a tool to apply
@@ -537,7 +537,7 @@
       try
       {
          List xids = tr.recoverPreparedTransactions();
-         
+
          return (MessagingXid[])xids.toArray(new MessagingXid[xids.size()]);
       }
       catch (Throwable t)
@@ -545,7 +545,8 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " getPreparedTransactions");
       }
    }
-   
+
+   /* We keep this in for now, so as not to break compatibilty with earlier clients */
    public IDBlock getIdBlock(int size) throws JMSException
    {
       try
@@ -557,14 +558,14 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " getIdBlock");
       }
    }
-   
+
    // Public ---------------------------------------------------------------------------------------
-   
+
    public String getUsername()
    {
       return username;
    }
-   
+
    public String getPassword()
    {
       return password;
@@ -611,37 +612,37 @@
    {
       return usingVersion;
    }
-   
+
    int getPrefetchSize()
    {
       return prefetchSize;
    }
-   
+
    int getDefaultTempQueueFullSize()
    {
       return defaultTempQueueFullSize;
    }
-   
+
    int getDefaultTempQueuePageSize()
    {
       return defaultTempQueuePageSize;
    }
-     
+
    int getDefaultTempQueueDownCacheSize()
    {
       return defaultTempQueueDownCacheSize;
    }
-   
+
    String getConnectionID()
    {
       return id;
    }
-   
+
    boolean isStarted()
    {
-      return started;    
+      return started;
    }
-   
+
    void removeSession(String sessionId) throws Exception
    {
       synchronized (sessions)
@@ -660,7 +661,7 @@
          temporaryDestinations.add(dest);
       }
    }
-   
+
    void removeTemporaryDestination(Destination dest)
    {
       synchronized (temporaryDestinations)
@@ -668,7 +669,7 @@
          temporaryDestinations.remove(dest);
       }
    }
-   
+
    boolean hasTemporaryDestination(Destination dest)
    {
       synchronized (temporaryDestinations)
@@ -676,77 +677,71 @@
          return temporaryDestinations.contains(dest);
       }
    }
-   
+
    String getRemotingClientSessionID()
    {
       return remotingClientSessionID;
    }
-   
-   void sendMessage(JBossMessage msg, Transaction tx, boolean checkForDuplicates) throws Exception
+
+   boolean sendMessage(JBossMessage msg, Transaction tx, boolean checkForDuplicates) throws Exception
    {
       if (trace) { log.trace(this + " sending message " + msg + (tx == null ? " non-transactionally" : " in " + tx)); }
 
-      if (checkForDuplicates)
-      {      	
-      	if (msg.isReliable())
-         {
-      		if (serverPeer.getPersistenceManagerInstance().referenceExists(msg.getMessageID()))
-      		{
-	      		// Message is already stored... so just ignoring the call
-	         	if (trace) { log.trace("Duplicate of " + msg + " exists in database - probably sent before failover"); }
-	         	
-	            return;
-      		}
-         }	      
-      	else
-      	{
-      		//NP messages get rejected http://jira.jboss.com/jira/browse/JBMESSAGING-1119
-      		if (trace) { log.trace("Rejecting NP message " + msg + " after failover"); }
-      		
-      		return;
-      	}
+      JBossDestination dest = (JBossDestination)msg.getJMSDestination();
+
+      if (!dest.isDirect())
+      {
+         long msgID = serverPeer.getMessageIDMgr().getID();
+
+         msg.setMessageId(msgID);
       }
-      
-      JBossDestination dest = (JBossDestination)msg.getJMSDestination();
-      
+
       // This allows the no-local consumers to filter out the messages that come from the same
       // connection.
 
-      // TODO Do we want to set this for ALL messages. Optimisation is possible here.
       msg.setConnectionID(id);
 
-
       // We must reference the message *before* we send it the destination to be handled. This is
       // so we can guarantee that the message doesn't disappear from the store before the
       // handling is complete. Each channel then takes copies of the reference if they decide to
       // maintain it internally
-      
+
       MessageReference ref = msg.createReference();
-      
+
+      if (checkForDuplicates)
+      {
+         if (serverPeer.getPersistenceManagerInstance().idExists(msg.getJMSMessageID()))
+         {
+            log.trace("ID exists in ID cache, probably duplicate sent on failover");
+
+            return false;
+         }
+      }
+
       long schedDeliveryTime = msg.getScheduledDeliveryTime();
-      
+
       if (schedDeliveryTime > 0)
       {
          ref.setScheduledDeliveryTime(schedDeliveryTime);
       }
-      
+
       if (dest.isDirect())
       {
       	//Route directly to queue - temp kludge for clustering
-         
+
       	Binding binding = postOffice.getBindingForQueueName(dest.getName());
-      	
+
       	if (binding == null)
       	{
       		throw new IllegalArgumentException("Cannot find binding for queue " + dest.getName());
       	}
-      	
+
       	Queue queue = binding.queue;
-      	
+
          Long scid = (Long)ref.getMessage().removeHeader(Message.SOURCE_CHANNEL_ID);
-         
+
          Delivery del = queue.handleMove(ref, scid.longValue());
-      	
+
       	if (del == null)
       	{
       		throw new JMSException("Failed to route " + ref + " to " + dest.getName());
@@ -761,35 +756,37 @@
       }
       else
       {
-         postOffice.route(ref, new JMSCondition(false, dest.getName()), tx);   
+         postOffice.route(ref, new JMSCondition(false, dest.getName()), tx);
       }
-         
+
       if (trace) { log.trace("sent " + msg); }
+
+      return true;
    }
-   
+
    // Protected ------------------------------------------------------------------------------------
 
    // Private --------------------------------------------------------------------------------------
-   
+
    private void setStarted(boolean s) throws Throwable
    {
       //We clone to avoid deadlock http://jira.jboss.org/jira/browse/JBMESSAGING-836
       Map sessionsClone = null;
-      
+
       synchronized(sessions)
       {
          sessionsClone = new HashMap(sessions);
       }
-      
+
       for (Iterator i = sessionsClone.values().iterator(); i.hasNext(); )
       {
          ServerSessionEndpoint sd = (ServerSessionEndpoint)i.next();
-         
+
          sd.setStarted(s);
       }
-      started = s;      
-   }   
-    
+      started = s;
+   }
+
    private void processTransaction(ClientTransaction txState,
                                    Transaction tx, boolean checkForDuplicates) throws Throwable
    {
@@ -805,29 +802,41 @@
          {
             JBossMessage message = (JBossMessage)j.next();
 
-            sendMessage(message, tx, checkForDuplicates);
+            if (checkForDuplicates && !message.isReliable())
+            {
+               //Ignore np messages on failover
+            }
+            else
+            {
+               boolean accepted = sendMessage(message, tx, checkForDuplicates);
+
+               if (!accepted)
+               {
+                  break;
+               }
+            }
          }
 
          // send the acks
-                  
+
          // We need to lookup the session in a global map maintained on the server peer. We can't
          // just assume it's one of the sessions in the connection. This is because in the case
          // of a connection consumer, the message might be delivered through one connection and
          // the transaction committed/rolledback through another. ConnectionConsumers suck.
-         
+
          ServerSessionEndpoint session = serverPeer.getSession(sessionState.getSessionId());
-         
+
          if (session == null)
-         {               
+         {
             throw new IllegalStateException("Cannot find session with id " +
                sessionState.getSessionId());
          }
 
          session.acknowledgeTransactionally(sessionState.getAcks(), tx);
       }
-            
+
       if (trace) { log.trace(this + " processed transaction " + tx); }
-   }   
+   }
 
    // Inner classes --------------------------------------------------------------------------------
 }

Modified: branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerSessionEndpoint.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerSessionEndpoint.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/jms/server/endpoint/ServerSessionEndpoint.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -95,7 +95,7 @@
 
 /**
  * The server side representation of a JMS session.
- * 
+ *
  * A user must not invoke methods of a session concurrently on different threads, however there are
  * situations where multiple threads may access this object concurrently, for instance:
  * - A session can be closed when it's connection is closed by the user which might be called on a
@@ -106,7 +106,7 @@
  * off messages to different sessions obtained from a pool, these may then cancel/ack etc on
  * different threads, but the acks/cancels/etc will end up back here on the connection consumer
  * session instance.
- * 
+ *
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
@@ -119,15 +119,15 @@
    // Constants ------------------------------------------------------------------------------------
 
    private static final Logger log = Logger.getLogger(ServerSessionEndpoint.class);
-   
+
    static final String DUR_SUB_STATE_CONSUMERS = "C";
-   
+
    static final String TEMP_QUEUE_MESSAGECOUNTER_PREFIX = "TempQueue.";
-   
+
    private static final long DELIVERY_WAIT_TIMEOUT = 5 * 1000;
-   
+
    private static final long CLOSE_WAIT_TIMEOUT = 10 * 1000;
-      
+
    // Static ---------------------------------------------------------------------------------------
 
    // Attributes -----------------------------------------------------------------------------------
@@ -140,7 +140,7 @@
 
    private ServerConnectionEndpoint connectionEndpoint;
    private ServerInvokerCallbackHandler callbackHandler;
-   
+
    private ServerPeer sp;
 
    private Map consumers;
@@ -160,26 +160,26 @@
    private Queue defaultExpiryQueue;
    private boolean supportsFailover;
    private boolean replicating;
-   
+
    private Object deliveryLock = new Object();
-      
+
    // Map <deliveryID, Delivery>
    private Map deliveries;
-   
+
    private long deliveryIdSequence;
-   
-   //Temporary until we have our own NIO transport   
+
+   //Temporary until we have our own NIO transport
    QueuedExecutor executor = new QueuedExecutor(new LinkedQueue());
-   
+
    private LinkedQueue toDeliver = new LinkedQueue();
-   
+
    private boolean waitingToClose = false;
-   
+
    private Object waitLock = new Object();
-   
+
    private long lastSequence = -1;
-   
-   
+
+
    // Constructors ---------------------------------------------------------------------------------
 
    ServerSessionEndpoint(String sessionID, ServerConnectionEndpoint connectionEndpoint,
@@ -188,48 +188,48 @@
       this.id = sessionID;
 
       this.connectionEndpoint = connectionEndpoint;
-      
+
       this.replicating = replicating;
-      
+
       callbackHandler = connectionEndpoint.getCallbackHandler();
-      
+
       sp = connectionEndpoint.getServerPeer();
 
       pm = sp.getPersistenceManagerInstance();
-      
+
       ms = sp.getMessageStore();
-      
+
       dm = sp.getDestinationManager();
-      
-      postOffice = sp.getPostOfficeInstance(); 
-      
+
+      postOffice = sp.getPostOfficeInstance();
+
       supportsFailover = connectionEndpoint.getConnectionFactoryEndpoint().isSupportsFailover() && postOffice.isClustered();
-      
+
       idm = sp.getChannelIDManager();
-      
+
       nodeId = sp.getServerPeerID();
-      
+
       tr = sp.getTxRepository();
-      
+
       consumers = new HashMap();
-      
+
 		browsers = new HashMap();
-      
+
       defaultDLQ = sp.getDefaultDLQInstance();
-      
+
       defaultExpiryQueue = sp.getDefaultExpiryQueueInstance();
-      
+
       tr = sp.getTxRepository();
-      
+
       defaultMaxDeliveryAttempts = sp.getDefaultMaxDeliveryAttempts();
-      
+
       defaultRedeliveryDelay = sp.getDefaultRedeliveryDelay();
-      
+
       deliveries = new ConcurrentHashMap();
    }
-   
+
    // SessionDelegate implementation ---------------------------------------------------------------
-       
+
    public ConsumerDelegate createConsumerDelegate(JBossDestination jmsDestination,
                                                   String selector,
                                                   boolean noLocal,
@@ -239,16 +239,16 @@
    {
       try
       {
-      	//TODO This is a temporary kludge to allow creation of consumers directly on core queues for 
+      	//TODO This is a temporary kludge to allow creation of consumers directly on core queues for
       	//cluster connections
       	//This will disappear once we move all JMS knowledge to the client side
-      	
+
       	if (jmsDestination.isDirect())
       	{
       		return createConsumerDelegateDirect(jmsDestination.getName(), selector);
       	}
       	else
-      	{      	      	
+      	{
 	         return createConsumerDelegateInternal(jmsDestination, selector,
 	                                               noLocal, subscriptionName);
       	}
@@ -258,7 +258,7 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " createConsumerDelegate");
       }
    }
-      
+
 	public BrowserDelegate createBrowserDelegate(JBossDestination jmsDestination,
                                                 String selector)
       throws JMSException
@@ -281,14 +281,14 @@
          {
             throw new IllegalStateException("Session is closed");
          }
-         
+
          ManagedDestination dest = (ManagedDestination)dm.getDestination(name, true);
-         
+
          if (dest == null)
          {
             throw new JMSException("There is no administratively defined queue with name:" + name);
-         }        
-   
+         }
+
          return new JBossQueue(dest.getName());
       }
       catch (Throwable t)
@@ -305,14 +305,14 @@
          {
             throw new IllegalStateException("Session is closed");
          }
-         
+
          ManagedDestination dest = (ManagedDestination)dm.getDestination(name, false);
-                  
+
          if (dest == null)
          {
             throw new JMSException("There is no administratively defined topic with name:" + name);
-         }        
-   
+         }
+
          return new JBossTopic(name);
       }
       catch (Throwable t)
@@ -320,13 +320,13 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " createTopic");
       }
    }
-   
+
    public void close() throws JMSException
    {
       try
       {
          localClose();
-         
+
          connectionEndpoint.removeSession(id);
       }
       catch (Throwable t)
@@ -334,60 +334,66 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " close");
       }
    }
-      
+
    public long closing(long sequence) throws JMSException
    {
       if (trace) log.trace(this + " closing");
-      
+
       //Need to wait for messages to arrive or they may be lost if connection/session is closed too
       //quickly after sending
-      
+
       if (sequence != -1)
       {
          synchronized (waitLock)
-         {           
+         {
             long wait = CLOSE_WAIT_TIMEOUT;
-            
+
             while (lastSequence != sequence - 1 && wait > 0)
             {
-               long start = System.currentTimeMillis(); 
+               long start = System.currentTimeMillis();
                try
                {
                   waitLock.wait(wait);
                }
                catch (InterruptedException e)
-               {                 
+               {
                }
                wait -= (System.currentTimeMillis() - start);
             }
-            
+
             if (wait <= 0)
             {
                log.warn("Timed out waiting for last message");
             }
-         }        
-      }  
-      
+         }
+      }
+
       return -1;
    }
- 
+
    public void send(JBossMessage message, final boolean checkForDuplicates) throws JMSException
    {
       throw new IllegalStateException("Should not be handled here");
    }
-   
+
    public void send(JBossMessage message, final boolean checkForDuplicates, long sequence) throws JMSException
    {
       try
-      {                
-         connectionEndpoint.sendMessage(message, null, checkForDuplicates); 
-         
+      {
+         if (checkForDuplicates && !message.isReliable())
+         {
+            //Ignore np messages on failover
+            return;
+         }
+
+         connectionEndpoint.sendMessage(message, null, checkForDuplicates);
+
          if (sequence != -1)
          {
             synchronized (waitLock)
             {
                this.lastSequence = sequence;
-               
+
                waitLock.notifyAll();
             }
          }
@@ -397,31 +403,31 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " send");
       }
    }
-   
+
    public boolean acknowledgeDelivery(Ack ack) throws JMSException
    {
       try
       {
-         return acknowledgeDeliveryInternal(ack);   
+         return acknowledgeDeliveryInternal(ack);
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " acknowledgeDelivery");
       }
-   }     
-         
+   }
+
    public void acknowledgeDeliveries(List acks) throws JMSException
-   {    
+   {
       if (trace) {log.trace(this + " acknowledges deliveries " + acks); }
-      
+
       try
       {
          Iterator iter = acks.iterator();
-         
+
          while (iter.hasNext())
          {
             Ack ack = (Ack)iter.next();
-            
+
             acknowledgeDeliveryInternal(ack);
          }
       }
@@ -430,17 +436,17 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " acknowledgeDeliveries");
       }
    }
-             
+
    public void cancelDelivery(Cancel cancel) throws JMSException
    {
       if (trace) {log.trace(this + " cancelDelivery " + cancel); }
-      
+
       try
       {
          Delivery del = cancelDeliveryInternal(cancel);
-         
+
          if (del != null)
-         {         
+         {
 	         //Prompt delivery
 	         promptDelivery((Channel)del.getObserver());
          }
@@ -448,45 +454,45 @@
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " cancelDelivery");
-      }     
-   }            
+      }
+   }
 
    public void cancelDeliveries(List cancels) throws JMSException
    {
       if (trace) {log.trace(this + " cancels deliveries " + cancels); }
-        
+
       try
       {
          // deliveries must be cancelled in reverse order
 
          Set channels = new HashSet();
-                          
+
          for (int i = cancels.size() - 1; i >= 0; i--)
          {
-            Cancel cancel = (Cancel)cancels.get(i);       
-            
+            Cancel cancel = (Cancel)cancels.get(i);
+
             if (trace) { log.trace(this + " cancelling delivery " + cancel.getDeliveryId()); }
-                        
+
             Delivery del = cancelDeliveryInternal(cancel);
-            
+
             if (del != null)
-            {            	
+            {
             	channels.add(del.getObserver());
             }
          }
-                 
+
          if (trace) { log.trace("Cancelled deliveries"); }
-         
+
          // need to prompt delivery for all affected channels
-         
+
          promptDelivery(channels);
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " cancelDeliveries");
       }
-   }         
-   
+   }
+
    public void recoverDeliveries(List deliveryRecoveryInfos, String oldSessionID) throws JMSException
    {
       if (trace) { log.trace(this + " recovers deliveries " + deliveryRecoveryInfos); }
@@ -497,125 +503,125 @@
          {
             throw new IllegalStateException("Recovering deliveries but post office is not clustered!");
          }
-         
+
          long maxDeliveryId = 0;
-                  
+
          //Sort into different list for each channel
          Map ackMap = new HashMap();
-                  
+
          for (Iterator iter = deliveryRecoveryInfos.iterator(); iter.hasNext(); )
          {
             DeliveryRecovery deliveryInfo = (DeliveryRecovery)iter.next();
-                
+
             String queueName = deliveryInfo.getQueueName();
 
             List acks = (List)ackMap.get(queueName);
-            
+
             if (acks == null)
             {
                acks = new ArrayList();
-               
+
                ackMap.put(queueName, acks);
             }
-            
+
             acks.add(deliveryInfo);
-         }  
+         }
 
          Iterator iter = ackMap.entrySet().iterator();
-         
+
          while (iter.hasNext())
          {
             Map.Entry entry = (Map.Entry)iter.next();
-            
+
             String queueName = (String)entry.getKey();
-            
+
             //Look up the queue
 
             Binding binding = postOffice.getBindingForQueueName(queueName);
-            
+
             Queue queue = binding.queue;
-            
+
             if (queue == null)
             {
                throw new IllegalStateException("Cannot find queue with queue name: " + queueName);
             }
-            
+
             List acks = (List)entry.getValue();
-            
+
             List ids = new ArrayList(acks.size());
-            
+
             for (Iterator iter2 = acks.iterator(); iter2.hasNext(); )
             {
                DeliveryRecovery info = (DeliveryRecovery)iter2.next();
-               
+
                ids.add(new Long(info.getMessageID()));
             }
-            
+
             JMSCondition cond = (JMSCondition)binding.condition;
-            
+
             ManagedDestination dest =
                sp.getDestinationManager().getDestination(cond.getName(), cond.isQueue());
-            
+
             if (dest == null)
             {
                throw new IllegalStateException("Cannot find managed destination with name " +
                   cond.getName() + " isQueue" + cond.isQueue());
             }
-            
+
             Queue dlqToUse =
                dest.getDLQ() == null ? defaultDLQ : dest.getDLQ();
-            
+
             Queue expiryQueueToUse =
                dest.getExpiryQueue() == null ? defaultExpiryQueue : dest.getExpiryQueue();
-            
+
             int maxDeliveryAttemptsToUse =
                dest.getMaxDeliveryAttempts() == -1 ? defaultMaxDeliveryAttempts : dest.getMaxDeliveryAttempts();
 
             List dels = queue.recoverDeliveries(ids);
 
             Iterator iter2 = dels.iterator();
-            
+
             Iterator iter3 = acks.iterator();
-            
+
             while (iter2.hasNext())
             {
                Delivery del = (Delivery)iter2.next();
-               
+
                DeliveryRecovery info = (DeliveryRecovery)iter3.next();
-               
+
                long deliveryId = info.getDeliveryID();
-               
+
                maxDeliveryId = Math.max(maxDeliveryId, deliveryId);
-               
+
                if (trace) { log.trace(this + " Recovered delivery " + deliveryId + ", " + del); }
-               
+
                deliveries.put(new Long(deliveryId),
                               new DeliveryRecord(del, dlqToUse, expiryQueueToUse, dest.getRedeliveryDelay(),
                               		maxDeliveryAttemptsToUse, queueName, supportsFailover, deliveryId));
-               
+
                //We want to replicate the deliveries to the new backup, but we don't want a response since that would cause actual delivery
                //to occur, which we don't want since the client already has the deliveries
-               
+
                if (supportsFailover)
                {
                	postOffice.sendReplicateDeliveryMessage(queueName, id, del.getReference().getMessage().getMessageID(), deliveryId, false, true);
                }
             }
          }
-         
+
          iter = postOffice.getAllBindings().iterator();
-         
+
          while (iter.hasNext())
          {
          	Binding binding = (Binding)iter.next();
-         	
+
          	if (binding.queue.isClustered() && binding.queue.isRecoverable())
          	{
          		// Remove any stranded refs corresponding to refs that might have been in the client buffer but not consumed
          		binding.queue.removeStrandedReferences(oldSessionID);
          	}
          }
-         
+
          deliveryIdSequence = maxDeliveryId + 1;
       }
       catch (Throwable t)
@@ -623,7 +629,7 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " recoverDeliveries");
       }
    }
-   
+
    public void addTemporaryDestination(JBossDestination dest) throws JMSException
    {
       try
@@ -639,15 +645,15 @@
          }
 
          connectionEndpoint.addTemporaryDestination(dest);
-         
+
          // Register with the destination manager
-         
+
          ManagedDestination mDest;
-         
+
          int fullSize = connectionEndpoint.getDefaultTempQueueFullSize();
          int pageSize = connectionEndpoint.getDefaultTempQueuePageSize();
          int downCacheSize = connectionEndpoint.getDefaultTempQueueDownCacheSize();
-         
+
          //Temporary destinations are clustered if the post office is clustered
 
          if (dest.isTopic())
@@ -658,35 +664,35 @@
          {
             mDest = new ManagedQueue(dest.getName(), fullSize, pageSize, downCacheSize, postOffice.isClustered());
          }
-         
+
          mDest.setTemporary(true);
-         
+
          dm.registerDestination(mDest);
-         
+
          if (dest.isQueue())
-         {            
+         {
             Queue coreQueue = new MessagingQueue(nodeId, dest.getName(),
             												 idm.getID(), ms, pm, false, -1, null,
 										                   fullSize, pageSize, downCacheSize, postOffice.isClustered(),
 										                   sp.getRecoverDeliveriesTimeout());
 
-        
+
             Condition cond = new JMSCondition(true, dest.getName());
-            
+
          	// make a binding for this temporary queue
-            
+
             // temporary queues need to bound on ALL nodes of the cluster
-            postOffice.addBinding(new Binding(cond, coreQueue, true), postOffice.isClustered());   
-            
+            postOffice.addBinding(new Binding(cond, coreQueue, true), postOffice.isClustered());
+
             coreQueue.activate();
-         }         
+         }
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " addTemporaryDestination");
       }
    }
-   
+
    public void deleteTemporaryDestination(JBossDestination dest) throws JMSException
    {
       try
@@ -695,67 +701,67 @@
          {
             throw new IllegalStateException("Session is closed");
          }
-   
+
          if (!dest.isTemporary())
          {
             throw new InvalidDestinationException("Destination:" + dest +
                                                   " is not a temporary destination");
          }
-         
+
          ManagedDestination mDest = dm.getDestination(dest.getName(), dest.isQueue());
-         
+
          if (mDest == null)
          {
             throw new InvalidDestinationException("No such destination: " + dest);
          }
-                  
+
          if (dest.isQueue())
          {
          	Binding binding = postOffice.getBindingForQueueName(dest.getName());
-         	
+
          	if (binding == null)
          	{
          		throw new IllegalStateException("Cannot find binding for queue " + dest.getName());
          	}
-         	
+
          	if (binding.queue.getLocalDistributor().getNumberOfReceivers() != 0)
          	{
          		throw new IllegalStateException("Cannot delete temporary queue if it has consumer(s)");
          	}
-         	
+
          	// temporary queues must be unbound on ALL nodes of the cluster
-         	
-            postOffice.removeBinding(dest.getName(), postOffice.isClustered());         	        
+
+            postOffice.removeBinding(dest.getName(), postOffice.isClustered());
          }
          else
          {
-            //Topic            
-            Collection queues = postOffice.getQueuesForCondition(new JMSCondition(false, dest.getName()), true);         	
-                           
+            //Topic
+            Collection queues = postOffice.getQueuesForCondition(new JMSCondition(false, dest.getName()), true);
+
             if (!queues.isEmpty())
          	{
             	throw new IllegalStateException("Cannot delete temporary topic if it has consumer(s)");
          	}
-                        
+
             // There is no need to explicitly unbind the subscriptions for the temp topic, this is because we
             // will not get here unless there are no bindings.
             // Note that you cannot create surable subs on a temp topic
          }
-         
-         connectionEndpoint.removeTemporaryDestination(dest);         
-         
-         dm.unregisterDestination(mDest);                             
+
+         connectionEndpoint.removeTemporaryDestination(dest);
+
+         dm.unregisterDestination(mDest);
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMSInvocation(t, this + " deleteTemporaryDestination");
       }
    }
-   
+
    public void unsubscribe(String subscriptionName) throws JMSException
    {
       log.trace(this + " unsubscribing " + subscriptionName);
-      
+
       try
       {
          if (closed)
@@ -766,58 +772,58 @@
          {
             throw new InvalidDestinationException("Destination is null");
          }
-   
+
          String clientID = connectionEndpoint.getClientID();
-   
+
          if (clientID == null)
          {
             throw new JMSException("null clientID on connection");
          }
-         
+
          String queueName = MessageQueueNameHelper.createSubscriptionName(clientID, subscriptionName);
-         
+
          Binding binding = postOffice.getBindingForQueueName(queueName);
-         
+
          if (binding == null)
          {
             throw new InvalidDestinationException("Cannot find durable subscription with name " +
                                                   subscriptionName + " to unsubscribe");
          }
-         
-         Queue sub = binding.queue;         
-         
+
+         Queue sub = binding.queue;
+
          // Section 6.11. JMS 1.1.
          // "It is erroneous for a client to delete a durable subscription while it has an active
          // TopicSubscriber for it or while a message received by it is part of a current
          // transaction or has not been acknowledged in the session."
-         
+
          if (sub.getLocalDistributor().getNumberOfReceivers() != 0)
          {
             throw new IllegalStateException("Cannot unsubscribe durable subscription " +
                                             subscriptionName + " since it has active subscribers");
          }
-         
+
          //Also if it is clustered we must disallow unsubscribing if it has active consumers on other nodes
-         
+
          if (sub.isClustered() && postOffice.isClustered())
          {
          	Replicator rep = (Replicator)postOffice;
-         	
+
          	Map map = rep.get(sub.getName());
-         	
+
          	if (!map.isEmpty())
          	{
          		throw new IllegalStateException("Cannot unsubscribe durable subscription " +
                      subscriptionName + " since it has active subscribers on other nodes");
          	}
          }
-         
-         postOffice.removeBinding(sub.getName(), sub.isClustered() && postOffice.isClustered());         
-         
+
+         postOffice.removeBinding(sub.getName(), sub.isClustered() && postOffice.isClustered());
+
          String counterName = TopicService.SUBSCRIPTION_MESSAGECOUNTER_PREFIX + sub.getName();
-         
+
          MessageCounter counter = sp.getMessageCounterManager().unregisterMessageCounter(counterName);
-         
+
          if (counter == null)
          {
             throw new IllegalStateException("Cannot find counter to remove " + counterName);
@@ -828,9 +834,9 @@
          throw ExceptionUtil.handleJMSInvocation(t, this + " unsubscribe");
       }
    }
-   
+
    // Public ---------------------------------------------------------------------------------------
-   
+
    public ServerConnectionEndpoint getConnectionEndpoint()
    {
       return connectionEndpoint;
@@ -840,33 +846,33 @@
    {
       return "SessionEndpoint[" + id + "]";
    }
-   
+
    public void deliverAnyWaitingDeliveries(String queueName) throws Exception
    {
    	//	First deliver any waiting deliveries
-   	
+
    	if (trace) { log.trace("Delivering any waiting deliveries: " + queueName); }
-   	
+
    	List toAddBack = null;
-   	
+
    	while (true)
    	{
    		DeliveryRecord dr = (DeliveryRecord)toDeliver.poll(0);
-   		
+
    		if (dr == null)
    		{
    			break;
    		}
-   		
-   		if (trace) { log.trace("Considering " + dr); } 
-   		
+
+   		if (trace) { log.trace("Considering " + dr); }
+
    		if (queueName == null || dr.queueName.equals(queueName))
-   		{   		
+   		{
    			//Need to synchronized to prevent the delivery being performed twice
    			synchronized (dr)
-   			{   				
-		   		performDelivery(dr.del.getReference(), dr.deliveryID, dr.getConsumer()); 
-					
+   			{
+		   		performDelivery(dr.del.getReference(), dr.deliveryID, dr.getConsumer());
+
 			   	dr.waitingForResponse = false;
    			}
    		}
@@ -876,63 +882,63 @@
    			{
    				toAddBack = new ArrayList();
    			}
-   			
+
    			toAddBack.add(dr);
    		}
    	}
-   	
+
    	if (toAddBack != null)
    	{
    		Iterator iter = toAddBack.iterator();
-   		
+
    		while (iter.hasNext())
    		{
    			toDeliver.put(iter.next());
    		}
    	}
-   	
+
    	if (trace) { log.trace("Done delivering"); }
    }
-   
+
    public boolean collectDeliveries(Map map, boolean firstNode, String queueName) throws Exception
    {
    	if (trace) { log.trace("Collecting deliveries"); }
-   	
+
    	boolean gotSome = false;
-   	   	
+
    	if (!firstNode && replicating)
-   	{	   	
+   	{
 	   	if (trace) { log.trace("Now collecting"); }
-	   	   	
+
 	   	Iterator iter = deliveries.entrySet().iterator();
-	   	
+
 	   	while (iter.hasNext())
 	   	{
 	   		Map.Entry entry = (Map.Entry)iter.next();
-	   		
+
 	   		Long l = (Long)entry.getKey();
-	   		
+
 	   		long deliveryID = l.longValue();
-	   		
+
 	   		DeliveryRecord rec = (DeliveryRecord)entry.getValue();
-	   		
+
 	   		if (rec.replicating && (queueName == null || rec.queueName.equals(queueName)))
 	   		{
 	   			Map ids = (Map)map.get(rec.queueName);
-	   			
+
 	   			if (ids == null)
 	   			{
 	   				ids = new HashMap();
-	   				
+
 	   				map.put(rec.queueName, ids);
 	   			}
-	   			
+
 	   			ids.put(new Long(rec.del.getReference().getMessage().getMessageID()), id);
-	   			
+
 	   			gotSome = true;
-	   			
+
 	   			boolean notify = false;
-	   			
+
 	   			//Need to synchronize to prevent delivery occurring more than once - e.g.
 	   			//if replicateDeliveryResponseReceived occurs curently with this
 	   			synchronized (rec)
@@ -940,15 +946,15 @@
 		   			if (rec.waitingForResponse)
 		   			{
 		   				//Do the delivery now
-		   				
-		   				performDelivery(rec.del.getReference(), deliveryID, rec.getConsumer());   	   	
-		   		   	
+
+		   				performDelivery(rec.del.getReference(), deliveryID, rec.getConsumer());
+
 		   		   	rec.waitingForResponse = false;
-		   		   	
+
 		   		   	notify = true;
 		   			}
 	   			}
-	   		   	
+
 	   			if (notify)
 	   			{
 	   		   	synchronized (deliveryLock)
@@ -957,64 +963,64 @@
 	   		   		{
 	   		   			deliveryLock.notifyAll();
 	   		   		}
-	   		   	}   					   			
+	   		   	}
 	   			}
 	   		}
 	   	}
    	}
-   	
+
    	if (trace) { log.trace("Collected " + map.size() + " deliveries"); }
-   	
+
    	return gotSome;
    }
-      
+
    public void replicateDeliveryResponseReceived(long deliveryID) throws Exception
    {
    	//We look up the delivery in the list and actually perform the delivery
-   	
+
    	if (trace) { log.trace(this + " replicate delivery response received for delivery " + deliveryID); }
-   	
+
    	DeliveryRecord rec = (DeliveryRecord)deliveries.get(new Long(deliveryID));
-   	
+
    	if (rec == null)
    	{
    		//This is ok - may happen at failover
-         
+
    	   // This can happen when the failover node is being changed
          // E.g. failover node changes, replicates start getting sent to the new failover node,
          // then the new node requests to collect the deliveries from this node, at which point we deliver
          // all waiting deliveries. Then the responses to the original ones come back.
          // So we can ignore them
-         
+
          return;
    	}
-   	   	
-   	boolean delivered = false;   	
-   	
+
+   	boolean delivered = false;
+
 		while (true)
    	{
    		DeliveryRecord dr = (DeliveryRecord)toDeliver.peek();
-   		      	      		
+
    		if (dr == null)
    		{
    			if (trace) { log.trace("No more deliveries in list"); }
-   			
+
    			break;
    		}
-   		
+
    		if (trace) { log.trace("Peeked delivery record: " + dr.deliveryID); }
-   		
+
    		//Needs to be synchronized to prevent delivery occurring twice e.g. if this occurs at same time as collectDeliveries
    		synchronized (dr)
-   		{	   		
+   		{
 	   		boolean performDelivery = false;
-	   		
+
 	   		if (dr.waitingForResponse)
 	   		{
 	   			if (dr == rec)
 	   			{
 	   				if (trace) { log.trace("Found our delivery"); }
-	   				
+
 	   				performDelivery = true;
 	   			}
 	   			else
@@ -1030,8 +1036,8 @@
 	   				}
 	   				else
 	   				{
-	   					//We have delivered ours and possibly any non replicated deliveries too   	   					   	   					
-	   	   	   	
+	   					//We have delivered ours and possibly any non replicated deliveries too
+
 	   					break;
 	   				}
 	   			}
@@ -1039,27 +1045,27 @@
 	   		else
 	   		{
 	   			//Non replicated delivery
-	   			
+
 	   			if (trace) { log.trace("Non replicated delivery"); }
-	   			
+
 	   			performDelivery = true;
 	   		}
-	   		
+
 	   		if (performDelivery)
 	   		{
 	   			toDeliver.take();
-	   			
-	   			performDelivery(dr.del.getReference(), dr.deliveryID, dr.getConsumer()); 
-	   			
+
+	   			performDelivery(dr.del.getReference(), dr.deliveryID, dr.getConsumer());
+
 	   			delivered = true;
-	   	   	
+
 	   	   	dr.waitingForResponse = false;
-	   	   	
+
 	   	   	delivered = true;
 	   		}
-   		}	
-   	}   	  	      	
-   	
+   		}
+   	}
+
    	if (delivered)
    	{
 	   	synchronized (deliveryLock)
@@ -1069,31 +1075,31 @@
 	   			deliveryLock.notifyAll();
 	   		}
 	   	}
-   	}   	   	   	   
+   	}
    }
 
    // Package protected ----------------------------------------------------------------------------
-   
+
    void expireDelivery(Delivery del, Queue expiryQueue) throws Throwable
    {
       if (trace) { log.trace(this + " detected expired message " + del.getReference()); }
-      
+
       if (expiryQueue != null)
       {
          if (trace) { log.trace(this + " sending expired message to expiry queue " + expiryQueue); }
-         
+
          JBossMessage copy = makeCopyForDLQOrExpiry(true, del);
-         
+
          moveInTransaction(copy, del, expiryQueue, true);
       }
       else
       {
          log.warn("No expiry queue has been configured so removing expired " +  del.getReference());
-         
+
          del.acknowledge(null);
       }
    }
-      
+
    void removeBrowser(String browserId) throws Exception
    {
       synchronized (browsers)
@@ -1115,52 +1121,52 @@
          }
       }
    }
-    
+
    void localClose() throws Throwable
    {
       if (closed)
       {
          throw new IllegalStateException("Session is already closed");
       }
-      
+
       if (trace) log.trace(this + " close()");
-            
+
       //We clone to avoid deadlock http://jira.jboss.org/jira/browse/JBMESSAGING-836
       Map consumersClone;
       synchronized (consumers)
       {
          consumersClone = new HashMap(consumers);
       }
-      
+
       for( Iterator i = consumersClone.values().iterator(); i.hasNext(); )
       {
          ((ServerConsumerEndpoint)i.next()).localClose();
-      }  
-      
+      }
+
       consumers.clear();
-      
-      
+
+
       //We clone to avoid deadlock http://jira.jboss.org/jira/browse/JBMESSAGING-836
       Map browsersClone;
       synchronized (browsers)
       {
          browsersClone = new HashMap(browsers);
       }
-      
+
       for( Iterator i = browsersClone.values().iterator(); i.hasNext(); )
       {
          ((ServerBrowserEndpoint)i.next()).localClose();
-      }  
-      
+      }
+
       browsers.clear();
-      
-      
+
+
       //Now cancel any remaining deliveries in reverse delivery order
       //Note we don't maintain order using a LinkedHashMap since then we lose
       //concurrency since we would have to lock it exclusively
-      
+
       List entries = new ArrayList(deliveries.entrySet());
-      
+
       //Sort them in reverse delivery id order
       Collections.sort(entries,
                        new Comparator()
@@ -1172,32 +1178,32 @@
                               Long id1 = (Long)entry1.getKey();
                               Long id2 = (Long)entry2.getKey();
                               return id2.compareTo(id1);
-                           } 
+                           }
                        });
 
       Iterator iter = entries.iterator();
-            
+
       Set channels = new HashSet();
-      
+
       if (trace) { log.trace(this + " cancelling " + entries.size() + " deliveries"); }
-      
+
       while (iter.hasNext())
       {
          Map.Entry entry = (Map.Entry)iter.next();
-         
+
          if (trace) { log.trace(this + " cancelling delivery with delivery id: " + entry.getKey()); }
-         
+
          DeliveryRecord rec = (DeliveryRecord)entry.getValue();
-         
+
          rec.del.cancel();
-         
+
          channels.add(rec.del.getObserver());
       }
-      
+
       promptDelivery(channels);
-      
+
       //Close down the executor
-      
+
       //Note we need to wait for ALL tasks to complete NOT just one otherwise we can end up with the following situation
       //prompter is queued and starts to execute
       //prompter almost finishes executing then a message is cancelled due to this session closing
@@ -1207,26 +1213,26 @@
       executor.shutdownAfterProcessingCurrentlyQueuedTasks();
 
       deliveries.clear();
-      
+
       sp.removeSession(id);
-            
+
       Dispatcher.instance.unregisterTarget(id, this);
-      
+
       closed = true;
-   }            
-   
+   }
+
    void cancelDelivery(long deliveryId) throws Throwable
    {
       DeliveryRecord rec = (DeliveryRecord)deliveries.remove(new Long(deliveryId));
-      
+
       if (rec == null)
       {
          throw new IllegalStateException("Cannot find delivery to cancel " + deliveryId);
       }
-      
+
       rec.del.cancel();
-   }         
-   
+   }
+
    /*
     * When a consumer closes there may be deliveries where the replication messages has gone out to the backup
     * but the response hasn't been received yet so the messages hasn't actually been delivered.
@@ -1234,35 +1240,35 @@
     * the session is closed.
     */
    void waitForDeliveriesFromConsumer(String consumerID) throws Exception
-   {   
+   {
 		long toWait = DELIVERY_WAIT_TIMEOUT;
-		
+
 		boolean wait;
-		
+
    	synchronized (deliveryLock)
-   	{   		
+   	{
    		do
    		{
    			wait = false;
-   			
+
    			long start = System.currentTimeMillis();
-   			
+
 	   		Iterator iter = deliveries.values().iterator();
-	   		
+
 	   		while (iter.hasNext())
 	   		{
 	   			DeliveryRecord rec = (DeliveryRecord)iter.next();
-	   			
+
 	   			ServerConsumerEndpoint consumer = rec.getConsumer();
-	   			
+
 	   			if (consumer != null && consumer.getID().equals(consumerID) && rec.waitingForResponse)
 	   			{
 	   				wait = true;
-	   				
+
 	   				break;
 	   			}
 	   		}
-	   		
+
 	   		if (wait)
 	   		{
 	   			waitingToClose = true;
@@ -1278,41 +1284,41 @@
 	   		}
    		}
    		while (wait && toWait > 0);
-   		
+
    		if (toWait <= 0)
    		{
    			//Clear toDeliver
    			while (toDeliver.poll(0) != null)
    			{
    			}
-   			
+
    			log.warn("Timed out waiting for response to arrive");
-   		}   		
+   		}
    		waitingToClose = false;
    	}
    }
-  
+
    //TODO NOTE! This needs to be synchronized to prevent deliveries coming back
-   //out of order! There maybe some better way of doing this 
+   //out of order! There maybe some better way of doing this
    synchronized void handleDelivery(Delivery delivery, ServerConsumerEndpoint consumer) throws Exception
    {
    	 if (trace) { log.trace(this + " handling delivery " + delivery); }
-   	 
+
    	 DeliveryRecord rec = null;
-   	 
+
    	 long deliveryId = deliveryIdSequence++;
-   	 
+
    	 if (trace) { log.trace("Delivery id is now " + deliveryId); }
-   	 
+
    	 //TODO can't we combine flags isRetainDeliveries and isReplicating - surely they're mutually exclusive?
        if (consumer.isRetainDeliveries())
-       {      	 
+       {
       	 // Add a delivery
 
       	 rec = new DeliveryRecord(delivery, consumer, deliveryId);
-          
+
           deliveries.put(new Long(deliveryId), rec);
-          
+
           if (trace) { log.trace(this + " added delivery " + deliveryId + ": " + delivery); }
        }
        else
@@ -1321,9 +1327,9 @@
        	try
        	{
        		//This basically just releases the memory reference
-       		
+
        		if (trace) { log.trace("Acknowledging delivery now"); }
-       		
+
        		delivery.acknowledge(null);
        	}
        	catch (Throwable t)
@@ -1331,28 +1337,28 @@
        		log.error("Failed to acknowledge delivery", t);
        	}
        }
-       
+
        Message message = delivery.getReference().getMessage();
-       
+
        //Note that we only replicate transacted or client acknowledge sessions
        //There is no point in replicating AUTO_ACK or DUPS_OK
        if (!consumer.isReplicating() || !replicating)
        {
       	 if (trace) { log.trace(this + " doing the delivery straight away"); }
-      	 
+
       	 //Actually do the delivery now
-      	 performDelivery(delivery.getReference(), deliveryId, consumer); 	           
+      	 performDelivery(delivery.getReference(), deliveryId, consumer);
        }
        else if (!message.isReliable())
        {
       	 if (!toDeliver.isEmpty())
       	 {
       		 if (trace) { log.trace("Message is unreliable and there are refs in the toDeliver so adding to list"); }
-      		 
+
       		 //We need to add to the list to prevent non persistent messages overtaking persistent messages from the same
       		 //producer in flight (since np don't need to be replicated)
       		 toDeliver.put(rec);
-      		 
+
       		 //Race check (there's a small chance the message in the queue got removed between the empty check
       		 //and the put so we do another check:
       		 if (toDeliver.peek() == rec)
@@ -1365,9 +1371,9 @@
       	 else
       	 {
       		 if (trace) { log.trace("Message is unreliable, but no deliveries in list so performing delivery now"); }
-      		 
+
       		 // Actually do the delivery now
-         	 performDelivery(delivery.getReference(), deliveryId, consumer); 
+         	 performDelivery(delivery.getReference(), deliveryId, consumer);
       	 }
        }
        else
@@ -1375,13 +1381,13 @@
       	 if (!postOffice.isFirstNode())
       	 {
          	 //We wait for the replication response to come back before actually performing delivery
-         	 
+
          	 if (trace) { log.trace(this + " deferring delivery until we know it's been replicated"); }
-         	 
-         	 rec.waitingForResponse = true;      	 
-         	 
+
+         	 rec.waitingForResponse = true;
+
          	 toDeliver.put(rec);
-         	  
+
          	 postOffice.sendReplicateDeliveryMessage(consumer.getQueueName(), id,
                                                      delivery.getReference().getMessage().getMessageID(),
                                                      deliveryId, true, false);
@@ -1389,50 +1395,50 @@
       	 else
       	 {
       		 //Only node in the cluster so deliver now
-      	 
+
       		 rec.waitingForResponse = false;
-      		 
+
       		 if (trace) { log.trace("First node so actually doing delivery now"); }
-      		 
+
       		 // Actually do the delivery now - we are only node in the cluster
-         	 performDelivery(delivery.getReference(), deliveryId, consumer); 	  
+         	 performDelivery(delivery.getReference(), deliveryId, consumer);
       	 }
-       }       
+       }
    }
-   
+
    void performDelivery(MessageReference ref, long deliveryID, ServerConsumerEndpoint consumer)
    {
    	if (consumer == null)
    	{
    		if (trace) { log.trace(this + " consumer is null, cannot perform delivery"); }
-   		
+
    		return;
    	}
-      
+
       if (consumer.isDead())
       {
          //Ignore any responses that come back after consumer has died
          return;
       }
-   	
+
    	if (trace) { log.trace(this + " performing delivery for " + ref); }
-   	   	
+
       // We send the message to the client on the current thread. The message is written onto the
       // transport and then the thread returns immediately without waiting for a response.
 
       ClientDelivery del = new ClientDelivery(ref.getMessage(), consumer.getID(), deliveryID, ref.getDeliveryCount());
 
       Callback callback = new Callback(del);
-      
+
       try
       {
          // one way invocation, no acknowledgment sent back by the client
          if (trace) { log.trace(this + " submitting message " + ref.getMessage() + " to the remoting layer to be sent asynchronously"); }
-               
-         callbackHandler.handleCallbackOneway(callback);        
-                                 
+
+         callbackHandler.handleCallbackOneway(callback);
+
          //We store the delivery id so we know to wait for any deliveries in transit on close
-         consumer.setLastDeliveryID(deliveryID);  
+         consumer.setLastDeliveryID(deliveryID);
       }
       catch (Throwable t)
       {
@@ -1442,39 +1448,39 @@
          // I need to do my own cleanup at ConnectionManager level.
 
          log.trace(this + " failed to handle callback", t);
-         
-         //We stop the consumer - some time later the lease will expire and the connection will be closed        
+
+         //We stop the consumer - some time later the lease will expire and the connection will be closed
          //which will remove the consumer
-         
+
          consumer.setStarted(false);
-         
+
          consumer.setDead();
 
          //** IMPORTANT NOTE! We must return the delivery NOT null. **
          //This is because if we return NULL then message will remain in the queue, but later
          //the connection checker will cleanup and close this consumer which will cancel all the deliveries in it
-         //including this one, so the message will go back on the queue twice!         
+         //including this one, so the message will go back on the queue twice!
       }
    }
-   
+
    void acknowledgeTransactionally(List acks, Transaction tx) throws Throwable
    {
       if (trace) { log.trace(this + " acknowledging transactionally " + acks.size() + " messages for " + tx); }
-      
+
       DeliveryCallback deliveryCallback = (DeliveryCallback)tx.getCallback(this);
-      
+
       if (deliveryCallback == null)
       {
          deliveryCallback = new DeliveryCallback();
          tx.addCallback(deliveryCallback, this);
       }
-            
+
       for(Iterator i = acks.iterator(); i.hasNext(); )
       {
          Ack ack = (Ack)i.next();
-         
+
          Long id = new Long(ack.getDeliveryID());
-         
+
          //TODO - do this more elegantly
          if (ack instanceof DeliveryInfo)
          {
@@ -1485,20 +1491,20 @@
          		continue;
          	}
          }
-         
+
          DeliveryRecord rec = (DeliveryRecord)deliveries.get(id);
-         
+
          if (rec == null)
          {
             log.warn("Cannot find delivery to acknowledge " + ack);
             continue;
          }
-                           
+
          deliveryCallback.addDeliveryId(id);
          rec.del.acknowledge(tx);
-      }      
+      }
    }
-   
+
    /**
     * Starts this session's Consumers
     */
@@ -1510,7 +1516,7 @@
       {
          consumersClone = new HashMap(consumers);
       }
-      
+
       for(Iterator i = consumersClone.values().iterator(); i.hasNext(); )
       {
          ServerConsumerEndpoint sce = (ServerConsumerEndpoint)i.next();
@@ -1522,22 +1528,22 @@
          {
             sce.stop();
          }
-      }      
-   } 
+      }
+   }
 
    void promptDelivery(final Channel channel)
    {
    	if (trace) { log.trace("Prompting delivery on " + channel); }
-   	
+
       try
       {
          //Prompting delivery must be asynchronous to avoid deadlock
          //but we cannot use one way invocations on cancelDelivery and
-         //cancelDeliveries because remoting one way invocations can 
+         //cancelDeliveries because remoting one way invocations can
          //overtake each other in flight - this problem will
          //go away when we have our own transport and our dedicated connection
          this.executor.execute(new Runnable() { public void run() { channel.deliver();} } );
-         
+
       }
       catch (Throwable t)
       {
@@ -1558,11 +1564,11 @@
    // Protected ------------------------------------------------------------------------------------
 
    // Private --------------------------------------------------------------------------------------
-   
+
    private Delivery cancelDeliveryInternal(Cancel cancel) throws Throwable
    {
       DeliveryRecord rec = (DeliveryRecord)deliveries.remove(new Long(cancel.getDeliveryId()));
-      
+
       if (rec == null)
       {
          //The delivery might not be found, if the session is not replicated (i.e. auto_ack or dups_ok)
@@ -1573,62 +1579,62 @@
       	}
       	return null;
       }
-                 
+
       //Note we check the flag *and* evaluate again, this is because the server and client clocks may
       //be out of synch and don't want to send back to the client a message it thought it has sent to
-      //the expiry queue  
+      //the expiry queue
       boolean expired = cancel.isExpired() || rec.del.getReference().getMessage().isExpired();
-      
+
       //Note we check the flag *and* evaluate again, this is because the server value of maxDeliveries
       //might get changed after the client has sent the cancel - and we don't want to end up cancelling
       //back to the original queue
       boolean reachedMaxDeliveryAttempts =
          cancel.isReachedMaxDeliveryAttempts() || cancel.getDeliveryCount() >= rec.maxDeliveryAttempts;
-                    
-      Delivery del = rec.del;   
-         
+
+      Delivery del = rec.del;
+
       if (!expired && !reachedMaxDeliveryAttempts)
       {
          //Normal cancel back to the queue
-         
+
          del.getReference().setDeliveryCount(cancel.getDeliveryCount());
-         
+
          //Do we need to set a redelivery delay?
-         
+
          if (rec.redeliveryDelay != 0)
          {
             del.getReference().setScheduledDeliveryTime(System.currentTimeMillis() + rec.redeliveryDelay);
          }
-         
+
          if (trace) { log.trace("Cancelling delivery " + cancel.getDeliveryId()); }
          del.cancel();
       }
       else
-      {                  
+      {
          if (expired)
          {
             //Sent to expiry queue
-            
+
             JBossMessage copy = makeCopyForDLQOrExpiry(true, del);
-            
+
             moveInTransaction(copy, del, rec.expiryQueue, false);
          }
          else
          {
             //Send to DLQ
-         	
+
             JBossMessage copy = makeCopyForDLQOrExpiry(false, del);
-            
+
             moveInTransaction(copy, del, rec.dlq, true);
          }
-      }      
-      
+      }
+
       //Need to send a message to the replicant to remove the id
       postOffice.sendReplicateAckMessage(rec.queueName, del.getReference().getMessage().getMessageID());
-      
+
       return rec.del;
-   }      
-   
+   }
+
    private JBossMessage makeCopyForDLQOrExpiry(boolean expiry, Delivery del) throws Exception
    {
       //We copy the message and send that to the dlq/expiry queue - this is because
@@ -1636,112 +1642,112 @@
       //which would barf - this might happen if the same message had been expire from multiple
       //subscriptions of a topic for example
       //We set headers that hold the original message destination, expiry time and original message id
-      
+
    	if (trace) { log.trace("Making copy of message for DLQ or expiry " + del); }
-   	
+
       JBossMessage msg = ((JBossMessage)del.getReference().getMessage());
-      
+
       JBossMessage copy = msg.doCopy();
-      
+
       long newMessageId = sp.getMessageIDManager().getID();
-      
+
       copy.setMessageId(newMessageId);
-      
+
       //reset expiry
       copy.setExpiration(0);
-      
+
       String origMessageId = msg.getJMSMessageID();
-      
+
       String origDest = msg.getJMSDestination().toString();
-            
+
       copy.setStringProperty(JBossMessage.JBOSS_MESSAGING_ORIG_MESSAGE_ID, origMessageId);
-      
+
       copy.setStringProperty(JBossMessage.JBOSS_MESSAGING_ORIG_DESTINATION, origDest);
-      
+
       if (expiry)
       {
          long actualExpiryTime = System.currentTimeMillis();
-         
+
          copy.setLongProperty(JBossMessage.JBOSS_MESSAGING_ACTUAL_EXPIRY_TIME, actualExpiryTime);
       }
-      
+
       return copy;
    }
-   
+
    private void moveInTransaction(JBossMessage msg, Delivery del, Queue queue, boolean dlq) throws Throwable
    {
       Transaction tx = tr.createTransaction();
-      
+
       MessageReference ref = msg.createReference();
-                    
+
       try
-      {               
+      {
          if (queue != null)
-         {          
+         {
             queue.handle(null, ref, tx);
             del.acknowledge(tx);
          }
          else
          {
             log.warn("No " + (dlq ? "DLQ" : "expiry queue") + " has been specified so the message will be removed");
-            
+
             del.acknowledge(tx);
-         }             
-         
-         tx.commit();         
+         }
+
+         tx.commit();
       }
       catch (Throwable t)
       {
          tx.rollback();
          throw t;
-      } 
-      
+      }
+
       //Need to prompt delivery on the dlq/expiry queue
-      
+
       //TODO - are we sure this is the right place to prompt delivery?
       if (queue != null)
       {
          promptDelivery(queue);
       }
    }
-   
+
    private boolean acknowledgeDeliveryInternal(Ack ack) throws Throwable
    {
       if (trace) { log.trace(this + " acknowledging delivery " + ack); }
 
       DeliveryRecord rec = (DeliveryRecord)deliveries.remove(new Long(ack.getDeliveryID()));
-      
+
       if (rec == null)
       {
       	//This can happen if an ack comes in after failover
          log.debug("Cannot find " + ack + " to acknowledge, it was probably acknowledged before");
          return false;
       }
-      
+
       ServerConsumerEndpoint consumer = rec.getConsumer();
-      
+
       if (consumer != null && consumer.isRemote())
       {
          //Optimisation for shared DB - we don't ack in DB - we move
          rec.del.getObserver().acknowledgeNoPersist(rec.del);
       }
       else
-      {      
+      {
          rec.del.acknowledge(null);
       }
-           
+
       //Now replicate the ack
-      
+
       if (rec.replicating && replicating)
       {
       	postOffice.sendReplicateAckMessage(rec.queueName, rec.del.getReference().getMessage().getMessageID());
       }
-      
+
       if (trace) { log.trace(this + " acknowledged delivery " + ack); }
-      
+
       return true;
    }
-   
+
    /* TODO We can combine this with createConsumerDelegateInternal once we move the distinction between queues and topics
     * to the client side, so the server side just deals with queues named by string - i.e MessagingQueue instances
     */
@@ -1751,59 +1757,59 @@
       {
          throw new IllegalStateException("Session is closed");
       }
-      
+
       if ("".equals(selectorString))
       {
          selectorString = null;
       }
-      
+
       if (trace)
       {
          log.trace(this + " creating direct consumer for " + queueName +
             (selectorString == null ? "" : ", selector '" + selectorString + "'"));
       }
-      
+
       Binding binding =  postOffice.getBindingForQueueName(queueName);
-      
+
       if (binding == null)
       {
       	throw new IllegalArgumentException("Cannot find queue with name " + queueName);
       }
-      
+
       String consumerID = GUIDGenerator.generateGUID();
-            
+
       int prefetchSize = connectionEndpoint.getPrefetchSize();
-      
+
       JBossDestination dest = new JBossQueue(queueName);
-      
+
       //We don't care about redelivery delays and number of attempts for a direct consumer
-      
+
       ServerConsumerEndpoint ep =
          new ServerConsumerEndpoint(consumerID, binding.queue,
                                     binding.queue.getName(), this, selectorString, false,
                                     dest, null, null, 0, -1, true, false, prefetchSize);
-      
+
       ConsumerAdvised advised;
-      
+
       // Need to synchronized to prevent a deadlock
       // See http://jira.jboss.com/jira/browse/JBMESSAGING-797
       synchronized (AspectManager.instance())
-      {       
+      {
          advised = new ConsumerAdvised(ep);
       }
-      
+
       Dispatcher.instance.registerTarget(consumerID, advised);
-      
+
       ClientConsumerDelegate stub =
          new ClientConsumerDelegate(consumerID, prefetchSize, -1, 0);
-      
+
       synchronized (consumers)
       {
          consumers.put(consumerID, ep);
       }
-         
-      log.trace(this + " created and registered " + ep);    
-      
+
+      log.trace(this + " created and registered " + ep);
+
       return stub;
    }
 
@@ -1817,12 +1823,12 @@
       {
          throw new IllegalStateException("Session is closed");
       }
-      
+
       if ("".equals(selectorString))
       {
          selectorString = null;
       }
-      
+
       if (trace)
       {
          log.trace(this + " creating consumer for " + jmsDestination +
@@ -1832,12 +1838,12 @@
       }
 
       ManagedDestination mDest = dm.getDestination(jmsDestination.getName(), jmsDestination.isQueue());
-      
+
       if (mDest == null)
       {
          throw new InvalidDestinationException("No such destination: " + jmsDestination + " has it been deployed?");
       }
-      
+
       if (jmsDestination.isTemporary())
       {
          // Can only create a consumer for a temporary destination on the same connection
@@ -1849,28 +1855,28 @@
             throw new IllegalStateException(msg);
          }
       }
-      
+
       String consumerID = GUIDGenerator.generateGUID();
-      
+
       // Always validate the selector first
       Selector selector = null;
-      
+
       if (selectorString != null)
       {
          selector = new Selector(selectorString);
       }
-      
+
       Queue queue;
-      
+
       if (jmsDestination.isTopic())
-      {         
+      {
          if (subscriptionName == null)
          {
             // non-durable subscription
             if (log.isTraceEnabled()) { log.trace(this + " creating new non-durable subscription on " + jmsDestination); }
-            
+
             // Create the non durable sub
-            
+
             queue = new MessagingQueue(nodeId, GUIDGenerator.generateGUID(),
 							                  idm.getID(), ms, pm, false,
 							                  mDest.getMaxSize(), selector,
@@ -1879,27 +1885,27 @@
 							                  mDest.getDownCacheSize(),
 							                  mDest.isClustered(),
 							                  sp.getRecoverDeliveriesTimeout());
-            
+
             JMSCondition topicCond = new JMSCondition(false, jmsDestination.getName());
-                        
-            postOffice.addBinding(new Binding(topicCond, queue, false), false);   
-            
+
+            postOffice.addBinding(new Binding(topicCond, queue, false), false);
+
             queue.activate();
 
             String counterName = TopicService.SUBSCRIPTION_MESSAGECOUNTER_PREFIX + queue.getName();
-  
+
             int dayLimitToUse = mDest.getMessageCounterHistoryDayLimit();
             if (dayLimitToUse == -1)
             {
                //Use override on server peer
                dayLimitToUse = sp.getDefaultMessageCounterHistoryDayLimit();
             }
-            
+
             //We don't create message counters on temp topics
             if (!mDest.isTemporary())
             {
 	            MessageCounter counter =  new MessageCounter(counterName, null, queue, true, false, dayLimitToUse);
-	            
+
 	            sp.getMessageCounterManager().registerMessageCounter(counterName, counter);
             }
          }
@@ -1909,26 +1915,26 @@
             {
                throw new InvalidDestinationException("Cannot create a durable subscription on a temporary topic");
             }
-            
+
             // We have a durable subscription, look it up
             String clientID = connectionEndpoint.getClientID();
             if (clientID == null)
             {
                throw new JMSException("Cannot create durable subscriber without a valid client ID");
             }
-            
+
             // See if there any bindings with the same client_id.subscription_name name
-            
+
             String name = MessageQueueNameHelper.createSubscriptionName(clientID, subscriptionName);
-            
+
             Binding binding = postOffice.getBindingForQueueName(name);
-            
+
             if (binding == null)
             {
                // Does not already exist
-               
+
                if (trace) { log.trace(this + " creating new durable subscription on " + jmsDestination); }
-                              
+
                queue = new MessagingQueue(nodeId, name, idm.getID(),
                                           ms, pm, true,
                                           mDest.getMaxSize(), selector,
@@ -1937,90 +1943,90 @@
                                           mDest.getDownCacheSize(),
                                           mDest.isClustered(),
                                           sp.getRecoverDeliveriesTimeout());
-               
+
                // Durable subs must be bound on ALL nodes of the cluster (if clustered)
-               
+
                postOffice.addBinding(new Binding(new JMSCondition(false, jmsDestination.getName()), queue, true),
                                      postOffice.isClustered() && mDest.isClustered());
-               
+
                queue.activate();
-                  
+
                //We don't create message counters on temp topics
                if (!mDest.isTemporary())
-               {	               
+               {
 	               String counterName = TopicService.SUBSCRIPTION_MESSAGECOUNTER_PREFIX + queue.getName();
-	                       
+
 	               MessageCounter counter =
 	                  new MessageCounter(counterName, subscriptionName, queue, true, true,
 	                                     mDest.getMessageCounterHistoryDayLimit());
-	               
+
 	               sp.getMessageCounterManager().registerMessageCounter(counterName, counter);
                }
             }
             else
             {
                //Durable sub already exists
-            	
+
             	queue = binding.queue;
-            	
+
                if (trace) { log.trace(this + " subscription " + subscriptionName + " already exists"); }
-               
+
             	//Check if it is already has a subscriber
             	//We can't have more than one subscriber at a time on the durable sub unless it is clustered
                //we need this for clustered since otherwise we wouldn't be able to fail over subcribers for the same durable
                //sub onto a node which already has one
-               
+
                if (queue.getLocalDistributor().getNumberOfReceivers() > 0 && !mDest.isClustered())
                {
                	throw new IllegalStateException("Cannot create a subscriber on the durable subscription since it already has subscriber(s)");
                }
-               
+
                // If the durable sub exists because it is clustered and was created on this node due to a bind on another node
                // then it will have no message counter
-               
-               String counterName = TopicService.SUBSCRIPTION_MESSAGECOUNTER_PREFIX + queue.getName();    
-               
+
+               String counterName = TopicService.SUBSCRIPTION_MESSAGECOUNTER_PREFIX + queue.getName();
+
                boolean createCounter = false;
-               
+
                if (sp.getMessageCounterManager().getMessageCounter(counterName) == null)
                {
                	createCounter = true;
                }
-                              
+
                // From javax.jms.Session Javadoc (and also JMS 1.1 6.11.1):
                // A client can change an existing durable subscription by creating a durable
                // TopicSubscriber with the same name and a new topic and/or message selector.
                // Changing a durable subscriber is equivalent to unsubscribing (deleting) the old
                // one and creating a new one.
-               
+
                String filterString = queue.getFilter() != null ? queue.getFilter().getFilterString() : null;
-               
+
                boolean selectorChanged =
                   (selectorString == null && filterString != null) ||
                   (filterString == null && selectorString != null) ||
                   (filterString != null && selectorString != null &&
                            !filterString.equals(selectorString));
-               
+
                if (trace) { log.trace("selector " + (selectorChanged ? "has" : "has NOT") + " changed"); }
-               
+
                String oldTopicName = ((JMSCondition)binding.condition).getName();
-               
+
                boolean topicChanged = !oldTopicName.equals(jmsDestination.getName());
-               
+
                if (log.isTraceEnabled()) { log.trace("topic " + (topicChanged ? "has" : "has NOT") + " changed"); }
-               
+
                if (selectorChanged || topicChanged)
                {
                   if (trace) { log.trace("topic or selector changed so deleting old subscription"); }
-                  
+
                   // Unbind the durable subscription
-                  
+
                   // Durable subs must be unbound on ALL nodes of the cluster
-                  
-                  postOffice.removeBinding(queue.getName(), postOffice.isClustered() && mDest.isClustered());                  
-                  
+
+                  postOffice.removeBinding(queue.getName(), postOffice.isClustered() && mDest.isClustered());
+
                   // create a fresh new subscription
-                                    
+
                   queue = new MessagingQueue(nodeId, name, idm.getID(), ms, pm, true,
 					                              mDest.getMaxSize(), selector,
 					                              mDest.getFullSize(),
@@ -2028,26 +2034,26 @@
 					                              mDest.getDownCacheSize(),
 					                              mDest.isClustered(),
 					                              sp.getRecoverDeliveriesTimeout());
-                  
+
                   // Durable subs must be bound on ALL nodes of the cluster
-                  
+
                   postOffice.addBinding(new Binding(new JMSCondition(false, jmsDestination.getName()), queue, true),
                   		                postOffice.isClustered() && mDest.isClustered());
-  
-                  queue.activate();                  
-                  
+
+                  queue.activate();
+
                   if (!mDest.isTemporary())
                   {
 	                  createCounter = true;
                   }
                }
-               
+
                if (createCounter)
                {
                	MessageCounter counter =
                      new MessageCounter(counterName, subscriptionName, queue, true, true,
                                         mDest.getMessageCounterHistoryDayLimit());
-                  
+
                   sp.getMessageCounterManager().registerMessageCounter(counterName, counter);
                }
             }
@@ -2056,74 +2062,74 @@
       else
       {
          // Consumer on a jms queue
-         
+
          // Let's find the queue
-      	
+
       	queue = postOffice.getBindingForQueueName(jmsDestination.getName()).queue;
-         
+
          if (queue == null)
          {
             throw new IllegalStateException("Cannot find queue: " + jmsDestination.getName());
          }
       }
-      
+
       int prefetchSize = connectionEndpoint.getPrefetchSize();
-      
+
       Queue dlqToUse = mDest.getDLQ() == null ? defaultDLQ : mDest.getDLQ();
-      
+
       Queue expiryQueueToUse = mDest.getExpiryQueue() == null ? defaultExpiryQueue : mDest.getExpiryQueue();
-      
+
       int maxDeliveryAttemptsToUse = mDest.getMaxDeliveryAttempts() == -1 ? defaultMaxDeliveryAttempts : mDest.getMaxDeliveryAttempts();
-          
+
       long redeliveryDelayToUse = mDest.getRedeliveryDelay() == -1 ? defaultRedeliveryDelay : mDest.getRedeliveryDelay();
-      
-      //Is the consumer going to have its session state replicated onto a backup node?      
-      
+
+      //Is the consumer going to have its session state replicated onto a backup node?
+
       boolean replicating = supportsFailover && queue.isClustered() && !(jmsDestination.isTopic() && !queue.isRecoverable());
-      
+
       ServerConsumerEndpoint ep =
          new ServerConsumerEndpoint(consumerID, queue,
                                     queue.getName(), this, selectorString, noLocal,
                                     jmsDestination, dlqToUse, expiryQueueToUse, redeliveryDelayToUse,
                                     maxDeliveryAttemptsToUse, false, replicating, prefetchSize);
-      
+
       if (queue.isClustered() && postOffice.isClustered() && jmsDestination.isTopic() && subscriptionName != null)
       {
       	//Clustered durable sub consumer created - we need to add this info in the replicator - it is needed by other nodes
-      	
+
       	//This is also used to prevent a possible race condition where a clustered durable sub is bound on all nodes
       	//but then unsubscribed before the bind is complete on all nodes, leaving it bound on some nodes and not on others
       	//The bind all is synchronous so by the time we add the x to the replicator we know it is bound on all nodes
       	//and same to unsubscribe
-      	
+
       	Replicator rep = (Replicator)postOffice;
-      	
+
       	rep.put(queue.getName(), DUR_SUB_STATE_CONSUMERS);
       }
-      
+
       ConsumerAdvised advised;
-      
+
       // Need to synchronized to prevent a deadlock
       // See http://jira.jboss.com/jira/browse/JBMESSAGING-797
       synchronized (AspectManager.instance())
-      {       
+      {
          advised = new ConsumerAdvised(ep);
       }
-      
+
       Dispatcher.instance.registerTarget(consumerID, advised);
-      
+
       ClientConsumerDelegate stub =
          new ClientConsumerDelegate(consumerID, prefetchSize, maxDeliveryAttemptsToUse, redeliveryDelayToUse);
-      
+
       synchronized (consumers)
       {
          consumers.put(consumerID, ep);
       }
-         
+
       log.trace(this + " created and registered " + ep);
-      
+
       return stub;
-   }   
+   }
 
    private BrowserDelegate createBrowserDelegateInternal(JBossDestination jmsDestination,
                                                          String selector) throws Throwable
@@ -2149,12 +2155,12 @@
          (selector == null ? "" : ", selector '" + selector + "'"));
 
       Binding binding = postOffice.getBindingForQueueName(jmsDestination.getName());
-      
+
       if (binding == null)
       {
       	throw new IllegalStateException("Cannot find queue with name " + jmsDestination.getName());
       }
-      
+
       String browserID = GUIDGenerator.generateGUID();
 
       ServerBrowserEndpoint ep = new ServerBrowserEndpoint(this, browserID, binding.queue, selector, jmsDestination);
@@ -2166,14 +2172,14 @@
       }
 
       BrowserAdvised advised;
-      
+
       // Need to synchronized to prevent a deadlock
       // See http://jira.jboss.com/jira/browse/JBMESSAGING-797
       synchronized (AspectManager.instance())
-      {       
+      {
          advised = new BrowserAdvised(ep);
       }
-      
+
       Dispatcher.instance.registerTarget(browserID, advised);
 
       ClientBrowserDelegate stub = new ClientBrowserDelegate(browserID);
@@ -2187,17 +2193,17 @@
    {
       //Now prompt delivery on the channels
       Iterator iter = channels.iterator();
-      
+
       while (iter.hasNext())
       {
          DeliveryObserver observer = (DeliveryObserver)iter.next();
-         
+
          promptDelivery((Channel)observer);
       }
    }
-   
+
    // Inner classes --------------------------------------------------------------------------------
-   
+
    /*
     * Holds a record of a delivery - we need to store the consumer id as well
     * hence this class
@@ -2206,34 +2212,34 @@
     * when they were in transit.
     * In such a case we might otherwise end up with the consumer closing but not all it's deliveries being
     * cancelled, which would mean they wouldn't be cancelled until the session is closed which is too late
-    * 
+    *
     * We need to store various pieces of information, such as consumer id, dlq, expiry queue
     * since we need this at cancel time, but by then the actual consumer might have closed
     */
    private static class DeliveryRecord
    {
-   	// We need to cache the attributes here  since the consumer may get gc'd BEFORE the delivery is acked   	
-   	
+   	// We need to cache the attributes here  since the consumer may get gc'd BEFORE the delivery is acked
+
       Delivery del;
-        
+
       Queue dlq;
-      
+
       Queue expiryQueue;
-      
+
       long redeliveryDelay;
-      
+
       int maxDeliveryAttempts;
-      
+
       WeakReference consumerRef;
-      
+
       String queueName;
-      
+
       boolean replicating;
-      
+
       volatile boolean waitingForResponse;
-      
+
       long deliveryID;
-      
+
       ServerConsumerEndpoint getConsumer()
       {
       	if (consumerRef != null)
@@ -2245,50 +2251,50 @@
       		return null;
       	}
       }
-            
+
       DeliveryRecord(Delivery del, Queue dlq, Queue expiryQueue, long redeliveryDelay, int maxDeliveryAttempts,
       		         String queueName, boolean replicating, long deliveryID)
       {
       	this.del = del;
-      	
+
       	this.dlq = dlq;
-      	
+
       	this.expiryQueue = expiryQueue;
-      	
+
       	this.redeliveryDelay = redeliveryDelay;
-      	
+
       	this.maxDeliveryAttempts = maxDeliveryAttempts;
-      	
+
       	this.queueName = queueName;
-      	
+
       	this.replicating = replicating;
-      	
+
       	this.deliveryID = deliveryID;
       }
-      
+
       DeliveryRecord(Delivery del, ServerConsumerEndpoint consumer, long deliveryID)
       {
       	this (del, consumer.getDLQ(), consumer.getExpiryQueue(), consumer.getRedliveryDelay(), consumer.getMaxDeliveryAttempts(),
       			consumer.getQueueName(), consumer.isReplicating(), deliveryID);
 
       	// We need to cache the attributes here  since the consumer may get gc'd BEFORE the delivery is acked
-         
-      	
+
+
          //We hold a WeakReference to the consumer - this is only needed when replicating - where we store the delivery then wait
          //for the response to come back from the replicant before actually performing delivery
          //We need a weak ref since when the consumer closes deliveries may still and remain and we don't want that to prevent
          //the consumer being gc'd
          this.consumerRef = new WeakReference(consumer);
-      }            
-      
+      }
+
    	public String toString()
    	{
    		return "DeliveryRecord " + System.identityHashCode(this) + " del: " + del + " queueName: " + queueName;
    	}
    }
-   
+
    /**
-    * 
+    *
     * The purpose of this class is to remove deliveries from the delivery list on commit
     * Each transaction has once instance of this per SCE
     *
@@ -2296,27 +2302,27 @@
    private class DeliveryCallback implements TxCallback
    {
       List delList = new ArrayList();
-         
+
       public void beforePrepare()
-      {         
+      {
          //NOOP
       }
-      
+
       public void beforeCommit(boolean onePhase)
-      {         
+      {
          //NOOP
       }
-      
+
       public void beforeRollback(boolean onePhase)
-      {         
+      {
          //NOOP
       }
-      
+
       public void afterPrepare()
-      {         
+      {
          //NOOP
       }
-      
+
       public synchronized void afterCommit(boolean onePhase) throws TransactionException
       {
          // Remove the deliveries from the delivery map.
@@ -2324,9 +2330,9 @@
          while (iter.hasNext())
          {
             Long deliveryId = (Long)iter.next();
-            
+
             DeliveryRecord del = (DeliveryRecord)deliveries.remove(deliveryId);
-            
+
             if (del != null && del.replicating)
             {
             	//TODO - we could batch this in one message
@@ -2335,25 +2341,25 @@
             		postOffice.sendReplicateAckMessage(del.queueName, del.del.getReference().getMessage().getMessageID());
             	}
             	catch (Exception e)
-            	{            		
+            	{
             		throw new TransactionException("Failed to handle send ack", e);
             	}
             }
          }
       }
-      
+
       public void afterRollback(boolean onePhase) throws TransactionException
-      {                            
+      {
          //One phase rollbacks never hit the server - they are dealt with locally only
          //so this would only ever be executed for a two phase rollback.
 
          //We don't do anything since cancellation is driven from the client.
       }
-      
+
       synchronized void addDeliveryId(Long deliveryId)
       {
          delList.add(deliveryId);
       }
    }
-   
+
 }

Modified: branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/PersistenceManager.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/PersistenceManager.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/PersistenceManager.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -40,116 +40,116 @@
 public interface PersistenceManager extends MessagingComponent
 {
    void addReference(long channelID, MessageReference ref, Transaction tx) throws Exception;
-   
+
    void moveReference(long sourceChannelID, long destChannelID, MessageReference ref) throws Exception;
 
    void removeReference(long channelID, MessageReference ref, Transaction tx) throws Exception;
-   
+
    void updateDeliveryCount(long channelID, MessageReference ref) throws Exception;
-   
+
    // XA Recovery functionality
-   
+
    List retrievePreparedTransactions() throws Exception;
-   
+
    List getMessageChannelPairRefsForTx(long transactionId) throws Exception;
 
    List getMessageChannelPairAcksForTx(long transactionId) throws Exception;
 
-      
+
    // Paging functionality - TODO we should split this out into its own interface
 
    void pageReferences(long channelID, List references, boolean paged) throws Exception;
-   
+
    void removeDepagedReferences(long channelID, List refs) throws Exception;
-    
+
    void updatePageOrder(long channelID, List references) throws Exception;
-   
+
    void updateReferencesNotPagedInRange(long channelID, long orderStart, long orderEnd, long num) throws Exception;
-   
+
    List getPagedReferenceInfos(long channelID, long orderStart, int number) throws Exception;
-   
+
    InitialLoadInfo loadFromStart(long channelID, int fullSize) throws Exception;
-   
-   void mergeTransactions (long fromChannelID, long toChannelID) throws Exception;
 
+   void mergeTransactions (int fromNodeID, int toNodeID) throws Exception;
+
    InitialLoadInfo mergeAndLoad(long fromChannelID, long toChannelID, int numberToLoad,
                                 long firstPagingOrder, long nextPagingOrder) throws Exception;
-     
+
    List getMessages(List messageIds) throws Exception;
-         
+
    //Counter related functionality - TODO we should split this out into its own interface
-   
+
    long reserveIDBlock(String counterName, int size) throws Exception;
-   
-   // Failover elated functionality (checkDuplicates on send)
 
-   boolean referenceExists(long messageID) throws Exception;
+   // Duplicate detection
 
+   boolean idExists(String messageID) throws Exception;
+
    // Interface value classes ----------------------------------------------------------------------
 
    class MessageChannelPair
    {
       private Message message;
-      
+
       private long channelId;
-      
+
       public MessageChannelPair(Message message, long channelId)
       {
          this.message = message;
-         
+
          this.channelId = channelId;
       }
-      
+
       public Message getMessage()
       {
          return message;
       }
-      
+
       public long getChannelId()
       {
          return channelId;
       }
    }
-   
+
    class ReferenceInfo
    {
       private long messageId;
-      
+
       private int deliveryCount;
-      
+
       private long scheduledDelivery;
-      
+
       public ReferenceInfo(long msgId, int deliveryCount, long scheduledDelivery)
       {
          this.messageId = msgId;
-         
+
          this.deliveryCount = deliveryCount;
-         
+
          this.scheduledDelivery = scheduledDelivery;
-      }    
-      
+      }
+
       public long getMessageId()
       {
          return messageId;
       }
- 
+
       public int getDeliveryCount()
       {
          return deliveryCount;
-      }      
-      
+      }
+
       public long getScheduledDelivery()
       {
          return scheduledDelivery;
       }
    }
-   
+
    class InitialLoadInfo
    {
       private Long minPageOrdering;
-      
+
       private Long maxPageOrdering;
-      
+
       private List refInfos;
 
       public InitialLoadInfo(Long minPageOrdering, Long maxPageOrdering, List refInfos)
@@ -168,11 +168,11 @@
       {
          return minPageOrdering;
       }
-      
+
       public List getRefInfos()
       {
          return refInfos;
       }
    }
-   
+
 }

Modified: branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/Queue.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/Queue.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/messaging/core/contract/Queue.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -39,59 +39,59 @@
 public interface Queue extends Channel
 {
    Filter getFilter();
-   
+
    /**
     * Merge the contents of one queue with another - this happens at failover when a queue is failed
     * over to another node, but a queue with the same name already exists. In this case we merge the
     * two queues.
     */
    void mergeIn(long channelID, int nodeID) throws Exception;
-   
-   /* 
-    * TODO - this method does not really belong here - the only reason it is, is because we create the 
+
+   /*
+    * TODO - this method does not really belong here - the only reason it is, is because we create the
     * queues in the post office on startup but paging info is only known at deploy time
     */
    void setPagingParams(int fullSize, int pageSize, int downCacheSize);
-   
+
    int getFullSize();
-   
+
    int getPageSize();
-   
+
    int getDownCacheSize();
-   
+
    boolean isClustered();
-   
+
    String getName();
-   
+
    int getNodeID();
-   
+
    long getRecoverDeliveriesTimeout();
-   
+
    Distributor getLocalDistributor();
-   
-   Distributor getRemoteDistributor();   
-   
+
+   Distributor getRemoteDistributor();
+
    void registerSucker(MessageSucker sucker);
-   
+
    boolean unregisterSucker(MessageSucker sucker);
-   
+
    void addToRecoveryArea(int nodeID, long messageID, String sessionID);
-   
+
    void removeFromRecoveryArea(int nodeID, long messageID);
-   
+
    void removeAllFromRecoveryArea(int nodeID);
-   
+
    void addAllToRecoveryArea(int nodeID, Map ids);
-   
-   List recoverDeliveries(List messageIds);  
-   
+
+   List recoverDeliveries(List messageIds);
+
    void removeStrandedReferences(String sessionID);
-   
+
    //For testing only
    Map getRecoveryArea();
-   
+
    int getRecoveryMapSize();
-   
+
    //Optimisation for shared database
-   Delivery handleMove(MessageReference ref, long sourceChannelID);   
+   Delivery handleMove(MessageReference ref, long sourceChannelID);
 }

Modified: branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/ChannelSupport.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/ChannelSupport.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/ChannelSupport.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -48,11 +48,11 @@
 import EDU.oswego.cs.dl.util.concurrent.SynchronizedInt;
 
 /**
- * 
+ *
  * This class provides much of the functionality needed to implement a channel.
- * 
+ *
  * This partial implementation supports atomicity, isolation and recoverability for reliable messages.
- * 
+ *
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @version <tt>$Revision$</tt> $Id: ChannelSupport.java,v 1.65
@@ -85,22 +85,22 @@
    protected Object lock;
 
    protected volatile boolean active;
-   
+
    //TODO - I would like to get rid of this - the only reason we still keep a count of
    //refs being delivered is because many tests require this
    //Having to keep this count requires synchronization between delivery thread and acknowledgement
    //thread which will hamper concurrency
    //Suggest that we have a flag that disables this for production systems
    protected SynchronizedInt deliveringCount;
-    
+
    protected Set scheduledDeliveries;
-   
+
    //The maximum number of refs this queue can hold, or -1 if no limit
    //If any more refs are added after this point they are dropped
    protected int maxSize;
-  
+
    protected SynchronizedInt messagesAdded;
-    
+
    // Constructors ---------------------------------------------------------------------------------
 
    protected ChannelSupport(long channelID, PersistenceManager pm,
@@ -117,61 +117,61 @@
       messageRefs = new BasicPriorityLinkedList(10);
 
       lock = new Object();
-      
+
       deliveringCount = new SynchronizedInt(0);
-      
+
       scheduledDeliveries = new HashSet();
-      
+
       this.maxSize = maxSize;
-      
+
       messagesAdded = new SynchronizedInt(0);
    }
-   
+
    // Receiver implementation ----------------------------------------------------------------------
-   
+
    //Optimisation
    public Delivery handleMove(MessageReference ref, long sourceChannelID)
    {
       if (!isActive())
-      {  
+      {
          if (trace) { log.trace(this + " is not active, returning null delivery for " + ref); }
-         
+
          return null;
       }
 
       checkClosed();
-           
+
       if (trace) { log.trace(this + " moving ref " + ref + " from channel " + sourceChannelID); }
-      
+
       if (maxSize != -1 && getMessageCount() >= maxSize)
       {
          //Have reached maximum size - will drop message
-         
+
          log.warn(this + " has reached maximum size, " + ref + " will be dropped");
-         
+
          return null;
       }
-   
+
       // Each channel has its own copy of the reference
       ref = ref.copy();
 
       try
-      {           
+      {
          if (ref.getMessage().isReliable() && recoverable)
          {
             // Reliable message in a recoverable state - also add to db
             if (trace) { log.trace(this + " adding " + ref + " to database non-transactionally"); }
-            
-            pm.moveReference(sourceChannelID, channelID, ref);        
+
+            pm.moveReference(sourceChannelID, channelID, ref);
          }
-         
+
          synchronized (lock)
          {
             addReferenceInMemory(ref);
-            
+
             deliverInternal();
          }
-            
+
          messagesAdded.increment();
       }
       catch (Throwable t)
@@ -181,62 +181,62 @@
          return null;
       }
 
-      return new SimpleDelivery(this, ref, true, false);  
+      return new SimpleDelivery(this, ref, true, false);
    }
-   
+
    public Delivery handle(DeliveryObserver sender, MessageReference ref, Transaction tx)
    {
       if (!isActive())
-      {	
+      {
       	if (trace) { log.trace(this + " is not active, returning null delivery for " + ref); }
-      	
+
          return null;
       }
 
       checkClosed();
-      
+
       if (ref == null)
       {
          return null;
       }
 
       if (trace) { log.trace(this + " handles " + ref + (tx == null ? " non-transactionally" : " in transaction: " + tx)); }
-      
+
       if (maxSize != -1 && getMessageCount() >= maxSize)
       {
          //Have reached maximum size - will drop message
-         
+
          log.warn(this + " has reached maximum size, " + ref + " will be dropped");
-         
+
          return null;
       }
-   
+
       // Each channel has its own copy of the reference
       ref = ref.copy();
 
       try
-      {           
+      {
          if (tx == null)
          {
             if (ref.getMessage().isReliable() && recoverable)
             {
                // Reliable message in a recoverable state - also add to db
                if (trace) { log.trace(this + " adding " + ref + " to database non-transactionally"); }
-               
-               pm.addReference(channelID, ref, null);        
+
+               pm.addReference(channelID, ref, null);
             }
-            
+
             // If the ref has a scheduled delivery time then we don't add to the in memory queue
             // instead we create a timeout, so when that time comes delivery will attempted directly
-            
+
             if (!checkAndSchedule(ref))
-            {               
+            {
                synchronized (lock)
                {
                   addReferenceInMemory(ref);
-                  
+
                   deliverInternal();
-               }            
+               }
             }
          }
          else
@@ -245,9 +245,9 @@
 
             // add to post commit callback
             getCallback(tx).addRef(ref);
-            
+
             if (trace) { log.trace(this + " added transactionally " + ref + " in memory"); }
-            
+
             if (ref.getMessage().isReliable() && recoverable)
             {
                // Reliable message in a recoverable state - also add to db
@@ -256,7 +256,7 @@
                pm.addReference(channelID, ref, tx);
             }
          }
-         
+
          messagesAdded.increment();
       }
       catch (Throwable t)
@@ -266,7 +266,7 @@
          return null;
       }
 
-      return new SimpleDelivery(this, ref, true, false);     
+      return new SimpleDelivery(this, ref, true, false);
    }
 
    // DeliveryObserver implementation --------------------------------------------------------------
@@ -277,7 +277,7 @@
 
       acknowledgeInternal(d, tx, true);
    }
-   
+
    public void acknowledgeNoPersist(Delivery d) throws Throwable
    {
       acknowledgeInternal(d, null, false);
@@ -286,25 +286,25 @@
    public void cancel(Delivery del) throws Throwable
    {
       //We may need to update the delivery count in the database
-      
+
       MessageReference ref = del.getReference();
-      
+
       if (ref.getMessage().isReliable())
       {
          pm.updateDeliveryCount(this.channelID, ref);
       }
-            
+
       if (!del.isRecovered())
       {
       	deliveringCount.decrement();
       }
-      
+
       if (!checkAndSchedule(ref))
       {
          cancelInternal(ref);
       }
-   }      
-        
+   }
+
    // Channel implementation -----------------------------------------------------------------------
 
    public long getChannelID()
@@ -340,23 +340,23 @@
             messages.add(ref.getMessage());
          }
          return messages;
-      }      
+      }
    }
- 
+
    public void deliver()
    {
       checkClosed();
-      
+
       synchronized (lock)
-      {      
+      {
 	      if (distributor != null && distributor.getNumberOfReceivers() > 0)
-	      {         
+	      {
 	         setReceiversReady(true);
-	            
-	         deliverInternal();                  
+
+	         deliverInternal();
 	      }
-      }     
-   }      
+      }
+   }
 
    public void close()
    {
@@ -365,10 +365,10 @@
 	      if (distributor != null)
 	      {
 	         distributor.clear();
-	         
+
 	         distributor = null;
 	      }
-	      
+
 	      clearAllScheduledDeliveries();
    	}
    }
@@ -382,7 +382,7 @@
     *
     */
    public void removeAllReferences() throws Throwable
-   { 
+   {
       synchronized (lock)
       {
          if (deliveringCount.get() > 0)
@@ -390,9 +390,9 @@
             throw new IllegalStateException("Cannot remove references while deliveries are in progress, there are " +
             		                           deliveringCount.get());
          }
-         
-         log.trace(this + " removing all references, there are " + this.messageRefs.size());       
-         
+
+         log.trace(this + " removing all references, there are " + this.messageRefs.size());
+
          //Now we consume the rest of the messages
          //This may take a while if we have a lot of messages including perhaps millions
          //paged in the database - but there's no obvious other way to do it.
@@ -407,18 +407,18 @@
          while ((ref = removeFirstInMemory()) != null)
          {
          	log.trace("Removing ref " + ref);
-         	
+
             SimpleDelivery del = new SimpleDelivery(this, ref);
 
             del.acknowledge(null);
          }
-         
+
          deliveringCount.set(0);
-         
+
          log.trace(this + " done removing all references, there are " + this.messageRefs.size());
       }
-      
-      clearAllScheduledDeliveries();            
+
+      clearAllScheduledDeliveries();
    }
 
    public List undelivered(Filter filter)
@@ -457,18 +457,18 @@
    public int getMessageCount()
    {
       synchronized (lock)
-      {      
+      {
       	if (trace) { log.trace("Getting message count mr: "+  messageRefs.size() + " dc " + getDeliveringCount() + " sc " + getScheduledCount()); }
-      	
+
          return messageRefs.size() + getDeliveringCount() + getScheduledCount();
       }
    }
-   
+
    public int getDeliveringCount()
    {
       return deliveringCount.get();
    }
-   
+
    public int getScheduledCount()
    {
       synchronized (scheduledDeliveries)
@@ -479,19 +479,19 @@
 
    public void activate()
    {
-      active = true;               
+      active = true;
    }
 
    public void deactivate()
    {
-      active = false;               
+      active = false;
    }
 
    public boolean isActive()
    {
-      return active;               
-   }   
-   
+      return active;
+   }
+
    public int getMaxSize()
    {
       synchronized (lock)
@@ -499,13 +499,13 @@
          return maxSize;
       }
    }
-   
+
    public void setMaxSize(int newSize)
    {
       synchronized (lock)
       {
          int count = getMessageCount();
-         
+
          if (newSize != -1 && count > newSize)
          {
             log.warn("Cannot set maxSize to " + newSize + " since there are already " + count + " refs");
@@ -516,7 +516,7 @@
          }
       }
    }
-   
+
    public int getMessagesAdded()
    {
       return messagesAdded.get();
@@ -534,24 +534,24 @@
    }
 
    // Package protected ----------------------------------------------------------------------------
-   
+
    // Protected ------------------------------------------------------------------------------------
-   
+
    protected void clearAllScheduledDeliveries()
    {
       synchronized (scheduledDeliveries)
       {
          Set clone = new HashSet(scheduledDeliveries);
-         
+
          Iterator iter = clone.iterator();
-         
+
          while (iter.hasNext())
          {
             Timeout timeout = (Timeout)iter.next();
-            
+
             timeout.cancel();
          }
-         
+
          scheduledDeliveries.clear();
       }
    }
@@ -564,10 +564,10 @@
       {
          messageRefs.addFirst(ref, ref.getMessage().getPriority());
       }
-                  
+
       if (trace) { log.trace(this + " added " + ref + " back into state"); }
    }
-   
+
    /**
     * This methods delivers as many messages as possible to the distributor until no more deliveries are
     * returned. This method should never be called at the same time as handle.
@@ -577,41 +577,41 @@
    protected void deliverInternal()
    {
       if (trace) { log.trace(this + " was prompted delivery"); }
-  
+
       try
       {
          // The iterator is used to iterate through the refs in the channel in the case that they
          // don't match the selectors of any receivers.
          ListIterator iter = null;
-         
+
          MessageReference ref = null;
-         
+
          if (!getReceiversReady())
          {
          	if (trace) { log.trace(this + " receivers not ready so not delivering"); }
-         	
+
             return;
          }
-         
+
          while (true)
-         {           
-            ref = nextReference(iter);               
-                     
+         {
+            ref = nextReference(iter);
+
             if (ref != null)
             {
                // Attempt to push the ref to a receiver
-               
-               if (trace) { log.trace(this + " pushing " + ref); }   
-               
+
+               if (trace) { log.trace(this + " pushing " + ref); }
+
                Delivery del = distributor.handle(this, ref, null);
-               
+
                setReceiversReady(del != null);
-               
+
                if (del == null)
                {
                   // No receiver, broken receiver or full receiver so we stop delivering
                   if (trace) { log.trace(this + " got no delivery for " + ref + " so no receiver got the message. Stopping delivery."); }
-                               
+
                   break;
                }
                else if (!del.isSelectorAccepted())
@@ -619,115 +619,115 @@
                   // No receiver accepted the message because no selectors matched, so we create
                   // an iterator (if we haven't already created it) to iterate through the refs
                   // in the channel. No delivery was really performed
-                  
+
                   if (iter == null)
                   {
                      iter = messageRefs.iterator();
-                     
+
                      //We just tried the first one, so we don't want to try it again
                      iter.next();
-                  }                     
+                  }
                }
                else
                {
                   if (trace) { log.trace(this + ": " + del + " returned for message " + ref); }
-                  
+
                   // Receiver accepted the reference
 
                   synchronized (lock)
                   {
                      if (iter == null)
                      {
-                        if (trace) { log.trace(this + " removing first ref in memory"); } 
-                        
+                        if (trace) { log.trace(this + " removing first ref in memory"); }
+
                         removeFirstInMemory();
                      }
                      else
                      {
-                        if (trace) { log.trace(this + " removed current message from iterator"); }                           
-                                    
-                        iter.remove();                                
+                        if (trace) { log.trace(this + " removed current message from iterator"); }
+
+                        iter.remove();
                      }
                   }
-                                  
-                  deliveringCount.increment();                     
-               }               
+
+                  deliveringCount.increment();
+               }
             }
             else
             {
                // No more refs in channel or only ones that don't match any selectors
                if (trace) { log.trace(this + " no more refs to deliver "); }
-               
+
                break;
-            }            
-         }         
+            }
+         }
       }
       catch (Throwable t)
       {
          log.error(this + " Failed to deliver", t);
       }
    }
-   
+
    protected boolean deliverScheduled(MessageReference ref)
    {
       try
-      {      
+      {
          // We synchonize on the ref lock to prevent scheduled deivery kicking in before
          // load has finished
          synchronized (lock)
          {
             // Attempt to push the ref to a receiver
-            
-            if (trace) { log.trace(this + " pushing " + ref); }                                  
-   
+
+            if (trace) { log.trace(this + " pushing " + ref); }
+
             Delivery del = distributor.handle(this, ref, null);
-   
+
             setReceiversReady(del != null);
-            
+
             if (del == null)
             {
                // No receiver, broken receiver or full receiver so we stop delivering
                if (trace) { log.trace(this + ": no delivery returned for message" + ref + " so no receiver got the message. Delivery is now complete"); }
-   
+
                return false;
             }
             else if (del.isSelectorAccepted())
             {
                if (trace) { log.trace(this + ": " + del + " returned for message:" + ref); }
-               
+
                // Receiver accepted the reference
-               
-               deliveringCount.increment();                   
-               
+
+               deliveringCount.increment();
+
                return true;
-            }                
+            }
          }
       }
       catch (Throwable t)
       {
          log.error(this + " Failed to deliver", t);
       }
-      
+
       return false;
    }
-         
+
    protected boolean checkAndSchedule(MessageReference ref)
    {
       if (ref.getScheduledDeliveryTime() > System.currentTimeMillis())
-      {      
+      {
          if (trace) { log.trace("Scheduling delivery for " + ref + " to occur at " + ref.getScheduledDeliveryTime()); }
-         
+
          // Schedule the cancel to actually occur at the specified time. Need to synchronize to
          // prevent timeout being removed before it is added.
          synchronized (scheduledDeliveries)
-         {            
+         {
             Timeout timeout =
                MessagingTimeoutFactory.instance.getFactory().
                   schedule(ref.getScheduledDeliveryTime(), new DeliverRefTimeoutTarget(ref));
-            
+
             scheduledDeliveries.add(timeout);
-         }      
-         
+         }
+
          return true;
       }
       else
@@ -735,16 +735,16 @@
          return false;
       }
    }
-   
+
    protected void acknowledgeInternal(Delivery d, Transaction tx, boolean persist) throws Exception
-   {   
+   {
       if (tx == null)
-      {            
+      {
          if (persist && recoverable && d.getReference().getMessage().isReliable())
          {
             pm.removeReference(channelID, d.getReference(), null);
          }
-              
+
          if (!d.isRecovered())
          {
          	deliveringCount.decrement();
@@ -753,9 +753,9 @@
       else
       {
          this.getCallback(tx).addDelivery(d);
-   
+
          if (trace) { log.trace(this + " added " + d + " to memory on transaction " + tx); }
-   
+
          if (recoverable && d.getReference().getMessage().isReliable())
          {
             pm.removeReference(channelID, d.getReference(), tx);
@@ -765,7 +765,7 @@
 
    protected InMemoryCallback getCallback(Transaction tx)
    {
-      InMemoryCallback callback = (InMemoryCallback) tx.getCallback(this);            
+      InMemoryCallback callback = (InMemoryCallback) tx.getCallback(this);
 
       if (callback == null)
       {
@@ -776,37 +776,37 @@
 
       return callback;
    }
- 
+
    protected MessageReference removeFirstInMemory() throws Exception
    {
       MessageReference result = (MessageReference) messageRefs.removeFirst();
 
       return (MessageReference) result;
    }
-   
+
    protected void addReferenceInMemory(MessageReference ref) throws Exception
    {
       messageRefs.addLast(ref, ref.getMessage().getPriority());
 
-      if (trace){ log.trace(this + " added " + ref + " non-transactionally in memory"); }      
-   }    
-   
+      if (trace){ log.trace(this + " added " + ref + " non-transactionally in memory"); }
+   }
+
    protected boolean getReceiversReady()
    {
    	return receiversReady;
    }
-   
+
    protected void setReceiversReady(boolean receiversReady)
    {
    	this.receiversReady = receiversReady;
    }
-   
+
    // Private --------------------------------------------------------------------------------------
-      
+
    private MessageReference nextReference(ListIterator iter) throws Throwable
    {
       MessageReference ref;
-      
+
       if (iter == null)
       {
          //We just get the next ref from the head of the queue
@@ -816,20 +816,20 @@
       {
          // TODO This will not work with paged refs - see http://jira.jboss.com/jira/browse/JBMESSAGING-275
          // We need to extend it to work with refs from the db
-         
+
          //We have an iterator - this means we are iterating through the queue to find a ref that matches
          if (iter.hasNext())
-         {                        
+         {
             ref = (MessageReference)iter.next();
-         } 
+         }
          else
          {
             ref = null;
          }
       }
-      
+
       return ref;
-   } 
+   }
 
    // Inner classes --------------------------------------------------------------------------------
 
@@ -838,14 +838,14 @@
       private List refsToAdd;
 
       private List deliveriesToRemove;
-      
+
       private InMemoryCallback()
       {
          refsToAdd = new ArrayList();
 
          deliveriesToRemove = new ArrayList();
       }
-      
+
       private void addRef(MessageReference ref)
       {
          refsToAdd.add(ref);
@@ -875,27 +875,27 @@
       {
          // NOOP
       }
-      
+
       public void afterCommit(boolean onePhase) throws Exception
-      {         
+      {
          try
          {
             // We add the references to the state (or schedule them if appropriate)
-         	
+
          	boolean promptDelivery = false;
-            
+
             for(Iterator i = refsToAdd.iterator(); i.hasNext(); )
             {
                MessageReference ref = (MessageReference)i.next();
-               
+
                if (checkAndSchedule(ref))
                {
                	if (trace) { log.trace(this + ": scheduled " + ref); }
                }
                else
-               {	
+               {
 	               if (trace) { log.trace(this + ": adding " + ref + " to memory"); }
-	               
+
 	               try
 	               {
 	                  synchronized (lock)
@@ -907,14 +907,14 @@
 	               {
 	                  throw new TransactionException("Failed to add reference", t);
 	               }
-               
+
 	               //Only need to prompt delivery if refs were added
 	               promptDelivery = true;
                }
             }
 
             // Remove deliveries
-            
+
             for(Iterator i = deliveriesToRemove.iterator(); i.hasNext(); )
             {
                Delivery del = (Delivery)i.next();
@@ -926,7 +926,7 @@
                	deliveringCount.decrement();
                }
             }
-            
+
             // prompt delivery
             if (promptDelivery)
             {
@@ -941,7 +941,7 @@
             log.error("failed to commit", t);
             throw new Exception("Failed to commit", t);
          }
-         
+
       }
 
       public void afterRollback(boolean onePhase) throws Exception
@@ -974,9 +974,9 @@
    }
 
    // Private --------------------------------------------------------------------------------------
-   
+
    // Inner classes --------------------------------------------------------------------------------
-      
+
    private class DeliverRefTimeoutTarget implements TimeoutTarget
    {
       private MessageReference ref;
@@ -989,24 +989,24 @@
       public void timedOut(Timeout timeout)
       {
          if (trace) { log.trace("Scheduled delivery timeout " + ref); }
-         
+
          synchronized (scheduledDeliveries)
          {
             boolean removed = scheduledDeliveries.remove(timeout);
-            
+
             if (!removed)
             {
                throw new IllegalStateException("Failed to remove timeout " + timeout);
             }
          }
-              
+
          ref.setScheduledDeliveryTime(0);
-         
+
          boolean delivered = false;
-         
+
          if (distributor.getNumberOfReceivers() > 0)
-         {               
-            delivered = deliverScheduled(ref);     
+         {
+            delivered = deliverScheduled(ref);
          }
 
          if (!delivered)

Modified: branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/JDBCPersistenceManager.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/JDBCPersistenceManager.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/JDBCPersistenceManager.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -44,11 +44,14 @@
 import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Semaphore;
 
 import javax.sql.DataSource;
 import javax.transaction.TransactionManager;
 import javax.transaction.xa.Xid;
 
+import org.jboss.jms.message.JBossMessage;
 import org.jboss.jms.tx.MessagingXid;
 import org.jboss.logging.Logger;
 import org.jboss.messaging.core.contract.Message;
@@ -65,18 +68,17 @@
 
 /**
  * JDBC implementation of PersistenceManager
- * 
+ *
  * @author <a href="mailto:ovidiu at jboss.org">Ovidiu Feodorov</a>
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @author <a href="mailto:adrian at jboss.org">Adrian Brock</a>
  * @author <a href="mailto:juha at jboss.org">Juha Lindfors</a>
- * 
+ *
  * @version <tt>1.1</tt>
- * 
+ *
  * JDBCPersistenceManager.java,v 1.1 2006/02/22 17:33:41 timfox Exp
  */
-public class JDBCPersistenceManager extends JDBCSupport implements
-      PersistenceManager
+public class JDBCPersistenceManager extends JDBCSupport implements PersistenceManager
 {
    // Constants -----------------------------------------------------
 
@@ -93,7 +95,7 @@
 
    private int maxParams;
 
-   private short orderCount;
+   private RotatingID orderingID;
 
    private int nodeID;
 
@@ -105,12 +107,26 @@
    // update)
    private boolean supportsBlobSelect;
 
+   private boolean detectDuplicates;
+
+   private Map<Integer, String> idCache = new ConcurrentHashMap<Integer, String>();
+
+   private Map<Integer, String> failedOverIdCache = new ConcurrentHashMap<Integer, String>();
+
+   //Use semaphore - performs better with high contention than synchronized
+   private Semaphore lock = new Semaphore(1);
+
+   private int idCacheCounter = 0;
+
+   private final int idCacheSize;
+
    // Constructors --------------------------------------------------
 
    public JDBCPersistenceManager(DataSource ds, TransactionManager tm,
          Properties sqlProperties, boolean createTablesOnStartup,
          boolean usingBatchUpdates, boolean usingBinaryStream,
-         boolean usingTrailingByte, int maxParams, boolean supportsBlobSelect)
+         boolean usingTrailingByte, int maxParams, boolean supportsBlobSelect,
+         boolean detectDuplicates, int idCacheSize)
    {
       super(ds, tm, sqlProperties, createTablesOnStartup);
 
@@ -124,8 +140,21 @@
       this.maxParams = maxParams;
 
       this.supportsBlobSelect = supportsBlobSelect;
+
+      this.detectDuplicates = detectDuplicates;
+
+      this.idCacheSize = idCacheSize;
    }
 
+   public JDBCPersistenceManager(DataSource ds, TransactionManager tm,
+         Properties sqlProperties, boolean createTablesOnStartup,
+         boolean usingBatchUpdates, boolean usingBinaryStream,
+         boolean usingTrailingByte, int maxParams, boolean supportsBlobSelect)
+   {
+      this (ds, tm, sqlProperties, createTablesOnStartup, usingBatchUpdates, usingBinaryStream, usingTrailingByte,
+            maxParams, supportsBlobSelect, false, 0);
+   }
+
    // MessagingComponent overrides ---------------------------------
 
    public void start() throws Exception
@@ -187,7 +216,7 @@
                selectCount = conn.createStatement();
                rset = selectCount.executeQuery(this
                      .getSQLStatement("CHECK_DUAL"));
-               
+
                // if JBM_DUAL is empty, and if an exception happened, we should
                // warn!
                // if JBM_DUAL has a line already, we don't care about the
@@ -230,9 +259,21 @@
          wrap.end();
       }
 
+      if (detectDuplicates)
+      {
+         loadIDCache(idCache, nodeID);
+      }
+
       log.debug(this + " started");
    }
 
+   public void stop() throws Exception
+   {
+      super.stop();
+
+      idCache.clear();
+   }
+
    // Injection -------------------------------------------------
 
    // This is only known by server peer so we inject it after startup
@@ -242,6 +283,8 @@
       this.nodeID = nodeID;
 
       this.nodeIDSet = true;
+
+      this.orderingID = new RotatingID(nodeID);
    }
 
    // PersistenceManager implementation -------------------------
@@ -403,26 +446,26 @@
                else
                {
                   long nextId = rs.getLong(1);
-   
+
                   rs.close();
                   ps.close();
-   
+
                   String updateCounterSQL = getSQLStatement("UPDATE_COUNTER");
-   
+
                   ps = conn.prepareStatement(updateCounterSQL);
-   
+
                   ps.setLong(1, nextId + size);
                   ps.setString(2, counterName);
-   
+
                   int rows = ps.executeUpdate();
-   
+
                   if (trace)
                   {
                      log.trace(JDBCUtil.statementToString(updateCounterSQL,
                            new Long(nextId + size), counterName)
                            + " updated " + rows + " rows");
                   }
-   
+
                   return nextId;
                }
             }
@@ -935,7 +978,7 @@
          {
             maxOrdering = null;
          }
-         
+
          rs.close();
 
          ps.close();
@@ -1037,18 +1080,18 @@
    // Merging functionality
    // --------------------
 
-   public void mergeTransactions(final long fromChannelID,
-         final long toChannelID) throws Exception
+   public void mergeTransactions(final int fromNodeID,
+         final int toNodeID) throws Exception
    {
       if (trace)
       {
-         log.trace("Merging transactions from channel " + fromChannelID
-               + " to " + toChannelID);
+         log.trace("Merging transactions from channel " + fromNodeID
+               + " to " + toNodeID);
       }
 
       // Sanity check
 
-      if (fromChannelID == toChannelID) { throw new IllegalArgumentException(
+      if (fromNodeID == toNodeID) { throw new IllegalArgumentException(
             "Cannot merge transactions - they have the same channel id!!"); }
 
       class MergeTransactionsRunner extends JDBCTxRunner2
@@ -1059,12 +1102,12 @@
             try
             {
                statement = conn.prepareStatement(getSQLStatement("UPDATE_TX"));
-               statement.setLong(1, toChannelID);
-               statement.setLong(2, fromChannelID);
+               statement.setInt(1, toNodeID);
+               statement.setInt(2, fromNodeID);
                int affected = statement.executeUpdate();
 
                log.debug("Merged " + affected + " transactions from channel "
-                     + fromChannelID + " into node " + toChannelID);
+                     + fromNodeID + " into node " + toNodeID);
 
                return null;
             }
@@ -1076,6 +1119,11 @@
       }
 
       new MergeTransactionsRunner().executeWithRetry();
+
+      if (detectDuplicates)
+      {
+         loadIDCache(failedOverIdCache, fromNodeID);
+      }
    }
 
    public InitialLoadInfo mergeAndLoad(final long fromChannelID,
@@ -1108,55 +1156,55 @@
             {
                /*
                 * If channel is paging and has full size f
-                * 
+                *
                 * then we don't need to load any refs but we need to:
-                * 
+                *
                 * make sure the page ord is correct across the old paged and new
                 * refs
-                * 
+                *
                 * we know the max page ord (from the channel) for the old refs
                 * so we just need to:
-                * 
+                *
                 * 1) Iterate through the failed channel and update page_ord =
                 * max + 1, max + 2 etc
-                * 
+                *
                 * 2) update channel id
-                * 
-                * 
+                *
+                *
                 * If channel is not paging and the total refs before and after
                 * <=f
-                * 
+                *
                 * 1) Load all refs from failed channel
-                * 
+                *
                 * 2) Update channel id
-                * 
+                *
                 * return those refs
-                * 
-                * 
+                *
+                *
                 * If channel is not paging but total new refs > f
-                * 
+                *
                 * 1) Iterate through failed channel refs and take the first x to
                 * make the channel full
-                * 
+                *
                 * 2) Update the others with page_ord starting at zero
-                * 
+                *
                 * 3) Update channel id
-                * 
+                *
                 * In general:
-                * 
+                *
                 * We have number to load n, max page size p
-                * 
+                *
                 * 1) Iterate through failed channel refs in page_ord order
-                * 
+                *
                 * 2) Put the first n in a List.
-                * 
+                *
                 * 3) Initialise page_ord_count to be p or 0 depending on whether
                 * it was specified
-                * 
+                *
                 * 4) Update the page_ord of the remaining refs accordiningly
-                * 
+                *
                 * 5) Update the channel id
-                * 
+                *
                 */
 
                // First load the refs from the failed channel
@@ -1271,11 +1319,6 @@
       return (InitialLoadInfo) new MergeAndLoadRunner().executeWithRetry();
    }
 
-   public void testSpeed() throws Exception
-   {
-
-   }
-
    // End of paging functionality
    // ===========================
 
@@ -1283,7 +1326,7 @@
          final Transaction tx) throws Exception
    {
       if (trace) { log.trace("Adding reference " + ref + " in channel " + channelID + " tx " + tx); }
-      
+
       class AddReferenceRunner extends JDBCTxRunner2
       {
          public Object doTransaction() throws Exception
@@ -1328,6 +1371,11 @@
                   // which case retry will be attempted and we want to insert it
                   // again
                   m.setPersisted(true);
+
+                  if (m instanceof JBossMessage)
+                  {
+                     cacheID(conn, ((JBossMessage)m).getJMSMessageID());
+                  }
                }
 
                return null;
@@ -1353,26 +1401,26 @@
          new AddReferenceRunner().executeWithRetry();
       }
    }
-   
+
    public void moveReference(final long sourceChannelID, final long destChannelID, final MessageReference ref)
       throws Exception
    {
       if (trace) { log.trace("Moving reference " + ref + " from " + sourceChannelID + " to " + destChannelID); }
-      
+
       class MoveReferenceRunner extends JDBCTxRunner2
       {
          public Object doTransaction() throws Exception
          {
             PreparedStatement psReference = null;
-            
+
             try
             {
                psReference = conn.prepareStatement(getSQLStatement("MOVE_REFERENCE"));
-               
+
                psReference.setLong(1, destChannelID);
                psReference.setLong(2, ref.getMessage().getMessageID());
                psReference.setLong(3, sourceChannelID);
-               
+
                int rows = psReference.executeUpdate();
 
                if (trace)
@@ -1389,7 +1437,7 @@
          }
       }
 
-      new MoveReferenceRunner().executeWithRetry();      
+      new MoveReferenceRunner().executeWithRetry();
    }
 
    public void updateDeliveryCount(final long channelID,
@@ -1409,7 +1457,7 @@
                psReference.setInt(1, ref.getDeliveryCount());
 
                psReference.setLong(2, ref.getMessage().getMessageID());
-               
+
                psReference.setLong(3, channelID);
 
                int rows = psReference.executeUpdate();
@@ -1435,7 +1483,7 @@
          final MessageReference ref, final Transaction tx) throws Exception
    {
       if (trace) { log.trace("Removing reference " + ref + " in channel " + channelID + " tx " + tx); }
-      
+
       class RemoveReferenceRunner extends JDBCTxRunner2
       {
          public Object doTransaction() throws Exception
@@ -1490,30 +1538,146 @@
       }
    }
 
-   public boolean referenceExists(long messageID) throws Exception
+
+
+   public boolean idExists(String messageID) throws Exception
    {
+      //Does not need to be fast since only called after failover - a scan is sufficient
+
+      for (String id: failedOverIdCache.values())
+      {
+         if (messageID.equals(id))
+         {
+            return true;
+         }
+      }
+
+      return false;
+   }
+
+
+
+   // Public --------------------------------------------------------
+
+   public String toString()
+   {
+      return "JDBCPersistenceManager[" + Integer.toHexString(hashCode()) + "]";
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   protected void cacheID(Connection conn, String id) throws Exception
+   {
+      if (!detectDuplicates)
+      {
+         return;
+      }
+
+      int pos;
+
+      lock.acquire();
+
+      try
+      {
+         pos = idCacheCounter;
+
+         idCacheCounter++;
+
+         if (idCacheCounter == idCacheSize)
+         {
+            idCacheCounter = 0;
+         }
+      }
+      finally
+      {
+         lock.release();
+      }
+
+      boolean exists = idCache.containsKey(pos);
+
+      PreparedStatement ps = null;
+
+      try
+      {
+         if (exists)
+         {
+            ps = conn.prepareStatement(getSQLStatement("UPDATE_ID_IN_CACHE"));
+
+            ps.setString(1, id);
+
+            ps.setInt(2, nodeID);
+
+            ps.setInt(3, pos);
+         }
+         else
+         {
+            ps = conn.prepareStatement(getSQLStatement("INSERT_ID_IN_CACHE"));
+
+            ps.setInt(1, nodeID);
+
+            ps.setInt(2, pos);
+
+            ps.setString(3, id);
+         }
+
+         int rows = ps.executeUpdate();
+
+         if (rows != 1)
+         {
+            log.warn("Failed to cache id value");
+         }
+      }
+      finally
+      {
+         closeStatement(ps);
+      }
+
+      idCache.put(pos, id);
+   }
+
+   protected void loadIDCache(Map<Integer, String> cache, int theNodeID) throws Exception
+   {
       Connection conn = null;
       PreparedStatement st = null;
       ResultSet rs = null;
       TransactionWrapper wrap = new TransactionWrapper();
 
+      cache.clear();
+
       try
       {
          conn = ds.getConnection();
 
-         st = conn
-               .prepareStatement(getSQLStatement("SELECT_EXISTS_REF_MESSAGE_ID"));
-         st.setLong(1, messageID);
+         st = conn.prepareStatement(getSQLStatement("LOAD_ID_CACHE"));
 
+         st.setInt(1, theNodeID);
+
          rs = st.executeQuery();
 
-         if (rs.next())
+         int maxCounter = -1;
+
+         int c = 0;
+
+         while (rs.next() && c < idCacheSize)
          {
-            return true;
+            int counter = rs.getInt(1);
+
+            String id = rs.getString(2);
+
+            cache.put(counter, id);
+
+            maxCounter = Math.max(maxCounter, counter);
+
+            c++;
          }
-         else
+
+         idCacheCounter = maxCounter + 1;
+
+         if (idCacheCounter >= idCacheSize)
          {
-            return false;
+            idCacheCounter = 0;
          }
       }
       catch (Exception e)
@@ -1530,17 +1694,6 @@
       }
    }
 
-   // Public --------------------------------------------------------
-
-   public String toString()
-   {
-      return "JDBCPersistenceManager[" + Integer.toHexString(hashCode()) + "]";
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
    protected TransactionCallback getCallback(Transaction tx)
    {
       TransactionCallback callback = (TransactionCallback) tx.getCallback(this);
@@ -1579,6 +1732,8 @@
             {
                // First the adds
 
+               boolean first = true;
+
                for (Iterator i = refsToAdd.iterator(); i.hasNext();)
                {
                   ChannelRefPair pair = (ChannelRefPair) i.next();
@@ -1632,6 +1787,14 @@
                         m.setPersisted(true);
 
                         messagesStored.add(m);
+
+                        //We only cache the first id in a tx - this is enough to determine if the tx succeeded
+                        if (first && m instanceof JBossMessage)
+                        {
+                           cacheID(conn, ((JBossMessage)m).getJMSMessageID());
+
+                           first = false;
+                        }
                      }
                   }
                }
@@ -1773,6 +1936,8 @@
                   addTXRecord(conn, tx);
                }
 
+               boolean first = false;
+
                Iterator iter = refsToAdd.iterator();
 
                while (iter.hasNext())
@@ -1818,6 +1983,14 @@
                         m.setPersisted(true);
 
                         messagesStored.add(m);
+
+                        //We only cache the first id in a tx - this is enough to determine if the tx succeeded
+                        if (first && m instanceof JBossMessage)
+                        {
+                           cacheID(conn, ((JBossMessage)m).getJMSMessageID());
+
+                           first = false;
+                        }
                      }
                   }
                }
@@ -1898,7 +2071,7 @@
                }
 
                ps.close();
- 
+
                ps = conn
                      .prepareStatement(getSQLStatement("ROLLBACK_MESSAGE_REF2"));
                ps.setLong(1, tx.getId());
@@ -2030,7 +2203,7 @@
       ps.setLong(2, ref.getMessage().getMessageID());
       ps.setNull(3, Types.BIGINT);
       ps.setString(4, "C");
-      ps.setLong(5, getOrdering());
+      ps.setLong(5, orderingID.getID());
       if (paged)
       {
          ps.setLong(6, ref.getPagingOrder());
@@ -2072,7 +2245,7 @@
       ps.setLong(2, ref.getMessage().getMessageID());
       ps.setLong(3, tx.getId());
       ps.setString(4, "+");
-      ps.setLong(5, getOrdering());
+      ps.setLong(5, orderingID.getID());
       ps.setNull(6, Types.BIGINT);
       ps.setInt(7, ref.getDeliveryCount());
       ps.setLong(8, ref.getScheduledDeliveryTime());
@@ -2141,7 +2314,7 @@
       ps.setLong(3, m.getExpiration());
       ps.setLong(4, m.getTimestamp());
       ps.setByte(5, m.getPriority());
-      ps.setByte(6, m.getType());     
+      ps.setByte(6, m.getType());
 
       if (bindBlobs)
       {
@@ -2370,7 +2543,7 @@
       map.put("CREATE_IDX_MESSAGE_REF_MESSAGE_ID",
               "CREATE INDEX JBM_MSG_REF_MESSAGE_ID ON JBM_MSG_REF (MESSAGE_ID)");
       map.put("CREATE_IDX_MESSAGE_REF_SCHED_DELIVERY",
-              "CREATE INDEX JBM_MSG_REF_SCHED_DELIVERY ON JBM_MSG_REF (SCHED_DELIVERY)");    
+              "CREATE INDEX JBM_MSG_REF_SCHED_DELIVERY ON JBM_MSG_REF (SCHED_DELIVERY)");
       // Message
       map.put("CREATE_MESSAGE",
               "CREATE TABLE JBM_MSG (MESSAGE_ID BIGINT, RELIABLE CHAR(1), "
@@ -2385,6 +2558,8 @@
       // Counter
       map.put("CREATE_COUNTER",
               "CREATE TABLE JBM_COUNTER (NAME VARCHAR(255), NEXT_ID BIGINT, PRIMARY KEY(NAME))");
+      // Id cache
+      map.put("CREATE_ID_CACHE", "CREATE TABLE JBM_ID_CACHE (NODE_ID INTEGER, CNTR INTEGER, JBM_ID VARCHAR(255), PRIMARY KEY(NODEID, CNTR))");
       return map;
    }
 
@@ -2425,15 +2600,17 @@
               "UPDATE JBM_MSG_REF SET PAGE_ORD = NULL WHERE PAGE_ORD BETWEEN ? AND ? AND CHANNEL_ID=?");
       map.put("SELECT_MIN_MAX_PAGE_ORD",
               "SELECT MIN(PAGE_ORD), MAX(PAGE_ORD) FROM JBM_MSG_REF WHERE CHANNEL_ID = ?");
-      map.put("SELECT_EXISTS_REF_MESSAGE_ID",
-              "SELECT MESSAGE_ID FROM JBM_MSG_REF WHERE MESSAGE_ID = ?");
       map.put("UPDATE_DELIVERY_COUNT",
               "UPDATE JBM_MSG_REF SET DELIVERY_COUNT = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?");
       map.put("UPDATE_CHANNEL_ID",
               "UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE CHANNEL_ID = ?");
       map.put("MOVE_REFERENCE",
               "UPDATE JBM_MSG_REF SET CHANNEL_ID = ? WHERE MESSAGE_ID = ? AND CHANNEL_ID = ?");
+      map.put("LOAD_ID_CACHE", "SELECT CNTR, ID FROM JBM_ID_CACHE WHERE NODE_ID = ?");
+      map.put("UPDATE_ID_IN_CACHE", "UPDATE JBM_ID_CACHE SET JBM_ID = ? WHERE NODE_ID = ? CNTR = ?");
+      map.put("INSERT_ID_IN_CACHE", "INSERT INTO JBM_ID_CACHE (NODE_ID, CNTR, JBM_ID) VALUES (?, ?, ?)");
 
+
       // Message
       map.put("LOAD_MESSAGES",
               "SELECT MESSAGE_ID, RELIABLE, EXPIRATION, TIMESTAMP, "
@@ -2688,50 +2865,31 @@
       }
    }
 
-   private synchronized long getOrdering()
-   {
-      // We generate the ordering for the message reference by taking the lowest
-      // 48 bits of the current time and
-      // concatenating with a 15 bit rotating counter to form a string of 63
-      // bits which we then place
-      // in the right most bits of a long, giving a positive signed 63 bit
-      // integer.
+   // Inner classes -------------------------------------------------
 
-      // Having a time element in the ordering means we don't have to maintain a
-      // counter in the database
-      // It also helps with failover since if two queues merge after failover
-      // then, the ordering will mean
-      // their orderings interleave nicely and they still get consumed in pretty
-      // much time order
 
-      // We only have to guarantee ordering per session, so having slight
-      // differences of time on different nodes is
-      // not a problem
+   // We generate the ordering for the message reference by taking the lowest
+   // 48 bits of the current time and
+   // concatenating with a 15 bit rotating counter to form a string of 63
+   // bits which we then place
+   // in the right most bits of a long, giving a positive signed 63 bit
+   // integer.
 
-      // The time element is good for about 8919 years - if you're still running
-      // JBoss Messaging then, I suggest you need an
-      // upgrade!
+   // Having a time element in the ordering means we don't have to maintain a
+   // counter in the database
+   // It also helps with failover since if two queues merge after failover
+   // then, the ordering will mean
+   // their orderings interleave nicely and they still get consumed in pretty
+   // much time order
 
-      long order = System.currentTimeMillis();
+   // We only have to guarantee ordering per session, so having slight
+   // differences of time on different nodes is
+   // not a problem
 
-      order = order << 15;
+   // The time element is good for about 8919 years - if you're still running
+   // JBoss Messaging then, I suggest you need an
+   // upgrade!
 
-      order = order | orderCount;
-
-      if (orderCount == Short.MAX_VALUE)
-      {
-         orderCount = 0;
-      }
-      else
-      {
-         orderCount++;
-      }
-
-      return order;
-   }
-
-   // Inner classes -------------------------------------------------
-
    private static class ChannelRefPair
    {
       private long channelID;

Copied: branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/RotatingID.java (from rev 3746, branches/Branch_Stable_temp/src/main/org/jboss/messaging/core/impl/RotatingID.java)
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/RotatingID.java	                        (rev 0)
+++ branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/RotatingID.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -0,0 +1,92 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.messaging.core.impl;
+
+/**
+ *
+ * A RotatingID
+ *
+ * 64 bits, made up of:
+ *
+ * First 8 bits - node id
+ * Next 42 bits - lowest 41 bits of system time
+ * Next 14 bits - rotating counter
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class RotatingID
+{
+   private short count;
+
+   private long lastTime = System.currentTimeMillis();
+
+   private final long nodeID;
+
+   public RotatingID(final int nodeID)
+   {
+      if (nodeID < 0 || nodeID > 255)
+      {
+         throw new IllegalArgumentException("node id must be between 0 to 255 inclusive");
+      }
+
+      this.nodeID = nodeID;
+   }
+
+   public synchronized long getID()
+   {
+      long id1 = nodeID << 54;
+
+      long id2 = System.currentTimeMillis() << 14;
+
+      long id = id1 | id2 | count;
+
+      if (count == Short.MAX_VALUE)
+      {
+         count = 0;
+
+         long now = System.currentTimeMillis();
+
+         //Safety - not likely to happen
+
+         while (now == lastTime)
+         {
+            try
+            {
+               Thread.sleep(1);
+            }
+            catch (InterruptedException e)
+            {}
+
+            now = System.currentTimeMillis();
+         }
+
+         lastTime = now;
+      }
+      else
+      {
+         count++;
+      }
+
+      return id;
+   }
+}
\ No newline at end of file

Modified: branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/tx/TransactionRepository.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/tx/TransactionRepository.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/messaging/core/impl/tx/TransactionRepository.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -38,14 +38,14 @@
 import org.jboss.messaging.core.contract.PersistenceManager;
 import org.jboss.messaging.core.contract.PostOffice;
 import org.jboss.messaging.core.contract.Queue;
-import org.jboss.messaging.core.impl.IDManager;
+import org.jboss.messaging.core.impl.RotatingID;
 import org.jboss.messaging.core.impl.SimpleDelivery;
 
 import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap;
 
 /**
  * This class maintains JMS Server local transactions.
- * 
+ *
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @author <a href="mailto:Konda.Madhu at uk.mizuho-sc.com">Madhu Konda</a>
  * @author <a href="mailto:juha at jboss.org">Juha Lindfors</a>
@@ -61,60 +61,60 @@
    private static final Logger log = Logger.getLogger(TransactionRepository.class);
 
    // Attributes ----------------------------------------------------
-   
+
    private boolean trace = log.isTraceEnabled();
-   
-   private Map map;     
-   
+
+   private Map map;
+
    private PersistenceManager persistenceManager;
 
    protected MessageStore messageStore;
 
-   private IDManager idManager;
-   
    private PostOffice postOffice;
-   
+
+   private RotatingID txID;
+
    // Static --------------------------------------------------------
-   
+
    // Constructors --------------------------------------------------
-   
-   public TransactionRepository(PersistenceManager persistenceManager, MessageStore store, IDManager idManager)
+
+   public TransactionRepository(PersistenceManager persistenceManager, MessageStore store, int nodeID)
    {
       this.persistenceManager = persistenceManager;
-      
+
       this.messageStore = store;
-      
-      this.idManager = idManager;
-      
-      map = new ConcurrentHashMap();        
+
+      map = new ConcurrentHashMap();
+
+      txID = new RotatingID(nodeID);
    }
-   
+
    // Injection ----------------------------------------
-   
+
    //Unfortunately we have to do this for now, since PostOffice is not started until after this is constructed
    //We will sort out dependencies properly when we go to the micro container
    public void injectPostOffice(PostOffice po)
    {
       postOffice = po;
    }
-   
 
+
    // MessagingComponent implementation --------------------------------
-   
+
    public void start() throws Exception
    {
       //NOOP
    }
-   
+
    // Public --------------------------------------------------------
-      
+
    public void stop() throws Exception
    {
       //NOOP
    }
-   
-   // Public --------------------------------------------------------   
 
+   // Public --------------------------------------------------------
+
    /**
     * Attempts to recover existing prepared transactions by redelivering unhandled messages and acknowledgements
     * on the appropriate channels.
@@ -124,15 +124,15 @@
    public synchronized List recoverPreparedTransactions()
    {
       if (trace) { log.trace(this + " recoverPreparedTransactions()"); }
-      
+
       ArrayList prepared = new ArrayList();
 
       Iterator iter = map.values().iterator();
-      
+
       while (iter.hasNext())
       {
          Transaction tx = (Transaction) iter.next();
-         
+
          if (tx.getXid() != null && tx.getState() == Transaction.STATE_PREPARED)
          {
             try
@@ -157,7 +157,7 @@
             prepared.add(tx.getXid());
          }
       }
-      
+
       if (trace) { log.trace("Returning " + prepared.size() + " transactions"); }
 
       return prepared;
@@ -187,33 +187,33 @@
 
             //This method may be called more than once - e.g. when failover occurs so we don't want to add the
             //prepared tx if it is already in memory
-            
+
             if (!map.containsKey(txInfo.getXid()))
             {
                Transaction tx = createTransaction(txInfo);
-               
+
                tx.setState(Transaction.STATE_PREPARED);
-               
+
                tx.setRecoveredFromStorage(true);
-               
+
                if (trace) log.trace("reinstating TX(XID: " + txInfo.getXid() + ", LocalId " + txInfo.getTxId() +")");
-               
-            }  
+
+            }
             else
             {
                if (trace) log.trace("Not adding to map since it's already in map");
             }
          }
-      }     
+      }
    }
-   
+
    public List getPreparedTransactions()
    {
       return new ArrayList(map.keySet());
    }
 
    public Transaction getPreparedTx(Xid xid) throws Exception
-   {            
+   {
       Transaction tx = (Transaction)map.get(xid);
 
       if (tx == null)
@@ -226,12 +226,12 @@
       }
       return tx;
    }
-   
+
    public void deleteTransaction(Transaction transaction) throws Exception
    {
 	   final Xid id = transaction.getXid();
 	   final int state = transaction.getState();
-	   
+
 	   if (id == null)
 	   {
 		   throw new IllegalArgumentException("DeleteTransaction was called for non XA transaction");
@@ -241,29 +241,29 @@
 	   {
 		   throw new TransactionException("Transaction with xid " + id + " can't be removed as it's not yet commited or rolledback: (Current state is " + Transaction.stateToString(state));
 	   }
-      
-	   map.remove(id);	   
+
+	   map.remove(id);
    }
-   
+
    public Transaction createTransaction(Xid xid) throws Exception
    {
       if (map.containsKey(xid))
       {
          throw new TransactionException("There is already an entry for xid " + xid);
       }
-      Transaction tx = new Transaction(idManager.getID(), xid, this);
-      
+      Transaction tx = new Transaction(txID.getID(), xid, this);
+
       if (trace) { log.trace("created transaction " + tx); }
-      
+
       map.put(xid, tx);
-      
+
       return tx;
    }
-   
+
    public Transaction createTransaction() throws Exception
    {
-      Transaction tx = new Transaction(idManager.getID());
-      
+      Transaction tx = new Transaction(txID.getID());
+
       if (trace) { log.trace("created transaction " + tx); }
 
       return tx;
@@ -273,17 +273,17 @@
    {
       return map.remove(xid) != null;
    }
-   
+
    /** To be used only by testcases */
    public int getNumberOfRegisteredTransactions()
    {
-	  return this.map.size();   
+	  return this.map.size();
    }
-   
-   
-   
+
+
+
    // Package protected ---------------------------------------------
-   
+
    /**
     * Load the references and invoke the channel to handle those refs
     */
@@ -300,29 +300,29 @@
       for (Iterator iter = pairs.iterator(); iter.hasNext();)
       {
          PersistenceManager.MessageChannelPair pair = (PersistenceManager.MessageChannelPair)iter.next();
-         
+
          Message msg = pair.getMessage();
-         
+
          long channelID = pair.getChannelId();
-         
-         MessageReference ref = messageStore.reference(msg);  
-         
+
+         MessageReference ref = messageStore.reference(msg);
+
          ref.getMessage().setPersisted(true);
 
          Binding binding = postOffice.getBindingForChannelID(channelID);
-         
+
          if (binding == null)
          {
             throw new IllegalStateException("Cannot find binding for channel id " + channelID);
          }
-         
+
          Queue queue = binding.queue;
-                     
+
          if (trace) log.trace("Destination for message[ID=" + ref.getMessage().getMessageID() + "] is: " + queue);
 
-         // The actual jmx queue may not have been deployed yet, so we need to activate the core queue if so, 
+         // The actual jmx queue may not have been deployed yet, so we need to activate the core queue if so,
          // or the handle will have no effect
-                     
+
          boolean deactivate = false;
 
          if (!queue.isActive())
@@ -347,38 +347,38 @@
    void handleAcks(Transaction tx) throws Exception
    {
       long txId = tx.getId();
-      
+
       List pairs = persistenceManager.getMessageChannelPairAcksForTx(txId);
 
       if (trace) log.trace("Found " + pairs.size() + " unhandled acks.");
-      
+
       List dels = new ArrayList();
 
       for (Iterator iter = pairs.iterator(); iter.hasNext();)
       {
          PersistenceManager.MessageChannelPair pair = (PersistenceManager.MessageChannelPair)iter.next();
-         
+
          Message msg = pair.getMessage();
-         
+
          long channelID = pair.getChannelId();
-         
+
          MessageReference ref = null;
-         
-         ref = messageStore.reference(msg);    
-         
+
+         ref = messageStore.reference(msg);
+
          ref.getMessage().setPersisted(true);
 
          Binding binding = postOffice.getBindingForChannelID(channelID);
-         
+
          if (binding == null)
          {
             throw new IllegalStateException("Cannot find binding for channel id " + channelID);
-         }                       
+         }
 
          Queue queue = binding.queue;
-         
-         if (trace) log.trace("Destination for message[ID=" + ref.getMessage().getMessageID() + "] is: " + queue);            
-         
+
+         if (trace) log.trace("Destination for message[ID=" + ref.getMessage().getMessageID() + "] is: " + queue);
+
          //Create a new delivery - note that it must have a delivery observer otherwise acknowledge will fail
          Delivery del = new SimpleDelivery(queue, ref, true, true);
 
@@ -386,9 +386,9 @@
 
          try
          {
-         	// The actual jmx queue may not have been deployed yet, so we need to the core queue if so, 
+         	// The actual jmx queue may not have been deployed yet, so we need to the core queue if so,
             // or the acknowledge will have no effect
-                        
+
             boolean deactivate = false;
 
             if (!queue.isActive())
@@ -409,23 +409,23 @@
          {
             log.error("Failed to acknowledge " + del + " during recovery", t);
          }
-         
-         dels.add(del);            
+
+         dels.add(del);
       }
-      
+
       if (!dels.isEmpty())
       {
          //Add a callback so these dels get cancelled on rollback
          tx.addCallback(new CancelCallback(dels), this);
-      }      
+      }
    }
-   
-   // Protected -----------------------------------------------------         
-   
+
+   // Protected -----------------------------------------------------
+
    // Private -------------------------------------------------------
 
-	         
-      
+
+
 	/**
 	 * Creates a prepared transaction
 	 *
@@ -454,11 +454,11 @@
 	}
 
    // Inner classes -------------------------------------------------
-   
+
    private class CancelCallback implements TxCallback
    {
       private List toCancel;
-      
+
       private CancelCallback(List toCancel)
       {
          this.toCancel = toCancel;
@@ -477,13 +477,13 @@
          //On rollback we need to cancel the ref back into the channel
          //We only need to do this if the tx was reloaded since otherwise the
          //cancel will come from the SCE
-         
+
          //Need to cancel in reverse
-         
+
          for (int i = toCancel.size() - 1; i >= 0; i--)
-         {                     
+         {
             Delivery del = (Delivery)toCancel.get(i);
-            
+
             try
             {
                del.cancel();
@@ -507,7 +507,7 @@
       public void beforeRollback(boolean onePhase) throws Exception
       {
       }
-      
+
    }
-   
+
 }
\ No newline at end of file

Modified: branches/Branch_Stable/src/main/org/jboss/messaging/core/jmx/JDBCPersistenceManagerService.java
===================================================================
--- branches/Branch_Stable/src/main/org/jboss/messaging/core/jmx/JDBCPersistenceManagerService.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/src/main/org/jboss/messaging/core/jmx/JDBCPersistenceManagerService.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -30,7 +30,7 @@
 
 /**
  * A JDBCPersistenceManagerService
- * 
+ *
  * MBean wrapper around a JDBCPersistenceManager
  *
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
@@ -42,136 +42,160 @@
 public class JDBCPersistenceManagerService extends JDBCServiceSupport
 {
    private PersistenceManager persistenceManager;
-   
+
    private boolean started;
-   
+
    private boolean usingBatchUpdates;
-   
+
    private boolean usingBinaryStream = true;
-   
+
    private boolean usingTrailingByte;
-   
+
    private int maxParams = 100;
-   
+
    private boolean supportsBlobOnSelect = true;
-   
+
+   private boolean detectDuplicates = false;
+
+   private int idCacheSize = 500;
+
    // Constructors --------------------------------------------------------
-   
+
    public JDBCPersistenceManagerService()
-   {      
+   {
    }
-   
+
    // ServerPlugin implementation ------------------------------------------
-   
+
    public MessagingComponent getInstance()
    {
       return persistenceManager;
    }
-   
+
    // ServiceMBeanSupport overrides -----------------------------------------
-   
+
    protected synchronized void startService() throws Exception
    {
       if (started)
       {
          throw new IllegalStateException("Service is already started");
       }
-      
+
       super.startService();
-      
+
       try
-      {  
+      {
          TransactionManager tm = getTransactionManagerReference();
-         
+
          persistenceManager =
             new JDBCPersistenceManager(ds, tm, sqlProperties,
                                        createTablesOnStartup, usingBatchUpdates,
                                        usingBinaryStream, usingTrailingByte, maxParams,
-                                       supportsBlobOnSelect);
-         
+                                       supportsBlobOnSelect, detectDuplicates, idCacheSize);
+
          persistenceManager.start();
-         
+
          started = true;
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMXInvocation(t, this + " startService");
-      } 
+      }
    }
-   
+
    protected void stopService() throws Exception
    {
       if (!started)
       {
          throw new IllegalStateException("Service is not started");
       }
-      
+
       try
       {
          persistenceManager.stop();
-         
+
          persistenceManager = null;
-         
+
          started = false;
       }
       catch (Throwable t)
       {
          throw ExceptionUtil.handleJMXInvocation(t, this + " startService");
-      } 
-      
+      }
+
       log.debug(this + " stopped");
    }
-   
+
    // MBean attributes -------------------------------------------------------
-   
+
    public boolean isUsingBatchUpdates()
    {
       return usingBatchUpdates;
    }
-   
+
    public void setUsingBatchUpdates(boolean b)
    {
       usingBatchUpdates = b;
    }
-   
+
    public int getMaxParams()
    {
       return maxParams;
    }
-   
+
    public void setMaxParams(int maxParams)
    {
       this.maxParams = maxParams;
    }
-   
+
    public boolean isUsingBinaryStream()
    {
       return usingBinaryStream;
    }
-   
+
    public void setUsingBinaryStream(boolean b)
    {
       usingBinaryStream = b;
    }
-   
+
    public boolean isUsingTrailingByte()
    {
       return usingTrailingByte;
    }
-   
+
    public void setUsingTrailingByte(boolean b)
    {
       usingTrailingByte = b;
    }
-   
+
    public boolean isSupportsBlobOnSelect()
    {
    	return supportsBlobOnSelect;
    }
-   
+
    public void setSupportsBlobOnSelect(boolean b)
    {
    	this.supportsBlobOnSelect = b;
    }
-      
+
+   public boolean isDetectDuplicates()
+   {
+      return detectDuplicates;
+   }
+
+   public void setDetectDuplicates(boolean detectDuplicates)
+   {
+      this.detectDuplicates = detectDuplicates;
+   }
+
+   public int getIDCacheSize()
+   {
+      return idCacheSize;
+   }
+
+   public void setIDCacheSize(int idCacheSize)
+   {
+      this.idCacheSize = idCacheSize;
+   }
+
 }

Modified: branches/Branch_Stable/tests/build.xml
===================================================================
--- branches/Branch_Stable/tests/build.xml	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/build.xml	2008-02-20 21:44:11 UTC (rev 3748)
@@ -774,7 +774,8 @@
             <formatter classname="org.jboss.test.messaging.tools.ant.JUnitTestSuiteListener"/>
 
             <fileset dir="${build.tests.classes}">
-              <include name="**/jms/clustering/${test-mask}.class"/>
+              <include name="**/jms/clustering/${test-mask}.class"/>	      
+	      <exclude name="**/jms/clustering/MultiThreadFailoverTest.class"/>
               <exclude name="**/jms/clustering/ClusterLeakTest.class"/>
            </fileset>
          </batchtest>

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/MessagingTestCase.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/MessagingTestCase.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/MessagingTestCase.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -21,11 +21,11 @@
 */
 package org.jboss.test.messaging;
 
+import java.lang.ref.WeakReference;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.util.ArrayList;
 import java.util.List;
-import java.lang.ref.WeakReference;
 
 import javax.jms.Connection;
 import javax.jms.ConnectionFactory;
@@ -43,7 +43,6 @@
 import javax.transaction.TransactionManager;
 
 import org.jboss.jms.client.JBossConnection;
-import org.jboss.jms.message.MessageIdGeneratorFactory;
 import org.jboss.logging.Logger;
 import org.jboss.test.messaging.tools.ServerManagement;
 import org.jboss.test.messaging.util.ProxyAssertSupport;
@@ -60,17 +59,17 @@
  * @version <tt>$Revision$</tt>
  * $Id$
  */
-public class MessagingTestCase extends ProxyAssertSupport 
+public class MessagingTestCase extends ProxyAssertSupport
 {
    // Constants -----------------------------------------------------
 
    public final static int MAX_TIMEOUT = 1000 * 10 /* seconds */;
 
    public final static int MIN_TIMEOUT = 1000 * 1 /* seconds */;
-   
 
+
    // Static --------------------------------------------------------
-   
+
    // Attributes ----------------------------------------------------
 
    protected Logger log = Logger.getLogger(getClass());
@@ -85,7 +84,7 @@
    // Public --------------------------------------------------------
 
    // Package protected ---------------------------------------------
-   
+
    // Protected -----------------------------------------------------
 
    protected void setUp() throws Exception
@@ -101,53 +100,57 @@
          // log the test start in the remote log, this will make hunting through logs so much easier
          ServerManagement.log(ServerManagement.INFO, banner);
       }
-      
-      MessageIdGeneratorFactory.instance.clear();
    }
 
    protected void tearDown() throws Exception
    {
-      String banner =
-         "####################################################### Stop " + 
-         (isRemote() ? "REMOTE" : "IN-VM") + " test: " + getName();
+      try
+      {
+         String banner =
+            "####################################################### Stop " +
+            (isRemote() ? "REMOTE" : "IN-VM") + " test: " + getName();
 
-      log.info(banner);
-      
-      if (isRemote())
+         log.info(banner);
+
+         if (isRemote())
+         {
+            // log the test stop in the remote log, this will make hunting through logs so much easier
+            ServerManagement.log(ServerManagement.INFO, banner);
+         }
+      }
+      catch (Throwable ignore)
       {
-         // log the test stop in the remote log, this will make hunting through logs so much easier
-         ServerManagement.log(ServerManagement.INFO, banner);
       }
    }
-      
+
    protected void removeAllMessages(String destName, boolean isQueue, int server) throws Exception
    {
    	String on = "jboss.messaging.destination:service=" + (isQueue ? "Queue" : "Topic") + ",name=" + destName;
-   	
+
    	ServerManagement.getServer(server).invoke(new ObjectName(on), "removeAllMessages", null, null);
    }
-   
+
    protected void checkEmpty(Queue queue) throws Exception
    {
    	ObjectName destObjectName =  new ObjectName("jboss.messaging.destination:service=Queue,name=" + queue.getQueueName());
-   	
+
       Integer messageCount = (Integer)ServerManagement.getAttribute(destObjectName, "MessageCount");
-       
+
       if (messageCount.intValue() != 0)
       {
       	//Delete before failing - so as not to make all other tests fail
       	removeAllMessages(queue.getQueueName(), true, 0);
-      	
+
       	fail("Message count for queue " + queue.getQueueName() + " on server is " + messageCount);
-      }    
+      }
    }
-   
+
    protected void checkEmpty(Queue queue, int server) throws Exception
    {
    	ObjectName destObjectName =  new ObjectName("jboss.messaging.destination:service=Queue,name=" + queue.getQueueName());
-   	
+
       Integer messageCount = (Integer)ServerManagement.getServer(server).getAttribute(destObjectName, "MessageCount");
-      
+
       if (messageCount.intValue() != 0)
       {
       	//Now delete it - prevents other tests from failing
@@ -159,19 +162,36 @@
       	{
       		log.debug("Failed to remove all messages", e);
       	}
-      	
+
       	fail("Queue " + queue.getQueueName()  + " is not empty");
       }
 
    }
-   
+
+   protected boolean isEmpty(Queue queue, int server) throws Exception
+   {
+      ObjectName destObjectName =  new ObjectName("jboss.messaging.destination:service=Queue,name=" + queue.getQueueName());
+
+      Integer messageCount = (Integer)ServerManagement.getServer(server).getAttribute(destObjectName, "MessageCount");
+
+      if (messageCount.intValue() != 0)
+      {
+         return false;
+      }
+      else
+      {
+         return true;
+      }
+
+   }
+
    protected void checkEmpty(Topic topic) throws Exception
    {
    	ObjectName destObjectName =  new ObjectName("jboss.messaging.destination:service=Topic,name=" + topic.getTopicName());
-   	
-      Integer messageCount = (Integer)ServerManagement.getAttribute(destObjectName, "AllMessageCount"); 
-      
-      assertEquals(0, messageCount.intValue());    
+
+      Integer messageCount = (Integer)ServerManagement.getAttribute(destObjectName, "AllMessageCount");
+
+      assertEquals(0, messageCount.intValue());
    }
 
    protected void checkNoSubscriptions(Topic topic) throws Exception
@@ -185,8 +205,8 @@
    protected void checkNoSubscriptions(Topic topic, int server) throws Exception
    {
       Integer messageCount = getNoSubscriptions(topic, server);
-      
-      assertEquals(0, messageCount.intValue());      
+
+      assertEquals(0, messageCount.intValue());
    }
 
    protected int getNoSubscriptions(Topic topic)
@@ -206,30 +226,30 @@
 
    protected boolean assertRemainingMessages(int expected) throws Exception
    {
-      ObjectName destObjectName = 
+      ObjectName destObjectName =
          new ObjectName("jboss.messaging.destination:service=Queue,name=Queue1");
-      Integer messageCount = (Integer)ServerManagement.getAttribute(destObjectName, "MessageCount"); 
-      
+      Integer messageCount = (Integer)ServerManagement.getAttribute(destObjectName, "MessageCount");
+
       log.trace("There are " + messageCount + " messages");
-      
-      assertEquals(expected, messageCount.intValue());      
+
+      assertEquals(expected, messageCount.intValue());
       return expected == messageCount.intValue();
    }
-   
+
    protected int getNumberOfMessages(Queue queue, int server) throws Exception
    {
    	ObjectName destObjectName =  new ObjectName("jboss.messaging.destination:service=Queue,name=" + queue.getQueueName());
-   	
+
       Integer messageCount = (Integer)ServerManagement.getServer(server).getAttribute(destObjectName, "MessageCount");
-      
+
       return messageCount.intValue();
    }
-   
+
    protected void drainDestination(ConnectionFactory cf, Destination dest) throws Exception
    {
       Connection conn = null;
       try
-      {         
+      {
          conn = cf.createConnection();
          Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
          MessageConsumer cons = sess.createConsumer(dest);
@@ -241,19 +261,19 @@
             m = cons.receive(500);
             if (m == null) break;
             log.trace("Drained message");
-         }         
+         }
       }
       finally
       {
          if (conn!= null) conn.close();
       }
    }
-   
+
    protected void drainSub(ConnectionFactory cf, Topic topic, String subName, String clientID) throws Exception
    {
       Connection conn = null;
       try
-      {         
+      {
          conn = cf.createConnection();
          conn.setClientID(clientID);
          Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -266,28 +286,28 @@
             m = cons.receive(500);
             if (m == null) break;
             log.trace("Drained message");
-         }         
+         }
       }
       finally
       {
          if (conn!= null) conn.close();
       }
    }
-   
+
    protected boolean checkNoBindingData() throws Exception
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
-      
+
       java.sql.Connection conn = null;
-      
+
       PreparedStatement ps = null;
-      
+
       ResultSet rs = null;
 
       try
@@ -295,50 +315,50 @@
          conn = ds.getConnection();
          String sql = "SELECT * FROM JBM_POSTOFFICE";
          ps = conn.prepareStatement(sql);
-         
+
          rs = ps.executeQuery();
-         
+
          return rs.next();
       }
       finally
       {
          if (rs != null) rs.close();
-         
+
          if (ps != null) ps.close();
-         
+
          if (conn != null) conn.close();
-         
+
          mgr.commit();
 
          if (txOld != null)
          {
             mgr.resume(txOld);
          }
-                  
-      } 
+
+      }
    }
-   
+
    protected boolean checkNoMessageData() throws Exception
    {
       //Can't do this remotely
-      
+
       if (ServerManagement.isRemote())
       {
          return false;
       }
-      
+
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
-      
+
       java.sql.Connection conn = null;
-      
+
       PreparedStatement ps = null;
-      
+
       ResultSet rs = null;
 
       try
@@ -346,72 +366,72 @@
          conn = ds.getConnection();
          String sql = "SELECT * FROM JBM_MSG_REF";
          ps = conn.prepareStatement(sql);
-         
+
          rs = ps.executeQuery();
-         
+
          boolean exists = rs.next();
-         
+
          if (exists)
          {
          	log.info("Message reference data exists");
          }
-         
+
          if (!exists)
          {
             rs.close();
-            
+
             ps.close();
-            
+
             ps = conn.prepareStatement("SELECT * FROM JBM_MSG");
-            
+
             rs = ps.executeQuery();
-           
-            exists = rs.next();      
-            
+
+            exists = rs.next();
+
             if (exists)
             {
             	log.info("Message data exists");
             }
          }
-         
+
          return exists;
       }
       finally
       {
          if (rs != null) rs.close();
-         
+
          if (ps != null) ps.close();
-         
+
          if (conn != null) conn.close();
-         
+
          mgr.commit();
 
          if (txOld != null)
          {
             mgr.resume(txOld);
          }
-                  
-      } 
+
+      }
    }
-   
+
    protected List getReferenceIds() throws Exception
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
 
       java.sql.Connection conn = ds.getConnection();
       String sql = "SELECT MESSAGE_ID, ORD FROM JBM_MSG_REF";
       PreparedStatement ps = conn.prepareStatement(sql);
-   
+
       ResultSet rs = ps.executeQuery();
-      
+
       List msgIds = new ArrayList();
-      
+
       while (rs.next())
       {
          long msgId = rs.getLong(1);
@@ -427,17 +447,17 @@
       {
          mgr.resume(txOld);
       }
-      
+
       return msgIds;
    }
-   
+
    protected List getReferenceIds(long channelId) throws Throwable
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
 
@@ -445,11 +465,11 @@
       String sql = "SELECT MESSAGE_ID FROM JBM_MSG_REF WHERE CHANNEL_ID=? ORDER BY ORD";
       PreparedStatement ps = conn.prepareStatement(sql);
       ps.setLong(1, channelId);
-   
+
       ResultSet rs = ps.executeQuery();
-      
+
       List msgIds = new ArrayList();
-      
+
       while (rs.next())
       {
          long msgId = rs.getLong(1);
@@ -465,28 +485,28 @@
       {
          mgr.resume(txOld);
       }
-      
+
       return msgIds;
    }
-   
+
    protected List getMessageIds() throws Exception
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
 
       java.sql.Connection conn = ds.getConnection();
       String sql = "SELECT MESSAGE_ID FROM JBM_MSG ORDER BY MESSAGE_ID";
       PreparedStatement ps = conn.prepareStatement(sql);
-      
+
       ResultSet rs = ps.executeQuery();
-      
+
       List msgIds = new ArrayList();
-      
+
       while (rs.next())
       {
          long msgId = rs.getLong(1);
@@ -502,17 +522,17 @@
       {
          mgr.resume(txOld);
       }
-      
+
       return msgIds;
    }
-   
-         
 
-   
-   
-   
 
 
+
+
+
+
+
    /**
     * @return true if this test is ran in "remote" mode, i.e. the server side of the test runs in a
     *         different VM than this one (that is running the client side)
@@ -530,7 +550,7 @@
    {
       return ((JBossConnection) conn).getServerID();
    }
-   
+
    protected Connection createConnectionOnServer(ConnectionFactory factory, int serverId)
    throws Exception
    {
@@ -618,6 +638,6 @@
    }
 
    // Private -------------------------------------------------------
-   
-   // Inner classes -------------------------------------------------   
+
+   // Inner classes -------------------------------------------------
 }

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/JDBCPersistenceManagerTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/JDBCPersistenceManagerTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/JDBCPersistenceManagerTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -58,12 +58,12 @@
    // Attributes ----------------------------------------------------
 
    protected ServiceContainer sc;
-   
+
    protected JDBCPersistenceManager pm;
-   
+
    protected MessageStore ms;
-   
-   
+
+
    // Constructors --------------------------------------------------
 
    public JDBCPersistenceManagerTest(String name)
@@ -79,23 +79,23 @@
       }
 
       super.setUp();
-      
+
       ServerManagement.stop();
 
       sc = new ServiceContainer("all");
-      sc.start();                      
+      sc.start();
    }
-   
+
    protected void doSetup(boolean batch, boolean useBinaryStream,
                           boolean trailingByte, int maxParams) throws Throwable
    {
-      pm = createPM(batch, useBinaryStream, trailingByte, maxParams);         
-      ms = new SimpleMessageStore();      
+      pm = createPM(batch, useBinaryStream, trailingByte, maxParams);
+      ms = new SimpleMessageStore();
    }
-   
+
    protected JDBCPersistenceManager createPM(boolean batch, boolean useBinaryStream,
                                              boolean trailingByte, int maxParams) throws Throwable
-   {      
+   {
       JDBCPersistenceManager p =
          new JDBCPersistenceManager(sc.getDataSource(), sc.getTransactionManager(),
                   sc.getPersistenceManagerSQLProperties(),
@@ -109,149 +109,149 @@
    {
       sc.stop();
       sc = null;
-      
+
       pm.stop();
       ms.stop();
       super.tearDown();
    }
-      
+
    public void testAddRemoveGetReferences_Batch() throws Throwable
    {
       addRemoveGetReferences(true);
    }
-   
+
    public void testAddRemoveGetReferences_NoBatch() throws Throwable
    {
       addRemoveGetReferences(false);
    }
-   
+
    public void testAddRemoveReference() throws Throwable
    {
       doSetup(false, false, false, 100);
-      
+
       Channel channel1 = new SimpleChannel(0, ms);
       Channel channel2 = new SimpleChannel(1, ms);
 
-      Message[] messages = createMessages(10);     
-      
+      Message[] messages = createMessages(10);
+
       for (int i = 0; i < 5; i++)
       {
          Message m1 = messages[i * 2];
          Message m2 = messages[i * 2 + 1];
-         
+
          MessageReference ref1_1 = ms.reference(m1);
          MessageReference ref1_2 = ms.reference(m1);
-                
+
          MessageReference ref2_1 = ms.reference(m2);
          MessageReference ref2_2 = ms.reference(m2);
-                  
+
          pm.addReference(channel1.getChannelID(), ref1_1, null);
-         pm.addReference(channel1.getChannelID(), ref2_1, null);         
-         
+         pm.addReference(channel1.getChannelID(), ref2_1, null);
+
          pm.addReference(channel2.getChannelID(), ref1_2, null);
          pm.addReference(channel2.getChannelID(), ref2_2, null);
-      
+
          List refs = getReferenceIds(channel1.getChannelID());
-         
+
          assertNotNull(refs);
          assertEquals(2, refs.size());
          assertTrue(refs.contains(new Long(m1.getMessageID())));
          assertTrue(refs.contains(new Long(m2.getMessageID())));
-         
+
          refs = getReferenceIds(channel2.getChannelID());
-         
+
          assertNotNull(refs);
          assertEquals(2, refs.size());
          assertTrue(refs.contains(new Long(m1.getMessageID())));
          assertTrue(refs.contains(new Long(m2.getMessageID())));
-         
+
          List msgs = getMessageIds();
          assertNotNull(msgs);
          assertEquals(2, msgs.size());
          assertTrue(msgs.contains(new Long(m1.getMessageID())));
          assertTrue(msgs.contains(new Long(m2.getMessageID())));
-                  
+
          pm.removeReference(channel1.getChannelID(), ref1_1, null);
-                  
+
          refs = getReferenceIds(channel1.getChannelID());
          assertNotNull(refs);
          assertEquals(1, refs.size());
          assertTrue(refs.contains(new Long(m2.getMessageID())));
-         
+
          refs = getReferenceIds(channel2.getChannelID());
          assertNotNull(refs);
          assertEquals(2, refs.size());
          assertTrue(refs.contains(new Long(m1.getMessageID())));
          assertTrue(refs.contains(new Long(m2.getMessageID())));
-         
+
          msgs = getMessageIds();
          assertNotNull(msgs);
          assertEquals(2, msgs.size());
          assertTrue(msgs.contains(new Long(m1.getMessageID())));
          assertTrue(msgs.contains(new Long(m2.getMessageID())));
-         
+
          pm.removeReference(channel2.getChannelID(), ref1_2, null);
-         
+
          refs = getReferenceIds(channel1.getChannelID());
          assertNotNull(refs);
          assertEquals(1, refs.size());
          assertTrue(refs.contains(new Long(m2.getMessageID())));
-         
+
          refs = getReferenceIds(channel2.getChannelID());
          assertNotNull(refs);
-         assertEquals(1, refs.size());         
+         assertEquals(1, refs.size());
          assertTrue(refs.contains(new Long(m2.getMessageID())));
-         
+
          msgs = getMessageIds();
          assertNotNull(msgs);
-         assertEquals(1, msgs.size()); 
+         assertEquals(1, msgs.size());
          assertTrue(msgs.contains(new Long(m2.getMessageID())));
-         
+
          pm.removeReference(channel1.getChannelID(), ref2_1, null);
-         
+
          refs = getReferenceIds(channel1.getChannelID());
          assertNotNull(refs);
          assertTrue(refs.isEmpty());
-         
+
          refs = getReferenceIds(channel2.getChannelID());
          assertNotNull(refs);
-         assertEquals(1, refs.size());         
+         assertEquals(1, refs.size());
          assertTrue(refs.contains(new Long(m2.getMessageID())));
-         
+
          msgs = getMessageIds();
          assertNotNull(msgs);
          assertEquals(1, msgs.size());
          assertTrue(msgs.contains(new Long(m2.getMessageID())));
-         
+
          pm.removeReference(channel2.getChannelID(), ref2_2, null);
-         
+
          refs = getReferenceIds(channel1.getChannelID());
          assertNotNull(refs);
          assertTrue(refs.isEmpty());
-         
+
          refs = getReferenceIds(channel2.getChannelID());
          assertNotNull(refs);
          assertTrue(refs.isEmpty());
-         
+
          msgs = getMessageIds();
          assertNotNull(msgs);
          assertTrue(msgs.isEmpty());
-            
+
       }
    }
-   
+
    // Trailing zero
    // -----------------
-   
+
    // Binary Stream
-   
+
    //non batch
-   
+
    public void testCommit_NotXA_Long_NB_BS_TZ() throws Throwable
    {
       doTransactionCommit(false, false, true, true);
    }
-   
+
    public void testCommit_XA_Long_NB_BS_TZ() throws Throwable
    {
       doTransactionCommit(true, false, true, true);
@@ -261,20 +261,20 @@
    {
       doTransactionRollback(false, false, true, true);
    }
-       
+
    public void testRollback_XA_Long_NB_BS_TZ() throws Throwable
    {
       doTransactionRollback(true, false, true, true);
    }
-   
 
+
    //batch
-   
+
    public void testCommit_NotXA_Long_B_BS_TZ() throws Throwable
    {
       doTransactionCommit(false, true, true, true);
    }
-     
+
    public void testCommit_XA_Long_B_BS_TZ() throws Throwable
    {
       doTransactionCommit(true, true, true, true);
@@ -284,21 +284,21 @@
    {
       doTransactionRollback(false, true, true, true);
    }
-        
+
    public void testRollback_XA_Long_B_BS_TZ() throws Throwable
    {
       doTransactionRollback(true, true, true, true);
    }
-   
+
    // No binary stream
-   
+
    //non batch
-   
+
    public void testCommit_NotXA_Long_NB_BNS_TZ() throws Throwable
    {
       doTransactionCommit(false, false, false, true);
    }
-   
+
    public void testCommit_XA_Long_NB_NBS_TZ() throws Throwable
    {
       doTransactionCommit(true, false, false, true);
@@ -308,20 +308,20 @@
    {
       doTransactionRollback(false, false, false, true);
    }
-       
+
    public void testRollback_XA_Long_NB_NBS_TZ() throws Throwable
    {
       doTransactionRollback(true, false, false, true);
    }
-   
 
+
    //batch
-   
+
    public void testCommit_NotXA_Long_B_NBS_TZ() throws Throwable
    {
       doTransactionCommit(false, true, false, true);
    }
-     
+
    public void testCommit_XA_Long_B_NBS_TZ() throws Throwable
    {
       doTransactionCommit(true, true, false, true);
@@ -331,25 +331,25 @@
    {
       doTransactionRollback(false, true, false, true);
    }
-        
+
    public void testRollback_XA_Long_B_NBS_TZ() throws Throwable
    {
       doTransactionRollback(true, true, false, true);
    }
-   
-       
+
+
    // Non trailing zero
    // -----------------
-   
+
    // Binary Stream
-   
+
    //non batch
-   
+
    public void testCommit_NotXA_Long_NB_BS_NTZ() throws Throwable
    {
       doTransactionCommit(false, false, true, false);
    }
-   
+
    public void testCommit_XA_Long_NB_BS_NTZ() throws Throwable
    {
       doTransactionCommit(true, false, true, false);
@@ -359,20 +359,20 @@
    {
       doTransactionRollback(false, false, true, false);
    }
-       
+
    public void testRollback_XA_Long_NB_BS_NTZ() throws Throwable
    {
       doTransactionRollback(true, false, true, false);
    }
-   
 
+
    //batch
-   
+
    public void testCommit_NotXA_Long_B_BS_NTZ() throws Throwable
    {
       doTransactionCommit(false, true, true, false);
    }
-     
+
    public void testCommit_XA_Long_B_BS_NTZ() throws Throwable
    {
       doTransactionCommit(true, true, true, false);
@@ -382,21 +382,21 @@
    {
       doTransactionRollback(false, true, true, false);
    }
-        
+
    public void testRollback_XA_Long_B_BS_NTZ() throws Throwable
    {
       doTransactionRollback(true, true, true, false);
    }
-   
+
    // No binary stream
-   
+
    //non batch
-   
+
    public void testCommit_NotXA_Long_NB_BNS_NTZ() throws Throwable
    {
       doTransactionCommit(false, false, false, false);
    }
-   
+
    public void testCommit_XA_Long_NB_NBS_NTZ() throws Throwable
    {
       doTransactionCommit(true, false, false, false);
@@ -406,20 +406,20 @@
    {
       doTransactionRollback(false, false, false, false);
    }
-       
+
    public void testRollback_XA_Long_NB_NBS_NTZ() throws Throwable
    {
       doTransactionRollback(true, false, false, false);
    }
-   
 
+
    //batch
-   
+
    public void testCommit_NotXA_Long_B_NBS_NTZ() throws Throwable
    {
       doTransactionCommit(false, true, false, false);
    }
-     
+
    public void testCommit_XA_Long_B_NBS_NTZ() throws Throwable
    {
       doTransactionCommit(true, true, false, false);
@@ -429,25 +429,25 @@
    {
       doTransactionRollback(false, true, false, false);
    }
-        
+
    public void testRollback_XA_Long_B_NBS_NTZ() throws Throwable
    {
       doTransactionRollback(true, true, false, false);
    }
-   
-   
-   
-   
+
+
+
+
    protected void addRemoveGetReferences(boolean batch) throws Throwable
    {
       doSetup(false, false, false, 100);
-      
+
       Channel channel1 = new SimpleChannel(0, ms);
-      
+
       Channel channel2 = new SimpleChannel(1, ms);
-      
+
       Message[] m = createMessages(10);
-      
+
       MessageReference ref1 = ms.reference(m[0]);
       MessageReference ref2 = ms.reference(m[1]);
       MessageReference ref3 = ms.reference(m[2]);
@@ -458,13 +458,13 @@
       MessageReference ref8 = ms.reference(m[7]);
       MessageReference ref9 = ms.reference(m[8]);
       MessageReference ref10 = ms.reference(m[9]);
-      
+
       MessageReference ref11 = ms.reference(m[0]);
       MessageReference ref12 = ms.reference(m[1]);
       MessageReference ref13 = ms.reference(m[2]);
       MessageReference ref14 = ms.reference(m[3]);
       MessageReference ref15 = ms.reference(m[4]);
-      
+
       List refs = new ArrayList();
       refs.add(ref1);
       refs.add(ref2);
@@ -476,18 +476,18 @@
       refs.add(ref8);
       refs.add(ref9);
       refs.add(ref10);
-      
+
       pm.pageReferences(channel1.getChannelID(), refs, false);
-      
+
       refs = new ArrayList();
       refs.add(ref11);
       refs.add(ref12);
       refs.add(ref13);
       refs.add(ref14);
       refs.add(ref15);
-    
+
       pm.pageReferences(channel2.getChannelID(), refs, false);
-                  
+
       List refIds = getReferenceIds(channel1.getChannelID());
       assertNotNull(refIds);
       assertEquals(10, refIds.size());
@@ -501,7 +501,7 @@
       assertTrue(refIds.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref10.getMessage().getMessageID())));
-      
+
       refIds = getReferenceIds(channel2.getChannelID());
       assertNotNull(refIds);
       assertEquals(5, refIds.size());
@@ -510,7 +510,7 @@
       assertTrue(refIds.contains(new Long(ref13.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref14.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref15.getMessage().getMessageID())));
-     
+
       List msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(10, msgs.size());
@@ -524,14 +524,14 @@
       assertTrue(msgs.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref10.getMessage().getMessageID())));
-      
+
       List msgIds = new ArrayList();
       msgIds.add(new Long(ref3.getMessage().getMessageID()));
       msgIds.add(new Long(ref4.getMessage().getMessageID()));
       msgIds.add(new Long(ref7.getMessage().getMessageID()));
       msgIds.add(new Long(ref9.getMessage().getMessageID()));
       msgIds.add(new Long(ref1.getMessage().getMessageID()));
-      
+
       List ms = pm.getMessages(msgIds);
       assertNotNull(ms);
       assertEquals(5, ms.size());
@@ -540,24 +540,24 @@
       assertTrue(containsMessage(ms, ref7.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref9.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref1.getMessage().getMessageID()));
-      
+
       refs = new ArrayList();
       refs.add(ref12);
       refs.add(ref13);
       refs.add(ref14);
       refs.add(ref15);
       pm.removeDepagedReferences(channel2.getChannelID(), refs);
-      
+
       refIds = getReferenceIds(channel2.getChannelID());
       assertNotNull(refIds);
       assertEquals(1, refIds.size());
       assertTrue(refIds.contains(new Long(ref11.getMessage().getMessageID())));
-      
+
       ms = getMessageIds();
 
       assertNotNull(ms);
       assertEquals(10, ms.size());
-      
+
       assertTrue(msgs.contains(new Long(ref1.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref2.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref3.getMessage().getMessageID())));
@@ -568,14 +568,14 @@
       assertTrue(msgs.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref10.getMessage().getMessageID())));
-     
-      
+
+
       refs = new ArrayList();
       refs.add(ref1);
       refs.add(ref2);
       refs.add(ref3);
       pm.removeDepagedReferences(channel1.getChannelID(), refs);
-      
+
       refIds = getReferenceIds(channel1.getChannelID());
       assertNotNull(refIds);
       assertEquals(7, refIds.size());
@@ -586,12 +586,12 @@
       assertTrue(refIds.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref10.getMessage().getMessageID())));
-     
+
       ms = getMessageIds();
-        
+
       assertNotNull(ms);
       assertEquals(8, ms.size());
-      
+
       assertTrue(msgs.contains(new Long(ref1.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref4.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref5.getMessage().getMessageID())));
@@ -600,11 +600,11 @@
       assertTrue(msgs.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref10.getMessage().getMessageID())));
-      
+
       refs = new ArrayList();
       refs.add(ref11);
       pm.removeDepagedReferences(channel2.getChannelID(), refs);
-      
+
       refs = new ArrayList();
       refs.add(ref4);
       refs.add(ref5);
@@ -614,22 +614,22 @@
       refs.add(ref9);
       refs.add(ref10);
       pm.removeDepagedReferences(channel1.getChannelID(), refs);
-      
+
       ms = getMessageIds();
       assertNotNull(ms);
       assertEquals(0, ms.size());
    }
-   
+
    public void testPageOrders() throws Throwable
    {
       doSetup(false, false, false, 100);
-      
+
       Channel channel = new SimpleChannel(0, ms);
-      
+
       Message[] m = createMessages(10);
-      
+
       List refs = new ArrayList();
-      
+
       MessageReference ref1 = ms.reference(m[0]);
       MessageReference ref2 = ms.reference(m[1]);
       MessageReference ref3 = ms.reference(m[2]);
@@ -640,7 +640,7 @@
       MessageReference ref8 = ms.reference(m[7]);
       MessageReference ref9 = ms.reference(m[8]);
       MessageReference ref10 = ms.reference(m[9]);
-      
+
       refs.add(ref1);
       refs.add(ref2);
       refs.add(ref3);
@@ -651,9 +651,9 @@
       refs.add(ref8);
       refs.add(ref9);
       refs.add(ref10);
-      
-      pm.pageReferences(channel.getChannelID(), refs, false); 
-      
+
+      pm.pageReferences(channel.getChannelID(), refs, false);
+
       ref1.setPagingOrder(0);
       ref2.setPagingOrder(1);
       ref3.setPagingOrder(2);
@@ -664,15 +664,15 @@
       ref8.setPagingOrder(7);
       ref9.setPagingOrder(8);
       ref10.setPagingOrder(9);
-      
+
       pm.updatePageOrder(channel.getChannelID(), refs);
-      
+
       List refInfos = pm.getPagedReferenceInfos(channel.getChannelID(), 0, 10);
-      
+
       assertNotNull(refInfos);
-      
+
       assertEquals(10, refInfos.size());
-      
+
       assertEquals(ref1.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(0)).getMessageId());
       assertEquals(ref2.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(1)).getMessageId());
       assertEquals(ref3.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(2)).getMessageId());
@@ -683,42 +683,42 @@
       assertEquals(ref8.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(7)).getMessageId());
       assertEquals(ref9.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(8)).getMessageId());
       assertEquals(ref10.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(9)).getMessageId());
-      
+
       refInfos = pm.getPagedReferenceInfos(channel.getChannelID(), 3, 5);
-      
+
       assertNotNull(refInfos);
-      
+
       assertEquals(5, refInfos.size());
-      
+
       assertEquals(ref4.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(0)).getMessageId());
       assertEquals(ref5.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(1)).getMessageId());
       assertEquals(ref6.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(2)).getMessageId());
       assertEquals(ref7.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(3)).getMessageId());
       assertEquals(ref8.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(4)).getMessageId());
-    
+
       pm.updateReferencesNotPagedInRange(channel.getChannelID(), 0, 3, 4);
-      
+
       refInfos = pm.getPagedReferenceInfos(channel.getChannelID(), 5, 5);
-      
+
       assertNotNull(refInfos);
-      
+
       assertEquals(5, refInfos.size());
-          
+
       assertEquals(ref6.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(0)).getMessageId());
       assertEquals(ref7.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(1)).getMessageId());
       assertEquals(ref8.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(2)).getMessageId());
       assertEquals(ref9.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(3)).getMessageId());
-      assertEquals(ref10.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(4)).getMessageId());                
+      assertEquals(ref10.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(4)).getMessageId());
    }
-     
+
    public void testGetMessages() throws Throwable
    {
       doSetup(false, false, false, 100);
-      
+
       Channel channel = new SimpleChannel(0, ms);
-      
+
       Message[] m = createMessages(10);
-      
+
       MessageReference ref1 = ms.reference(m[0]);
       MessageReference ref2 = ms.reference(m[1]);
       MessageReference ref3 = ms.reference(m[2]);
@@ -729,7 +729,7 @@
       MessageReference ref8 = ms.reference(m[7]);
       MessageReference ref9 = ms.reference(m[8]);
       MessageReference ref10 = ms.reference(m[9]);
-      
+
       pm.addReference(channel.getChannelID(), ref1, null);
       pm.addReference(channel.getChannelID(), ref2, null);
       pm.addReference(channel.getChannelID(), ref3, null);
@@ -740,7 +740,7 @@
       pm.addReference(channel.getChannelID(), ref8, null);
       pm.addReference(channel.getChannelID(), ref9, null);
       pm.addReference(channel.getChannelID(), ref10, null);
-      
+
       List refIds = getReferenceIds(channel.getChannelID());
       assertNotNull(refIds);
       assertEquals(10, refIds.size());
@@ -754,7 +754,7 @@
       assertTrue(refIds.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref10.getMessage().getMessageID())));
-      
+
       List msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(10, msgs.size());
@@ -768,36 +768,36 @@
       assertTrue(msgs.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref10.getMessage().getMessageID())));
-      
+
       List msgIds = new ArrayList();
       msgIds.add(new Long(ref3.getMessage().getMessageID()));
       msgIds.add(new Long(ref4.getMessage().getMessageID()));
       msgIds.add(new Long(ref7.getMessage().getMessageID()));
       msgIds.add(new Long(ref9.getMessage().getMessageID()));
       msgIds.add(new Long(ref1.getMessage().getMessageID()));
-      
+
       List ms = pm.getMessages(msgIds);
       assertNotNull(ms);
       assertEquals(5, ms.size());
-        
+
       assertTrue(containsMessage(ms, ref3.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref4.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref7.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref9.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref1.getMessage().getMessageID()));
-        
+
    }
-   
+
    public void testGetInitialRefInfos() throws Throwable
    {
       doSetup(false, false, false, 100);
-      
+
       Channel channel = new SimpleChannel(0, ms);
-      
+
       Message[] m = createMessages(10);
-      
+
       List refs = new ArrayList();
-      
+
       MessageReference ref1 = ms.reference(m[0]);
       MessageReference ref2 = ms.reference(m[1]);
       MessageReference ref3 = ms.reference(m[2]);
@@ -808,7 +808,7 @@
       MessageReference ref8 = ms.reference(m[7]);
       MessageReference ref9 = ms.reference(m[8]);
       MessageReference ref10 = ms.reference(m[9]);
-      
+
       refs.add(ref1);
       refs.add(ref2);
       refs.add(ref3);
@@ -819,20 +819,20 @@
       refs.add(ref8);
       refs.add(ref9);
       refs.add(ref10);
-      
-      pm.pageReferences(channel.getChannelID(), refs, false); 
-      
+
+      pm.pageReferences(channel.getChannelID(), refs, false);
+
       //First load exactly 10
       PersistenceManager.InitialLoadInfo info = pm.loadFromStart(channel.getChannelID(), 10);
-      
+
       assertNull(info.getMinPageOrdering());
       assertNull(info.getMaxPageOrdering());
-      
+
       List refInfos = info.getRefInfos();
-      
+
       assertNotNull(refInfos);
       assertEquals(10, refInfos.size());
-      
+
       assertEquals(ref1.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(0)).getMessageId());
       assertEquals(ref2.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(1)).getMessageId());
       assertEquals(ref3.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(2)).getMessageId());
@@ -842,10 +842,10 @@
       assertEquals(ref7.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(6)).getMessageId());
       assertEquals(ref8.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(7)).getMessageId());
       assertEquals(ref9.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(8)).getMessageId());
-      assertEquals(ref10.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(9)).getMessageId());          
+      assertEquals(ref10.getMessage().getMessageID(), ((PersistenceManager.ReferenceInfo)refInfos.get(9)).getMessageId());
    }
-      
-   
+
+
    protected boolean containsMessage(List msgs, long msgId)
    {
       Iterator iter = msgs.iterator();
@@ -855,19 +855,19 @@
          if (m.getMessageID() == msgId)
          {
             return true;
-         }           
+         }
       }
       return false;
    }
-   
+
    public void testGetMessagesMaxParams() throws Throwable
    {
       doSetup(false, false, false, 5);
-      
+
       Channel channel = new SimpleChannel(0, ms);
-      
+
       Message[] m = createMessages(10);
-      
+
       MessageReference ref1 = ms.reference(m[0]);
       MessageReference ref2 = ms.reference(m[1]);
       MessageReference ref3 = ms.reference(m[2]);
@@ -878,7 +878,7 @@
       MessageReference ref8 = ms.reference(m[7]);
       MessageReference ref9 = ms.reference(m[8]);
       MessageReference ref10 = ms.reference(m[9]);
-      
+
       pm.addReference(channel.getChannelID(), ref1, null);
       pm.addReference(channel.getChannelID(), ref2, null);
       pm.addReference(channel.getChannelID(), ref3, null);
@@ -889,7 +889,7 @@
       pm.addReference(channel.getChannelID(), ref8, null);
       pm.addReference(channel.getChannelID(), ref9, null);
       pm.addReference(channel.getChannelID(), ref10, null);
-      
+
       List refIds = getReferenceIds(channel.getChannelID());
       assertNotNull(refIds);
       assertEquals(10, refIds.size());
@@ -903,7 +903,7 @@
       assertTrue(refIds.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(refIds.contains(new Long(ref10.getMessage().getMessageID())));
-      
+
       List msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(10, msgs.size());
@@ -917,14 +917,14 @@
       assertTrue(msgs.contains(new Long(ref8.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref9.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref10.getMessage().getMessageID())));
-      
+
       List msgIds = new ArrayList();
       msgIds.add(new Long(ref3.getMessage().getMessageID()));
       msgIds.add(new Long(ref4.getMessage().getMessageID()));
       msgIds.add(new Long(ref7.getMessage().getMessageID()));
       msgIds.add(new Long(ref9.getMessage().getMessageID()));
       msgIds.add(new Long(ref1.getMessage().getMessageID()));
-      
+
       List ms = pm.getMessages(msgIds);
       assertNotNull(ms);
       assertEquals(5, ms.size());
@@ -932,10 +932,10 @@
       assertTrue(containsMessage(ms, ref4.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref7.getMessage().getMessageID()));
       assertTrue(containsMessage(ms, ref9.getMessage().getMessageID()));
-      assertTrue(containsMessage(ms, ref1.getMessage().getMessageID()));   
+      assertTrue(containsMessage(ms, ref1.getMessage().getMessageID()));
    }
-   
-   
+
+
    protected Message createMessage(byte i, boolean reliable) throws Throwable
    {
       Map headers = generateFilledMap(true);
@@ -949,30 +949,30 @@
                            headers,
                            i % 2 == 0 ? new WibblishObject() : null);
    }
-   
+
    protected Message[] createMessages(int num) throws Throwable
    {
       //Generate some messages with a good range of attribute values
       Message[] messages = new Message[num];
       for (int i = 0; i < num; i++)
-      {            
+      {
          messages[i] = createMessage((byte)i, true);
       }
       return messages;
    }
-   
+
    protected void checkEquivalent(Message m1, Message m2) throws Throwable
    {
       if (m1 == m2)
       {
          fail();
       }
-      
+
       if (m1 == null || m2 == null)
       {
          fail();
       }
-      
+
       //Attributes from org.jboss.messaging.core.Message
       assertEquals(m1.getMessageID(), m2.getMessageID());
       assertEquals(m1.isReliable(), m2.isReliable());
@@ -984,7 +984,7 @@
       Map m2Headers = m2.getHeaders();
       checkMapsEquivalent(m1Headers, m2Headers);
       checkMapsEquivalent(m2Headers, m1Headers);
-      
+
       if (m1.getPayload() instanceof byte[] && m2.getPayload() instanceof byte[])
       {
          this.checkByteArraysEqual((byte[])m1.getPayload(), (byte[])m2.getPayload());
@@ -998,12 +998,12 @@
          this.checkListsEquivalent((List)m1.getPayload(), (List)m2.getPayload());
       }
       else
-      {      
+      {
          assertEquals(m1.getPayload(), m2.getPayload());
       }
-      
+
    }
-   
+
    protected void checkMapsEquivalent(Map headers1, Map headers2)
    {
       Iterator iter = headers1.entrySet().iterator();
@@ -1022,16 +1022,16 @@
          }
       }
    }
-   
+
    protected void checkListsEquivalent(List l1, List l2)
-   {      
+   {
       Iterator iter1 = l1.iterator();
       Iterator iter2 = l2.iterator();
       while (iter1.hasNext())
       {
          Object o1 = iter1.next();
          Object o2 = iter2.next();
-         
+
          if (o1 instanceof byte[])
          {
             checkByteArraysEqual((byte[])o1, (byte[])o2);
@@ -1042,7 +1042,7 @@
          }
       }
    }
-   
+
    public static class WibblishObject implements Serializable
    {
       private static final long serialVersionUID = -822739710811857027L;
@@ -1061,7 +1061,7 @@
          return oo.wibble.equals(this.wibble);
       }
    }
-   
+
    protected HashMap generateFilledMap(boolean useObject)
    {
       HashMap headers = new HashMap();
@@ -1077,7 +1077,7 @@
          {
             k = j % 10;
          }
-         
+
          switch (k)
          {
             case 0:
@@ -1101,47 +1101,47 @@
             case 9:
                headers.put(new GUID().toString(), randByteArray(500));
             case 10:
-               headers.put(new GUID().toString(), new WibblishObject());               
+               headers.put(new GUID().toString(), new WibblishObject());
          }
       }
       return headers;
    }
-   
+
    protected Byte randByte()
    {
       return new Byte((byte)(Math.random() * (2^8 - 1) - (2^7)));
    }
-   
+
    protected Short randShort()
    {
       return new Short((short)(Math.random() * (2^16 - 1) - (2^15)));
    }
-   
+
    protected Integer randInt()
    {
       return new Integer((int)(Math.random() * (2^32 - 1) - (2^31)));
    }
-   
+
    protected Long randLong()
    {
       return new Long((long)(Math.random() * (2^64 - 1) - (2^64)));
    }
-   
+
    protected Boolean randBool()
    {
       return new Boolean(Math.random() > 0.5);
    }
-   
+
    protected Float randFloat()
    {
       return new Float((float)(Math.random() * 1000000));
    }
-   
+
    protected Double randDouble()
    {
       return new Double(Math.random() * 1000000);
    }
-   
+
    protected String randString(int length)
    {
       StringBuffer buf = new StringBuffer(length);
@@ -1151,18 +1151,18 @@
       }
       return buf.toString();
    }
-   
+
    protected byte[] randByteArray(int size)
    {
       String s = randString(size / 2);
       return s.getBytes();
    }
-   
+
    protected Character randChar()
    {
       return new Character((char)randShort().shortValue());
    }
-   
+
    protected void checkByteArraysEqual(byte[] b1, byte[] b2)
    {
       if (b1 == null || b2 == null)
@@ -1173,20 +1173,20 @@
       {
          fail();
       }
-      
+
       for (int i = 0; i < b1.length; i++)
       {
          assertEquals(b1[i], b2[i]);
       }
-      
+
    }
-   
+
    protected class MockXid implements Xid
    {
       byte[] branchQual;
       int formatID;
       byte[] globalTxId;
-      
+
       protected MockXid()
       {
          branchQual = new GUID().toString().getBytes();
@@ -1208,7 +1208,7 @@
       {
          return globalTxId;
       }
-      
+
       public boolean equals(Object other)
       {
          if (!(other instanceof Xid))
@@ -1246,41 +1246,38 @@
          }
          return true;
       }
-      
+
    }
-   
+
    protected void doTransactionCommit(boolean xa, boolean batch, boolean useBinaryStream, boolean trailingByte) throws Throwable
    {
       doSetup(batch, useBinaryStream, trailingByte, 100);
 
       Channel channel = new SimpleChannel(0, ms);
-      
-      IDManager idm = new IDManager("TRANSACTION_ID", 10, pm);
-      idm.start();
-      
-      TransactionRepository txRep = new TransactionRepository(pm, ms, idm);
+
+      TransactionRepository txRep = new TransactionRepository(pm, ms, 0);
       txRep.start();
 
       log.debug("transaction log started");
 
       Message[] messages = createMessages(10);
-      
+
       Message m1 = messages[0];
       Message m2 = messages[1];
-      Message m3 = messages[2];      
+      Message m3 = messages[2];
       Message m4 = messages[3];
       Message m5 = messages[4];
 
       Transaction tx = null;
       if (xa)
-      {         
+      {
          tx = txRep.createTransaction(new MockXid());
       }
       else
       {
          tx = txRep.createTransaction();
       }
-      
+
       if (xa)
       {
     	  assertEquals(1,txRep.getNumberOfRegisteredTransactions());
@@ -1289,10 +1286,10 @@
       {
     	  assertEquals(0,txRep.getNumberOfRegisteredTransactions());
       }
-      
+
       MessageReference ref1 = ms.reference(m1);
-      MessageReference ref2 = ms.reference(m2);  
-      MessageReference ref3 = ms.reference(m3);       
+      MessageReference ref2 = ms.reference(m2);
+      MessageReference ref3 = ms.reference(m3);
       MessageReference ref4 = ms.reference(m4);
       MessageReference ref5 = ms.reference(m5);
 
@@ -1301,14 +1298,14 @@
       // Add first two refs non transactionally
       pm.addReference(channel.getChannelID(), ref1, null);
       pm.addReference(channel.getChannelID(), ref2, null);
-      
+
       //check they're there
       List refs = getReferenceIds(channel.getChannelID());
       assertNotNull(refs);
       assertEquals(2, refs.size());
       assertTrue(refs.contains(new Long(ref1.getMessage().getMessageID())));
       assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));
-      
+
       List msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(2, msgs.size());
@@ -1321,37 +1318,37 @@
       pm.addReference(channel.getChannelID(), ref3, tx);
       pm.addReference(channel.getChannelID(), ref4, tx);
       pm.addReference(channel.getChannelID(), ref5, tx);
-      
+
       //Remove the other 2 transactionally
       pm.removeReference(channel.getChannelID(), ref1, tx);
       pm.removeReference(channel.getChannelID(), ref2, tx);
-      
+
       //Check the changes aren't visible
       refs = getReferenceIds(channel.getChannelID());
       assertNotNull(refs);
       assertEquals(2, refs.size());
       assertTrue(refs.contains(new Long(ref1.getMessage().getMessageID())));
-      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));  
-      
+      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));
+
       msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(2, msgs.size());
       assertTrue(msgs.contains(new Long(ref1.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref2.getMessage().getMessageID())));
-      
+
       //commit transaction
       tx.commit();
 
       assertEquals("numberOfRegisteredTransactions",0,txRep.getNumberOfRegisteredTransactions());
-      
+
       //check we can see only the last 3 refs
       refs = getReferenceIds(channel.getChannelID());
       assertNotNull(refs);
-      assertEquals(3, refs.size()); 
+      assertEquals(3, refs.size());
       assertTrue(refs.contains(new Long(ref3.getMessage().getMessageID())));
-      assertTrue(refs.contains(new Long(ref4.getMessage().getMessageID())));  
+      assertTrue(refs.contains(new Long(ref4.getMessage().getMessageID())));
       assertTrue(refs.contains(new Long(ref5.getMessage().getMessageID())));
-      
+
       msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(3, msgs.size());
@@ -1359,28 +1356,25 @@
       assertTrue(msgs.contains(new Long(ref4.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref5.getMessage().getMessageID())));
    }
-         
+
    protected void doTransactionRollback(boolean xa, boolean batch, boolean useBinaryStream, boolean trailingByte) throws Throwable
    {
       doSetup(batch, useBinaryStream, trailingByte, 100);
 
       Channel channel = new SimpleChannel(0, ms);
-      
-      IDManager idm = new IDManager("TRANSACTION_ID", 10, pm);
-      idm.start();
-      
-      TransactionRepository txRep = new TransactionRepository(pm, ms, idm);
+
+      TransactionRepository txRep = new TransactionRepository(pm, ms, 0);
       txRep.start();
- 
-      Message[] messages = createMessages(10);     
-      
+
+      Message[] messages = createMessages(10);
+
       Message m1 = messages[0];
       Message m2 = messages[1];
-      Message m3 = messages[2];      
+      Message m3 = messages[2];
       Message m4 = messages[3];
       Message m5 = messages[4];
 
-      
+
       Transaction tx = null;
       if (xa)
       {
@@ -1390,71 +1384,71 @@
       {
          tx = txRep.createTransaction();
       }
-      
+
       MessageReference ref1 = ms.reference(m1);
-      MessageReference ref2 = ms.reference(m2);  
-      MessageReference ref3 = ms.reference(m3);       
+      MessageReference ref2 = ms.reference(m2);
+      MessageReference ref3 = ms.reference(m3);
       MessageReference ref4 = ms.reference(m4);
-      MessageReference ref5 = ms.reference(m5);  
+      MessageReference ref5 = ms.reference(m5);
 
       //Add first two refs non transactionally
       pm.addReference(channel.getChannelID(), ref1, null);
       pm.addReference(channel.getChannelID(), ref2, null);
-      
+
       //check they're there
       List refs = getReferenceIds(channel.getChannelID());
       assertNotNull(refs);
       assertEquals(2, refs.size());
       assertTrue(refs.contains(new Long(ref1.getMessage().getMessageID())));
-      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));      
-      
+      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));
+
       List msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(2, msgs.size());
       assertTrue(msgs.contains(new Long(ref1.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref2.getMessage().getMessageID())));
-      
-           
+
+
       //Add the next 3 refs transactionally
       pm.addReference(channel.getChannelID(), ref3, tx);
       pm.addReference(channel.getChannelID(), ref4, tx);
       pm.addReference(channel.getChannelID(), ref5, tx);
-      
+
       //Remove the other 2 transactionally
       pm.removeReference(channel.getChannelID(), ref1, tx);
       pm.removeReference(channel.getChannelID(), ref2, tx);
-      
+
       //Check the changes aren't visible
       refs = getReferenceIds(channel.getChannelID());
       assertNotNull(refs);
       assertEquals(2, refs.size());
       assertTrue(refs.contains(new Long(ref1.getMessage().getMessageID())));
-      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));  
-      
+      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));
+
       msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(2, msgs.size());
       assertTrue(msgs.contains(new Long(ref1.getMessage().getMessageID())));
       assertTrue(msgs.contains(new Long(ref2.getMessage().getMessageID())));
-      
+
       //rollback transaction
       tx.rollback();
-      
+
       refs = getReferenceIds(channel.getChannelID());
       assertNotNull(refs);
       assertEquals(2, refs.size());
       assertTrue(refs.contains(new Long(ref1.getMessage().getMessageID())));
-      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));  
-      
+      assertTrue(refs.contains(new Long(ref2.getMessage().getMessageID())));
+
       msgs = getMessageIds();
       assertNotNull(msgs);
       assertEquals(2, msgs.size());
       assertTrue(msgs.contains(new Long(ref1.getMessage().getMessageID())));
-      assertTrue(msgs.contains(new Long(ref2.getMessage().getMessageID())));          
+      assertTrue(msgs.contains(new Long(ref2.getMessage().getMessageID())));
    }
-   
-   
-  
+
+
+
 }
 
 

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/MessagingQueueTestBase.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/MessagingQueueTestBase.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/MessagingQueueTestBase.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -32,7 +32,6 @@
 import org.jboss.messaging.core.contract.MessageStore;
 import org.jboss.messaging.core.contract.PersistenceManager;
 import org.jboss.messaging.core.contract.Receiver;
-import org.jboss.messaging.core.impl.IDManager;
 import org.jboss.messaging.core.impl.JDBCPersistenceManager;
 import org.jboss.messaging.core.impl.MessagingQueue;
 import org.jboss.messaging.core.impl.message.SimpleMessageStore;
@@ -75,21 +74,19 @@
    public static final int NUMBER_OF_MESSAGES = 10;
 
    // Static --------------------------------------------------------
-   
+
    // Attributes ----------------------------------------------------
 
    protected PersistenceManager pm;
-   
+
    protected TransactionRepository tr;
-   
+
    protected MessageStore ms;
-   
+
    protected ServiceContainer sc;
 
    protected MessagingQueue queue;
-   
-   protected IDManager idm;
-   
+
    // Constructors --------------------------------------------------
 
    public MessagingQueueTestBase(String name)
@@ -102,7 +99,7 @@
    public void setUp() throws Exception
    {
       super.setUp();
-      
+
       sc = new ServiceContainer("all,-remoting,-security");
       sc.start();
 
@@ -111,30 +108,25 @@
                                       true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));
       ((JDBCPersistenceManager)pm).injectNodeID(1);
       pm.start();
-      
-      idm = new IDManager("TRANSACTION_ID", 10, pm);
-      idm.start();
-      
+
       ms = new SimpleMessageStore();
       ms.start();
-      
-      tr = new TransactionRepository(pm, ms, idm);
+
+      tr = new TransactionRepository(pm, ms, 0);
       tr.start();
-      
+
    }
 
    public void tearDown() throws Exception
    {
       sc.stop();
-      
+
       pm.stop();
-      idm.stop();
       tr.stop();
       ms.stop();
-      
-      sc = null;   
+
+      sc = null;
       pm = null;
-      idm = null;
       ms = null;
       tr = null;
       super.tearDown();
@@ -151,7 +143,7 @@
          {
             Object o = j.next();
             Message m = (Message)o;
-            
+
             if (a[i].getMessage().getMessageID() == m.getMessageID() &&
                 m.getPayload().equals(a[i].getMessage().getPayload()))
             {
@@ -195,7 +187,7 @@
 
 
    // Channel tests -------------------------------------------------
-   
+
    public void testUnreliableSynchronousDeliveryTwoReceivers() throws Exception
    {
       if (queue.isRecoverable())
@@ -207,12 +199,12 @@
       SimpleDeliveryObserver observer = new SimpleDeliveryObserver();
       SimpleReceiver r1 = new SimpleReceiver("ONE", SimpleReceiver.ACKING);
       SimpleReceiver r2 = new SimpleReceiver("TWO", SimpleReceiver.ACKING);
-      
+
       queue.getLocalDistributor().add(r1);
       queue.getLocalDistributor().add(r2);
-      
+
       Delivery d = queue.handle(observer, createReference(0, false, "payload"), null);
-      
+
       List l1 = r1.getMessages();
       List l2 = r2.getMessages();
       if (l2.isEmpty())
@@ -263,7 +255,7 @@
          assertEquals("payload", m.getPayload());
       }
    }
-   
+
    /*
     * If a channel has a set a receiver and remove is called with a different receiver
     * need to ensure the receiver is not removed (since it doesn't match)
@@ -271,29 +263,29 @@
    public void testRemoveDifferentReceiver() throws Exception
    {
       Receiver receiver1 = new SimpleReceiver();
-      
+
       Receiver receiver2 = new SimpleReceiver();
-      
+
       assertFalse(queue.getLocalDistributor().iterator().hasNext());
-      
+
       queue.getLocalDistributor().add(receiver1);
-      
+
       assertTrue(queue.getLocalDistributor().contains(receiver1));
-      
+
       queue.getLocalDistributor().remove(receiver1);
-      
+
       assertFalse(queue.getLocalDistributor().iterator().hasNext());
-      
+
       assertFalse(queue.getLocalDistributor().contains(receiver1));
-      
+
       queue.getLocalDistributor().add(receiver1);
-      
+
       assertTrue(queue.getLocalDistributor().contains(receiver1));
-      
+
       queue.getLocalDistributor().remove(receiver2);
-      
+
       assertTrue(queue.getLocalDistributor().contains(receiver1));
-                 
+
    }
 
    public void testClosedChannel() throws Exception
@@ -411,7 +403,7 @@
       assertEquals(10, receiver.getMessages().size());
       for(int i = 0; i < NUMBER_OF_MESSAGES; i++)
       {
-         assertEquals(i, ((Message)receiver.getMessages().get(i)).getMessageID());         
+         assertEquals(i, ((Message)receiver.getMessages().get(i)).getMessageID());
       }
       receiver.clear();
 
@@ -445,7 +437,7 @@
 
       MessageReference ref = createReference(0, true, "payload");
       SimpleDeliveryObserver observer = new SimpleDeliveryObserver();
-      
+
       log.trace("ref is reliable:" + ref.getMessage().isReliable());
 
       // non-transacted send, reliable message, one message
@@ -508,7 +500,7 @@
       assertEquals(10, receiver.getMessages().size());
       for(int i = 0; i < NUMBER_OF_MESSAGES; i++)
       {
-         assertEquals(i, ((Message)receiver.getMessages().get(i)).getMessageID());         
+         assertEquals(i, ((Message)receiver.getMessages().get(i)).getMessageID());
       }
       receiver.clear();
 
@@ -653,7 +645,7 @@
    ////////// Multiple message
    //////////
 
-   
+
    public void testNonRecoverableChannel_8_1_mixed_1() throws Exception
    {
       if (queue.isRecoverable())
@@ -693,12 +685,12 @@
       assertEquals(0, queue.browse(null).size());
 
       tx.commit();
-        
+
       assertEqualSets(refs, queue.browse(null));
    }
-   
-  
 
+
+
    ///////////
    /////////// Channel accepts reliable messages
    ///////////
@@ -1221,8 +1213,8 @@
    ////////// One message
    //////////
 
- 
 
+
    ///////////
    /////////// Channel accepts reliable messages
    ///////////
@@ -1271,8 +1263,8 @@
    ////////// Multiple message
    //////////
 
-   
 
+
    /**
     * This is a variation where I send a mixture of reliable and non-reliable messages,
     */
@@ -1772,7 +1764,7 @@
       tx.commit();
 
       assertTrue(queue.browse(null).isEmpty());
-      
+
       deliveringCount = queue.getDeliveringCount();
       assertEquals(0, deliveringCount);
    }
@@ -1979,7 +1971,7 @@
    //////////// Non-transacted acknowledgment
    ////////////
 
-  
+
    ///////////
    /////////// Channel accepts reliable messages
    ///////////
@@ -2321,7 +2313,7 @@
       tx.commit();
 
       int deliveringCount = queue.getDeliveringCount();
-      assertEquals(1, deliveringCount);      
+      assertEquals(1, deliveringCount);
 
       List received = r.getMessages();
       assertEquals(1, received.size());
@@ -2335,9 +2327,9 @@
    ////////// Multiple message
    //////////
 
-  
-   
 
+
+
    ///////////
    /////////// Channel accepts reliable messages
    ///////////
@@ -2378,7 +2370,7 @@
 
       int deliveringCount = queue.getDeliveringCount();
       assertEquals(NUMBER_OF_MESSAGES, deliveringCount);
-      
+
       assertEqualSets(refs, r.getMessages());
    }
 
@@ -3887,7 +3879,7 @@
 
       // non-transacted send, non-reliable message, one message
       Delivery delivery = queue.handle(observer, ref, null);
-      
+
       int deliveringCount = queue.getDeliveringCount();
       assertEquals(1, deliveringCount);
 
@@ -4453,7 +4445,7 @@
       }
 
       assertEquals(NUMBER_OF_MESSAGES, queue.getDeliveringCount());
-      
+
       assertEqualSets(refs, r.getMessages());
 
       for(Iterator i = r.getMessages().iterator(); i.hasNext();)
@@ -4769,8 +4761,8 @@
       assertTrue(r.getMessages().isEmpty());
 
       tx.commit();
-      
-      
+
+
       assertEquals(NUMBER_OF_MESSAGES, queue.getDeliveringCount());
       assertEqualSets(refs, r.getMessages());
 
@@ -4823,7 +4815,7 @@
       assertTrue(r.getMessages().isEmpty());
 
       tx.commit();
-      
+
       assertEquals(NUMBER_OF_MESSAGES, queue.getDeliveringCount());
       assertEqualSets(refs, r.getMessages());
 
@@ -5376,7 +5368,7 @@
 
 
    // Package protected ---------------------------------------------
-   
+
    // Protected -----------------------------------------------------
 
 //   protected abstract void crashChannel() throws Exception;
@@ -5384,17 +5376,17 @@
 //   protected abstract void recoverChannel() throws Exception;
 
    // Private -------------------------------------------------------
-   
+
    private MessageReference createReference(long id, boolean reliable, Serializable payload)
    {
       return ms.reference(CoreMessageFactory.createCoreMessage(id, reliable, payload));
    }
-   
+
    private MessageReference createReference(long id)
    {
       return ms.reference(CoreMessageFactory.createCoreMessage(id));
    }
-   
+
    // Inner classes -------------------------------------------------
 
 }

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/PostOfficeTestBase.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/PostOfficeTestBase.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/PostOfficeTestBase.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -48,7 +48,7 @@
 import org.jboss.test.messaging.util.CoreMessageFactory;
 
 /**
- * 
+ *
  * A PostOfficeTestBase
  *
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
@@ -63,13 +63,13 @@
    // Constants ------------------------------------------------------------------------------------
 
    // Static ---------------------------------------------------------------------------------------
-	
-   protected static PostOffice createClusteredPostOffice(int nodeID,   		
+
+   protected static PostOffice createClusteredPostOffice(int nodeID,
 			                                                String groupName,
 			                                                long stateTimeout,
 			                                                long castTimeout,
 			                                                ServiceContainer sc,
-			                                                MessageStore ms,			                                         
+			                                                MessageStore ms,
 			                                                TransactionRepository tr,
 			                                                PersistenceManager pm)
       throws Exception
@@ -90,19 +90,19 @@
          new ClusteredPersistenceServiceConfigFileJChannelFactory(configFilePath,
                                                                   ignoreMultiplexer,
                                                                   sc.getMBeanServer());
-      
+
       MessagingPostOffice postOffice =
          new MessagingPostOffice(sc.getDataSource(), sc.getTransactionManager(),
                                  sc.getPostOfficeSQLProperties(), true, nodeID,
                                  "Clustered", ms, pm, tr, ff, cf, idm, cn,
                                  groupName, jChannelFactory,
                                  stateTimeout, castTimeout, true, 100);
-      
+
       postOffice.start();
 
       return postOffice;
    }
-   
+
    protected static PostOffice createNonClusteredPostOffice(ServiceContainer sc, MessageStore ms, TransactionRepository tr,
    		                                                   PersistenceManager pm)
    	throws Exception
@@ -120,27 +120,25 @@
    	postOffice.start();
 
    	return postOffice;
-   }   
+   }
 
    // Attributes -----------------------------------------------------------------------------------
 
    protected ServiceContainer sc;
 
    protected IDManager channelIDManager;
-   
-   protected IDManager transactionIDManager;
-   
+
    protected PersistenceManager pm;
-      
+
    protected MessageStore ms;
-   
+
    protected TransactionRepository tr;
-   
+
    protected ConditionFactory conditionFactory;
-   
+
    private static long msgCount;
-   
-   
+
+
    // Constructors --------------------------------------------------
 
    public PostOfficeTestBase(String name)
@@ -149,48 +147,48 @@
    }
 
    // Public --------------------------------------------------------
-   
+
    // Protected --------------------------------------------------------
-   
+
 	protected PostOffice createNonClusteredPostOffice() throws Exception
 	{
 		return createNonClusteredPostOffice(sc, ms, tr, pm);
 	}
-	
+
 	protected PostOffice createClusteredPostOffice(int nodeID) throws Exception
    {
       //System property provides group name so we can run concurrently in QA lab
       String groupName = System.getProperty("jboss.messaging.groupname");
-      
+
       log.info("Creating clusteredPostOffice node " + nodeID);
-      
+
       return createClusteredPostOffice(nodeID, groupName == null ? "testgroup" : groupName, 5000, 5000, sc, ms, tr, pm);
    }
-   
+
    protected List sendMessages(String conditionText, boolean persistent, PostOffice office, int num, Transaction tx) throws Exception
    {
       List list = new ArrayList();
-      
+
       for (int i = 0; i < num; i++)
-      {         
-         Message msg = CoreMessageFactory.createCoreMessage(msgCount++, persistent, null);      
-         
-         MessageReference ref = ms.reference(msg);         
-         
+      {
+         Message msg = CoreMessageFactory.createCoreMessage(msgCount++, persistent, null);
+
+         MessageReference ref = ms.reference(msg);
+
          Condition condition = conditionFactory.createCondition(conditionText);
-         
-         boolean routed = office.route(ref, condition, null);         
-         
+
+         boolean routed = office.route(ref, condition, null);
+
          assertTrue(routed);
-         
+
          list.add(msg);
       }
-      
+
       Thread.sleep(1000);
-      
+
       return list;
    }
-   
+
    protected void checkContainsAndAcknowledge(Message msg, SimpleReceiver receiver, Queue queue) throws Throwable
    {
       List msgs = receiver.getMessages();
@@ -201,16 +199,16 @@
       receiver.acknowledge(msgRec, null);
       msgs = queue.browse(null);
       assertNotNull(msgs);
-      assertTrue(msgs.isEmpty()); 
+      assertTrue(msgs.isEmpty());
       receiver.clear();
    }
-   
+
    protected void checkContainsAndAcknowledge(List msgList, SimpleReceiver receiver, Queue queue) throws Throwable
    {
       List msgs = receiver.getMessages();
       assertNotNull(msgs);
       assertEquals(msgList.size(), msgs.size());
-      
+
       for (int i = 0; i < msgList.size(); i++)
       {
          Message msgRec = (Message)msgs.get(i);
@@ -218,13 +216,13 @@
          assertEquals(msgCheck.getMessageID(), msgRec.getMessageID());
          receiver.acknowledge(msgRec, null);
       }
-      
+
       msgs = queue.browse(null);
       assertNotNull(msgs);
-      assertTrue(msgs.isEmpty()); 
+      assertTrue(msgs.isEmpty());
       receiver.clear();
    }
-   
+
    protected void checkEmpty(SimpleReceiver receiver) throws Throwable
    {
       List msgs = receiver.getMessages();
@@ -247,13 +245,10 @@
       ((JDBCPersistenceManager)pm).injectNodeID(1);
       pm.start();
 
-      transactionIDManager = new IDManager("TRANSACTION_ID", 10, pm);
-      transactionIDManager.start();
-
       ms = new SimpleMessageStore();
       ms.start();
 
-      tr = new TransactionRepository(pm, ms, transactionIDManager);
+      tr = new TransactionRepository(pm, ms, 0);
       tr.start();
 
       channelIDManager = new IDManager("CHANNEL_ID", 10, pm);
@@ -289,7 +284,6 @@
           pm.stop();
           tr.stop();
           ms.stop();
-          transactionIDManager.stop();
           channelIDManager.stop();
 
           super.tearDown();

Copied: branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/RotatingIDTest.java (from rev 3746, branches/Branch_Stable_temp/tests/src/org/jboss/test/messaging/core/RotatingIDTest.java)
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/RotatingIDTest.java	                        (rev 0)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/RotatingIDTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -0,0 +1,87 @@
+/*
+  * JBoss, Home of Professional Open Source
+  * Copyright 2005, JBoss Inc., and individual contributors as indicated
+  * by the @authors tag. See the copyright.txt in the distribution for a
+  * full listing of individual contributors.
+  *
+  * This is free software; you can redistribute it and/or modify it
+  * under the terms of the GNU Lesser General Public License as
+  * published by the Free Software Foundation; either version 2.1 of
+  * the License, or (at your option) any later version.
+  *
+  * This software is distributed in the hope that it will be useful,
+  * but WITHOUT ANY WARRANTY; without even the implied warranty of
+  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+  * Lesser General Public License for more details.
+  *
+  * You should have received a copy of the GNU Lesser General Public
+  * License along with this software; if not, write to the Free
+  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+  */
+package org.jboss.test.messaging.core;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.jboss.messaging.core.impl.RotatingID;
+import org.jboss.test.messaging.MessagingTestCase;
+
+/**
+ *
+ * A RotatingIDTest
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class RotatingIDTest extends MessagingTestCase
+{
+   // Constants -----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public RotatingIDTest(String name)
+   {
+      super(name);
+   }
+
+   // Public --------------------------------------------------------
+
+   public void testRotatingID() throws Exception
+   {
+      final int NUM_ITERS = 1000;
+
+      Set<Long> ids = new HashSet<Long>(NUM_ITERS);
+
+      RotatingID id = new RotatingID(63);
+
+      for (int i = 0; i < NUM_ITERS; i++)
+      {
+         long l = id.getID();
+
+         if (ids.contains(l))
+         {
+            fail("Already produced id " + l);
+         }
+
+         ids.add(l);
+
+         System.out.println(l);
+      }
+   }
+
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+
+}
+

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/PagingStateTestBase.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/PagingStateTestBase.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/PagingStateTestBase.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -51,9 +51,9 @@
 import org.jboss.util.id.GUID;
 
 /**
- * 
+ *
  * A PagingStateTestBase.
- * 
+ *
  * @author <a href="tim.fox at jboss.com">Tim Fox</a>
  * @version <tt>$Revision$</tt>
  *
@@ -64,14 +64,13 @@
    // Constants -----------------------------------------------------
 
    // Static --------------------------------------------------------
-         
+
    // Attributes ----------------------------------------------------
 
    protected ServiceContainer sc;
    protected PersistenceManager pm;
    protected SimpleMessageStore ms;
    protected TransactionRepository tr;
-   protected IDManager idm;
 
    // Constructors --------------------------------------------------
 
@@ -81,8 +80,8 @@
    }
 
    // Public --------------------------------------------------------
-   
 
+
    public void setUp() throws Exception
    {
       super.setUp();
@@ -93,42 +92,39 @@
       pm =
          new JDBCPersistenceManager(sc.getDataSource(), sc.getTransactionManager(),
                   sc.getPersistenceManagerSQLProperties(),
-                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));  
+                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));
       ((JDBCPersistenceManager)pm).injectNodeID(1);
       pm.start();
- 
-      idm = new IDManager("TRANSACTION_ID", 10, pm);
-      idm.start();
-      
+
       ms = new SimpleMessageStore();
       ms.start();
-      
-      tr = new TransactionRepository(pm, ms, idm);
-      tr.start();          
-      
+
+      tr = new TransactionRepository(pm, ms, 0);
+      tr.start();
+
       ms.clear();
    }
-   
-   
+
+
    public void tearDown() throws Exception
    {
-   	; 
+   	;
    	if (checkNoMessageData())
    	{
    		fail("Message data still exists");
-   	}  	
+   	}
       pm.stop();
       tr.stop();
       ms.stop();
-      sc.stop();     
+      sc.stop();
       super.tearDown();
    }
-   
+
    protected Transaction createXATx() throws Exception
    {
       MessagingXid xid =
          new MessagingXid(new GUID().toString().getBytes(), 345, new GUID().toString().getBytes());
-      
+
       return tr.createTransaction(xid);
    }
 
@@ -145,73 +141,73 @@
          i++;
       }
    }
-   
+
    class ConsumingReceiver implements Receiver
    {
       int numToConsume;
-      
+
       int count;
-      
+
       MessageReference[] refs;
-      
+
       int consumeCount;
-      
+
       boolean xa;
-      
+
       boolean tx;
-      
+
       SimpleDelivery[] dels;
-      
+
       ConsumingReceiver(int numToConsume, MessageReference[] refs,
                         int consumeCount, boolean tx, boolean xa) throws Exception
       {
          this.numToConsume = numToConsume;
-         
+
          this.refs = refs;
-         
+
          this.consumeCount = consumeCount;
-         
+
          this.xa = xa;
-         
+
          this.tx = tx;
-         
+
          this.dels = new SimpleDelivery[numToConsume];
       }
 
       public synchronized Delivery handle(DeliveryObserver observer,
                                           MessageReference ref, Transaction tx)
-      {  
+      {
          if (count >= numToConsume)
          {
             return null;
          }
-         
+
          assertEquals(refs[consumeCount + count].getMessage().getMessageID(), ref.getMessage().getMessageID());
-         
+
          SimpleDelivery del = new SimpleDelivery(observer, ref);
-         
+
          dels[count] = del;
-         
+
          count++;
-         
+
          if (count == numToConsume)
          {
             notify();
          }
-           
-         return del;                 
-      }      
-      
+
+         return del;
+      }
+
       void acknowledge() throws Throwable
       {
          //Wait for them all to arrive first
-         
+
          synchronized (this)
-         {         
+         {
             while (count < numToConsume)
             {
                wait(10000);
-      
+
                if (count < numToConsume)
                {
                   PagingStateTestBase.fail();
@@ -219,9 +215,9 @@
                }
             }
          }
-         
+
          Transaction theTx = null;
-         
+
          if (tx)
          {
             if (xa)
@@ -233,12 +229,12 @@
                theTx = tr.createTransaction();
             }
          }
-         
+
          for (int i = 0; i < numToConsume; i++)
          {
             dels[i].acknowledge(theTx);
          }
-         
+
          if (tx)
          {
             if (xa)
@@ -250,25 +246,25 @@
             {
                theTx.commit();
             }
-         }    
+         }
       }
    }
-   
+
    class CancellingReceiver implements Receiver
    {
       int numToCancel;
-      
+
       int count;
-        
+
       SimpleDelivery[] toCancel;
-      
+
       CancellingReceiver(int numToConsume)
          throws Exception
       {
          this.numToCancel = numToConsume;
-         
+
          this.toCancel = new SimpleDelivery[numToCancel];
-         
+
       }
 
       public synchronized Delivery handle(DeliveryObserver observer,
@@ -278,52 +274,52 @@
          {
             return null;
          }
-         
+
          SimpleDelivery del = new SimpleDelivery(observer, ref);
-         
-         toCancel[count] = del;                  
-         
-         count++;         
-         
+
+         toCancel[count] = del;
+
+         count++;
+
          if (count == numToCancel)
          {
             notify();
          }
-         
+
          return del;
-                  
-      }      
-      
+
+      }
+
       public synchronized SimpleDelivery[] getToCancel() throws Exception
       {
          // Wait for them all to arrive first
-         
+
          while (count < numToCancel)
          {
             wait(1000);
-            
+
             if (count < numToCancel)
             {
                PagingStateTestBase.fail();
                return null;
             }
          }
-         
+
          return toCancel;
-         
+
       }
-      
+
       void cancel() throws Exception
       {
          //Wait for them all to arrive first
-         
+
          synchronized (this)
          {
-            
+
             while (count < numToCancel)
             {
                wait(1000);
-               
+
                if (count < numToCancel)
                {
                   PagingStateTestBase.fail();
@@ -331,7 +327,7 @@
                }
             }
          }
-         
+
          for (int i = numToCancel - 1; i >=0; i--)
          {
             try
@@ -357,7 +353,7 @@
       r.acknowledge();
       queue.getLocalDistributor().remove(r);
    }
-   
+
    protected void consumeInTx(Queue queue, int consumeCount,
          MessageReference[] refs, int num)
       throws Throwable
@@ -368,7 +364,7 @@
       r.acknowledge();
       queue.getLocalDistributor().remove(r);
    }
-   
+
    protected void consumeIn2PCTx(Queue queue, int consumeCount,
          MessageReference[] refs, int num)
       throws Throwable
@@ -382,55 +378,55 @@
       //thus removing the ref
     //  Thread.sleep(500);
    }
-   
+
    protected SimpleDelivery[] getDeliveries(Queue queue, int number) throws Exception
    {
       CancellingReceiver r1 = new CancellingReceiver(number);
       queue.getLocalDistributor().add(r1);
-      queue.deliver();   
+      queue.deliver();
       SimpleDelivery[] dels = r1.getToCancel();
       queue.getLocalDistributor().remove(r1);
       //Need to give enough time for the call to handle to complete and return
       //thus removing the ref
-    //  Thread.sleep(500);      
-      
+    //  Thread.sleep(500);
+
       return dels;
    }
-   
+
    protected void cancelDeliveries(Queue queue, int number) throws Exception
    {
       CancellingReceiver r1 = new CancellingReceiver(number);
       queue.getLocalDistributor().add(r1);
-      queue.deliver();   
+      queue.deliver();
       r1.cancel();
       queue.getLocalDistributor().remove(r1);
       //Need to give enough time for the call to handle to complete and return
       //thus removing the ref
-     // Thread.sleep(500);      
+     // Thread.sleep(500);
    }
-   
-   
+
+
    protected List getReferenceIdsOrderedByOrd(long queueId) throws Exception
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
 
       Connection conn = ds.getConnection();
-      
+
       List msgIds = new ArrayList();
 
       String sql =
          "SELECT MESSAGE_ID, ORD, PAGE_ORD FROM JBM_MSG_REF WHERE CHANNEL_ID=? ORDER BY ORD";
       PreparedStatement ps = conn.prepareStatement(sql);
       ps.setLong(1, queueId);
-   
+
       ResultSet rs = ps.executeQuery();
-            
+
       while (rs.next())
       {
          long msgId = rs.getLong(1);
@@ -439,49 +435,49 @@
       }
       rs.close();
       ps.close();
-       
+
       conn.close();
-      
+
       mgr.commit();
 
       if (txOld != null)
       {
          mgr.resume(txOld);
       }
-      
+
       return msgIds;
    }
-   
+
    protected List getReferenceIdsOrderedByPageOrd(long queueId) throws Exception
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
 
       Connection conn = ds.getConnection();
-      
+
       List msgIds = new ArrayList();
- 
+
       String sql =
          "SELECT MESSAGE_ID, ORD, PAGE_ORD FROM JBM_MSG_REF WHERE CHANNEL_ID=? ORDER BY PAGE_ORD";
       PreparedStatement ps = conn.prepareStatement(sql);
       ps.setLong(1, queueId);
-   
+
       ResultSet rs = ps.executeQuery();
-            
+
       while (rs.next())
       {
-         long msgId = rs.getLong(1);     
+         long msgId = rs.getLong(1);
 
          msgIds.add(new Long(msgId));
       }
       rs.close();
       ps.close();
-       
+
       conn.close();
 
       mgr.commit();
@@ -490,17 +486,17 @@
       {
          mgr.resume(txOld);
       }
-      
+
       return msgIds;
    }
-   
+
    protected List getPagedReferenceIds(long queueId) throws Exception
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
 
@@ -511,11 +507,11 @@
 
       PreparedStatement ps = conn.prepareStatement(sql);
       ps.setLong(1, queueId);
-   
+
       ResultSet rs = ps.executeQuery();
-      
+
       List msgIds = new ArrayList();
-      
+
       while (rs.next())
       {
          long msgId = rs.getLong(1);
@@ -531,28 +527,28 @@
       {
          mgr.resume(txOld);
       }
-      
+
       return msgIds;
    }
-   
+
    protected List getMessageIds() throws Exception
    {
       InitialContext ctx = new InitialContext();
 
       TransactionManager mgr = (TransactionManager)ctx.lookup(TransactionManagerService.JNDI_NAME);
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
-      
+
       javax.transaction.Transaction txOld = mgr.suspend();
       mgr.begin();
 
       Connection conn = ds.getConnection();
       String sql = "SELECT MESSAGE_ID FROM JBM_MSG ORDER BY MESSAGE_ID";
       PreparedStatement ps = conn.prepareStatement(sql);
-      
+
       ResultSet rs = ps.executeQuery();
-      
+
       List msgIds = new ArrayList();
-      
+
       while (rs.next())
       {
          long msgId = rs.getLong(1);
@@ -568,7 +564,7 @@
       {
          mgr.resume(txOld);
       }
-      
+
       return msgIds;
    }
 }

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/SingleChannel_ReloadTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/SingleChannel_ReloadTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/core/paging/SingleChannel_ReloadTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -32,12 +32,12 @@
 import org.jboss.test.messaging.util.CoreMessageFactory;
 
 /**
- * 
+ *
  * A PagingTest_Reload.
- * 
+ *
  * @author <a href="tim.fox at jboss.com">Tim Fox</a>
  * @author <a href="mailto:juha at jboss.org">Juha Lindfors</a>
- * 
+ *
  * @version <tt>$Revision$</tt>
  *
  * $Id$
@@ -53,318 +53,318 @@
 
    public void setUp() throws Exception
    {
-      super.setUp(); 
+      super.setUp();
    }
-   
-   
+
+
    public void tearDown() throws Exception
    {
       super.tearDown();
    }
-   
+
    public void testRecoverableQueueCrash() throws Throwable
    {
       MessagingQueue queue = new MessagingQueue(1, "queue1", 1, ms, pm, true, -1, null, 100, 20, 10, false, 300000);
       queue.activate();
-      
+
       Message[] msgs = new Message[200];
-      
+
       MessageReference[] refs = new MessageReference[200];
-       
+
       //Send 150 np mesages
       for (int i = 0; i < 150; i++)
       {
          msgs[i] = CoreMessageFactory.createCoreMessage(i, false, null);
-         
+
          refs[i] = msgs[i].createReference();
-                
-         queue.handle(null, refs[i], null); 
+
+         queue.handle(null, refs[i], null);
       }
-      
+
       //Send 50 p messages
       for (int i = 150; i < 200; i++)
       {
          msgs[i] = CoreMessageFactory.createCoreMessage(i, true, null);
-         
+
          refs[i] = msgs[i].createReference();
-                
-         queue.handle(null, refs[i], null); 
+
+         queue.handle(null, refs[i], null);
       }
 
       List refIds = getReferenceIdsOrderedByPageOrd(queue.getChannelID());
       assertEquals(100, refIds.size());
-                                                
+
       assertEquals(100, queue.memoryRefCount());
-      
+
       assertEquals(0, queue.downCacheCount());
-      
-      assertTrue(queue.isPaging());      
-      
+
+      assertTrue(queue.isPaging());
+
       assertEquals(0, queue.getDeliveringCount());
-      
+
       //Stop and restart the persistence manager
       //All the paged refs will survive
-       
+
       pm.stop();
       tr.stop();
       ms.stop();
-      
+
       pm =
          new JDBCPersistenceManager(sc.getDataSource(), sc.getTransactionManager(),
                   sc.getPersistenceManagerSQLProperties(),
-                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));   
+                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));
       ((JDBCPersistenceManager)pm).injectNodeID(1);
       pm.start();
-      
+
       ms = new SimpleMessageStore();
       ms.start();
-      
-      tr = new TransactionRepository(pm, ms, idm);
 
+      tr = new TransactionRepository(pm, ms, 0);
+
       tr.start();
-         
+
       MessagingQueue queue2 = new MessagingQueue(1, "queue1", 1, ms, pm, true, -1, null, 100, 20, 10, false, 300000);
-    
+
       queue2.load();
       queue2.activate();
-      
+
       refIds = getReferenceIdsOrderedByPageOrd(queue2.getChannelID());
       assertEquals(50, refIds.size());
-      
+
       assertEquals(100, queue2.memoryRefCount());
       assertEquals(0, queue2.downCacheCount());
-      assertFalse(queue2.isPaging());      
-      
+      assertFalse(queue2.isPaging());
+
       assertEquals(0, queue2.getDeliveringCount());
-                   
+
       this.consume(queue2, 100, refs, 100);
-      
+
       refIds = getReferenceIdsOrderedByPageOrd(queue2.getChannelID());
       assertEquals(0, refIds.size());
-                                                
+
       assertEquals(0, queue2.memoryRefCount());
-      
+
       assertEquals(0, queue2.downCacheCount());
-      
-      assertFalse(queue2.isPaging());      
-      
+
+      assertFalse(queue2.isPaging());
+
       assertEquals(0, queue2.getDeliveringCount());
-      
+
       assertEquals(0, queue2.getMessageCount());
    }
-   
+
    public void testNonRecoverableQueueCrash() throws Throwable
    {
       //Non recoverable queue - eg temporary queue
-      
+
       MessagingQueue queue = new MessagingQueue(1, "queue1", 1, ms, pm, false, -1, null, 100, 20, 10, false, 300000);
       queue.activate();
-         	      
+
       Message[] msgs = new Message[200];
-      
+
       MessageReference[] refs = new MessageReference[200];
-       
+
       //Send 150 np mesages
       for (int i = 0; i < 150; i++)
       {
          msgs[i] = CoreMessageFactory.createCoreMessage(i, false, null);
-         
+
          refs[i] = msgs[i].createReference();
-                
-         queue.handle(null, refs[i], null); 
+
+         queue.handle(null, refs[i], null);
       }
-      
+
       //Send 50 p messages
       for (int i = 150; i < 200; i++)
       {
          msgs[i] = CoreMessageFactory.createCoreMessage(i, true, null);
-         
+
          refs[i] = msgs[i].createReference();
-                
-         queue.handle(null, refs[i], null); 
+
+         queue.handle(null, refs[i], null);
       }
 
       List refIds = getReferenceIdsOrderedByPageOrd(queue.getChannelID());
       assertEquals(100, refIds.size());
-                                                
+
       assertEquals(100, queue.memoryRefCount());
-      
+
       assertEquals(0, queue.downCacheCount());
-      
-      assertTrue(queue.isPaging());      
-      
+
+      assertTrue(queue.isPaging());
+
       assertEquals(0, queue.getDeliveringCount());
-      
-      //Stop and restart      
 
+      //Stop and restart
+
       pm.stop();
       tr.stop();
       ms.stop();
-      
+
       pm =
          new JDBCPersistenceManager(sc.getDataSource(), sc.getTransactionManager(),
                   sc.getPersistenceManagerSQLProperties(),
-                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle")); 
+                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));
       ((JDBCPersistenceManager)pm).injectNodeID(1);
       pm.start();
-      
+
       ms = new SimpleMessageStore();
       ms.start();
-      
-      tr = new TransactionRepository(pm, ms, idm);
+
+      tr = new TransactionRepository(pm, ms, 0);
       tr.start();
 
       MessagingQueue queue2 = new MessagingQueue(1, "queue1", 1, ms, pm, false, -1, null, 100, 20, 10, false, 300000);
-      
+
       queue2.load();
-      
+
       queue2.activate();
-      
+
       //There should be none in the db - the queue is non recoverable
       refIds = getReferenceIdsOrderedByPageOrd(queue2.getChannelID());
       assertEquals(0, refIds.size());
-      
+
       ;
       List msgIds = getMessageIds();
       assertEquals(0, msgIds.size());
-                                                                  
+
       assertEquals(100, queue2.memoryRefCount());
-      
+
       assertEquals(0, queue2.downCacheCount());
-      
-      assertFalse(queue2.isPaging());      
-      
+
+      assertFalse(queue2.isPaging());
+
       this.consume(queue2, 100, refs, 100);
-      
+
       assertEquals(0, queue2.getDeliveringCount());
-      
+
       assertEquals(0, queue2.getMessageCount());
    }
-   
+
    public void testNonRecoverableQueueRemoveAllReferences() throws Throwable
    {
       //Non recoverable queue - eg temporary queue
-      
+
       MessagingQueue queue = new MessagingQueue(1, "queue1", 1, ms, pm, false, -1, null, 100, 20, 10, false, 300000);
       queue.activate();
-        
+
       Message[] msgs = new Message[200];
-      
+
       MessageReference[] refs = new MessageReference[200];
-       
+
       //Send 150 np mesages
       for (int i = 0; i < 150; i++)
       {
          msgs[i] = CoreMessageFactory.createCoreMessage(i, false, null);
-         
+
          refs[i] = msgs[i].createReference();
-                
-         queue.handle(null, refs[i], null); 
+
+         queue.handle(null, refs[i], null);
       }
-      
+
       //Send 50 p messages
       for (int i = 150; i < 200; i++)
       {
          msgs[i] = CoreMessageFactory.createCoreMessage(i, true, null);
-         
+
          refs[i] = msgs[i].createReference();
-                
-         queue.handle(null, refs[i], null); 
+
+         queue.handle(null, refs[i], null);
       }
 
       List refIds = getReferenceIdsOrderedByPageOrd(queue.getChannelID());
       assertEquals(100, refIds.size());
-                                                
+
       assertEquals(100, queue.memoryRefCount());
-      
+
       assertEquals(0, queue.downCacheCount());
-      
-      assertTrue(queue.isPaging());      
-      
+
+      assertTrue(queue.isPaging());
+
       assertEquals(0, queue.getDeliveringCount());
-      
+
       queue.removeAllReferences();
-      
+
       refIds = getReferenceIdsOrderedByPageOrd(queue.getChannelID());
       assertEquals(0, refIds.size());
-      
+
       ;
       List msgIds = getMessageIds();
       assertEquals(0, msgIds.size());
-                                                                  
+
       assertEquals(0, queue.memoryRefCount());
-      
+
       assertEquals(0, queue.downCacheCount());
-      
-      assertFalse(queue.isPaging());      
-      
+
+      assertFalse(queue.isPaging());
+
       assertEquals(0, queue.getDeliveringCount());
-      
+
       assertEquals(0, queue.getMessageCount());
    }
-   
+
    //http://jira.jboss.org/jira/browse/JBMESSAGING-1139
    //If the downcache is not full when we stop the server, we need to test that when we start it again
    //it loads ok (previously it wasn't)
-   
+
    //First test with downcach never flushed
    public void testRecoverableQueueRestartWithDownCache() throws Throwable
    {
       testRecoverableQueueRestartWithDownCache(110);
    }
-   
-   //Then with down cache flushed once 
+
+   //Then with down cache flushed once
    public void testRecoverableQueueRestartWithDownCacheAlreadyFlushed() throws Throwable
    {
       testRecoverableQueueRestartWithDownCache(130);
    }
-   
+
    private void testRecoverableQueueRestartWithDownCache(int num) throws Throwable
    {
       MessagingQueue queue =
          new MessagingQueue(1, "queue1", 1, ms, pm, true, -1, null, 100, 20, 20, false, 300000);
       queue.activate();
-      
+
       Message[] msgs = new Message[num];
-      
+
       MessageReference[] refs = new MessageReference[num];
-            
+
       for (int i = 0; i < num; i++)
       {
          msgs[i] = CoreMessageFactory.createCoreMessage(i, true, null);
-         
+
          refs[i] = msgs[i].createReference();
-                
-         queue.handle(null, refs[i], null); 
+
+         queue.handle(null, refs[i], null);
       }
-      
-            
+
+
       pm.stop();
       tr.stop();
       ms.stop();
-      
+
       pm =
          new JDBCPersistenceManager(sc.getDataSource(), sc.getTransactionManager(),
                   sc.getPersistenceManagerSQLProperties(),
-                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));   
+                  true, true, true, false, 100, !sc.getDatabaseName().equals("oracle"));
       ((JDBCPersistenceManager)pm).injectNodeID(1);
       pm.start();
-      
+
       ms = new SimpleMessageStore();
       ms.start();
-      
-      tr = new TransactionRepository(pm, ms, idm);
 
+      tr = new TransactionRepository(pm, ms, 0);
+
       tr.start();
-         
+
       MessagingQueue queue2 =
          new MessagingQueue(1, "queue1", 1, ms, pm, true, -1, null, 100, 20, 20, false, 300000);
-    
+
       queue2.load();
       queue2.activate();
-                              
-      this.consume(queue2, 0, refs, num);            
+
+      this.consume(queue2, 0, refs, num);
    }
-     
-  
+
+
 }

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/ConnectionTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/ConnectionTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/ConnectionTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -36,8 +36,6 @@
 import org.jboss.jms.client.JBossConnection;
 import org.jboss.jms.client.delegate.ClientConnectionDelegate;
 import org.jboss.jms.client.state.ConnectionState;
-import org.jboss.jms.message.MessageIdGenerator;
-import org.jboss.jms.message.MessageIdGeneratorFactory;
 import org.jboss.jms.tx.ResourceManager;
 import org.jboss.jms.tx.ResourceManagerFactory;
 import org.jboss.logging.Logger;
@@ -165,41 +163,6 @@
       }
    }     
    
-   public void testMessageIDGeneratorsForSameServer() throws Exception
-   {
-      Connection conn1 = cf.createConnection();      
-            
-      ClientConnectionDelegate del1 = (ClientConnectionDelegate)((JBossConnection)conn1).getDelegate();
-      
-      ConnectionState state1 = (ConnectionState)del1.getState();
-      
-      MessageIdGenerator gen1 = state1.getIdGenerator();
-      
-      Connection conn2 = cf.createConnection();      
-      
-      ClientConnectionDelegate del2 = (ClientConnectionDelegate)((JBossConnection)conn2).getDelegate();
-      
-      ConnectionState state2 = (ConnectionState)del2.getState();
-      
-      MessageIdGenerator gen2 = state2.getIdGenerator();
-
-      //Two connections for same server should share the same resource manager
-      
-      assertTrue(gen1 == gen2);
-      
-      assertTrue(MessageIdGeneratorFactory.instance.containsMessageIdGenerator(state2.getServerID()));
-      
-      conn1.close();
-      
-      //Check reference counting
-      assertTrue(MessageIdGeneratorFactory.instance.containsMessageIdGenerator(state2.getServerID()));
-           
-      conn2.close();
-      
-      assertFalse(MessageIdGeneratorFactory.instance.containsMessageIdGenerator(state2.getServerID()));     
-   }
-      
-
    //
    // Note: All tests related to closing a Connection should go to ConnectionClosedTest
    //

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusterConnectionManagerTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusterConnectionManagerTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusterConnectionManagerTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -34,11 +34,11 @@
 import org.jboss.test.messaging.tools.ServerManagement;
 
 /**
- * 
+ *
  * We test every combination of the order of deployment of connection factory, local and remote queue
- * 
+ *
  * and verify message sucking still works
- * 
+ *
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @version <tt>$Revision: $</tt>2 Jul 2007
  *
@@ -62,9 +62,9 @@
    }
 
    // Public ---------------------------------------------------------------------------------------
-   
+
    public void test1() throws Exception
-   {   
+   {
    	deployCFLocal();
    	deployCFRemote();
    	deployLocal();
@@ -73,7 +73,7 @@
    }
 
    public void test2() throws Exception
-   {   
+   {
    	deployCFLocal();
    	deployCFRemote();
    	deployRemote();
@@ -82,7 +82,7 @@
    }
 
    public void test3() throws Exception
-   {   
+   {
    	deployCFLocal();
    	deployLocal();
    	deployCFRemote();
@@ -91,7 +91,7 @@
    }
 
    public void test4() throws Exception
-   {   
+   {
    	deployCFLocal();
    	deployLocal();
    	deployRemote();
@@ -100,7 +100,7 @@
    }
 
    public void test5() throws Exception
-   {   
+   {
    	deployCFLocal();
    	deployRemote();
    	deployCFRemote();
@@ -109,7 +109,7 @@
    }
 
    public void test6() throws Exception
-   {   
+   {
    	deployCFLocal();
    	deployRemote();
    	deployLocal();
@@ -118,7 +118,7 @@
    }
 
    public void test7() throws Exception
-   {   
+   {
    	deployCFRemote();
    	deployCFLocal();
    	deployLocal();
@@ -127,7 +127,7 @@
    }
 
    public void test8() throws Exception
-   {   
+   {
    	deployCFRemote();
    	deployCFLocal();
    	deployRemote();
@@ -136,7 +136,7 @@
    }
 
    public void test9() throws Exception
-   {   
+   {
    	deployCFRemote();
    	deployLocal();
    	deployCFLocal();
@@ -145,7 +145,7 @@
    }
 
    public void test10() throws Exception
-   {   
+   {
    	deployCFRemote();
    	deployLocal();
    	deployRemote();
@@ -154,7 +154,7 @@
    }
 
    public void test11() throws Exception
-   {   
+   {
    	deployCFRemote();
    	deployRemote();
    	deployCFLocal();
@@ -163,7 +163,7 @@
    }
 
    public void test12() throws Exception
-   {   
+   {
    	deployCFRemote();
    	deployRemote();
    	deployLocal();
@@ -172,7 +172,7 @@
    }
 
    public void test13() throws Exception
-   {   
+   {
    	deployLocal();
    	deployCFLocal();
    	deployCFRemote();
@@ -181,7 +181,7 @@
    }
 
    public void test14() throws Exception
-   {   
+   {
    	deployLocal();
    	deployCFLocal();
    	deployRemote();
@@ -190,7 +190,7 @@
    }
 
    public void test15() throws Exception
-   {   
+   {
    	deployLocal();
    	deployCFRemote();
    	deployCFLocal();
@@ -199,7 +199,7 @@
    }
 
    public void test16() throws Exception
-   {   
+   {
    	deployLocal();
    	deployCFRemote();
    	deployRemote();
@@ -208,7 +208,7 @@
    }
 
    public void test17() throws Exception
-   {   
+   {
    	deployLocal();
    	deployRemote();
    	deployCFLocal();
@@ -217,7 +217,7 @@
    }
 
    public void test18() throws Exception
-   {   
+   {
    	deployLocal();
    	deployRemote();
    	deployCFRemote();
@@ -226,7 +226,7 @@
    }
 
    public void test19() throws Exception
-   {   
+   {
    	deployRemote();
    	deployCFLocal();
    	deployCFRemote();
@@ -235,7 +235,7 @@
    }
 
    public void test20() throws Exception
-   {   
+   {
    	deployRemote();
    	deployCFLocal();
    	deployLocal();
@@ -244,7 +244,7 @@
    }
 
    public void test21() throws Exception
-   {   
+   {
    	deployRemote();
    	deployCFRemote();
    	deployCFLocal();
@@ -253,7 +253,7 @@
    }
 
    public void test22() throws Exception
-   {   
+   {
    	deployRemote();
    	deployCFRemote();
    	deployLocal();
@@ -262,7 +262,7 @@
    }
 
    public void test23() throws Exception
-   {   
+   {
    	deployRemote();
    	deployLocal();
    	deployCFLocal();
@@ -271,44 +271,44 @@
    }
 
    public void test24() throws Exception
-   {   
+   {
    	deployRemote();
    	deployLocal();
    	deployCFRemote();
    	deployCFLocal();
    	suck();
    }
-   
+
    // http://jira.jboss.org/jira/browse/JBMESSAGING-1136
    public void testCreateConsumerBeforeRemoteDeployment() throws Exception
-   {      
-      final int NUM_MESSAGES = 20;      
-      
-      deployCFLocal();      
+   {
+      final int NUM_MESSAGES = 20;
+
+      deployCFLocal();
       deployLocal();
-      
+
       //Send some messages
-      
+
       Queue queue0 = (Queue)ic[0].lookup("/queue/suckQueue");
-      
+
       Connection conn0 = null;
-      
+
       try
       {
          conn0 = this.createConnectionOnServer(cf, 0);
-         
+
          assertEquals(0, getServerId(conn0));
-         
+
          //Send some messages on node 0
-         
+
          Session sess0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
-         
+
          MessageProducer prod = sess0.createProducer(queue0);
-         
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = sess0.createTextMessage("message" + i);
-            
+
             prod.send(tm);
          }
       }
@@ -319,22 +319,22 @@
             conn0.close();
          }
       }
-      
+
       log.info("Sent messages");
-      
+
       //Undeploy
       this.undeployAll();
-      
+
       log.info("Undeployed");
-      
+
       deployCFRemote();
       deployRemote();
-      
+
       Queue queue1 = (Queue)ic[1].lookup("/queue/suckQueue");
-            
+
       //Create the consumer - but the messages will be stranded on other node
       //Until we deploy - we do this on another thread
-      
+
       Thread t = new Thread(new Runnable() {
          public void run()
          {
@@ -350,35 +350,35 @@
             }
          }
       });
-      
+
       t.start();
-      
+
       Connection conn1 = null;
-      
+
       try
-      {         
+      {
          //Consume them on node 1
-         
+
          conn1 = this.createConnectionOnServer(cf, 1);
-         
+
          assertEquals(1, getServerId(conn1));
-         
+
          Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
-         
+
          MessageConsumer cons1 = sess1.createConsumer(queue1);
-         
+
          conn1.start();
-         
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)cons1.receive(30000);
-            
+
             assertNotNull(tm);
-            
+
             log.info("Got message " + tm.getText());
-            
+
             assertEquals("message" + i, tm.getText());
-         } 
+         }
       }
       finally
       {
@@ -387,9 +387,9 @@
             conn1.close();
          }
       }
-      
+
       t.join();
-      
+
    }
    // Package protected ----------------------------------------------------------------------------
 
@@ -401,13 +401,6 @@
 
       undeployAll();
    }
-   
-   protected void tearDown() throws Exception
-   {
-   	super.tearDown();
-   	
-   	undeployAll();
-   }
 
    private void undeployAll() throws Exception
    {
@@ -426,22 +419,22 @@
       catch (Exception ignore)
       {
       }
-   	
+
       String cfName =
    		(String)ServerManagement.getServer(1).getAttribute(ServerManagement.getServerPeerObjectName(), "ClusterPullConnectionFactoryName");
 
       log.info("CF name is " + cfName);
-      
-      
-   	//undeploy cf on node 0  	
+
+
+   	//undeploy cf on node 0
       try
       {
       	ServerManagement.getServer(0).undeployConnectionFactory(new ObjectName(cfName));
       }
       catch (Exception ignore)
       {}
-   	
-   	//undeploy cf on node 0  
+
+   	//undeploy cf on node 0
       try
       {
       	ServerManagement.getServer(1).undeployConnectionFactory(new ObjectName(cfName));
@@ -449,88 +442,88 @@
       catch (Exception ignore)
       {}
    }
-   
+
    // Private --------------------------------------------------------------------------------------
-      
+
    private void deployCFRemote() throws Exception
    {
    	String cfName =
    		(String)ServerManagement.getServer(1).getAttribute(ServerManagement.getServerPeerObjectName(), "ClusterPullConnectionFactoryName");
 
-   	//Deploy cf on node 1   	
+   	//Deploy cf on node 1
    	ServerManagement.getServer(1).deployConnectionFactory(cfName, null, 150);
    }
-   
+
    private void deployCFLocal() throws Exception
    {
    	String cfName =
    		(String)ServerManagement.getServer(0).getAttribute(ServerManagement.getServerPeerObjectName(), "ClusterPullConnectionFactoryName");
 
-   	//Deploy cf on node 0  	
+   	//Deploy cf on node 0
    	ServerManagement.getServer(0).deployConnectionFactory(cfName, null, 150);
    }
-   
+
    private void deployLocal() throws Exception
    {
    	 ServerManagement.deployQueue("suckQueue", 0);
    }
-   
+
    private void deployRemote() throws Exception
    {
-   	 ServerManagement.deployQueue("suckQueue", 1);   	 
+   	 ServerManagement.deployQueue("suckQueue", 1);
    }
-   
+
    private void suck() throws Exception
-   {      
+   {
       Queue queue0 = (Queue)ic[0].lookup("/queue/suckQueue");
-      
+
       Queue queue1 = (Queue)ic[1].lookup("/queue/suckQueue");
-      
+
       Connection conn0 = null;
-      
+
       Connection conn1 = null;
-      
+
       try
       {
       	conn0 = this.createConnectionOnServer(cf, 0);
-      	
+
       	assertEquals(0, getServerId(conn0));
-      	
+
       	//Send some messages on node 0
-      	
+
       	final int NUM_MESSAGES = 20;
-      	
+
       	Session sess0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
-      	
+
       	MessageProducer prod = sess0.createProducer(queue0);
-      	
+
       	for (int i = 0; i < NUM_MESSAGES; i++)
       	{
       		TextMessage tm = sess0.createTextMessage("message" + i);
-      		
+
       		prod.send(tm);
       	}
-      	
+
       	//Consume them on node 1
-      	
+
       	conn1 = this.createConnectionOnServer(cf, 1);
-      	
+
       	assertEquals(1, getServerId(conn1));
-      	
+
       	Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
-      	
+
       	MessageConsumer cons1 = sess1.createConsumer(queue1);
-      	
+
       	conn1.start();
-      	
+
       	for (int i = 0; i < NUM_MESSAGES; i++)
       	{
       		TextMessage tm = (TextMessage)cons1.receive(5000);
-      		
+
       		assertNotNull(tm);
-      		
+
       		assertEquals("message" + i, tm.getText());
-      	} 
+      	}
       }
       finally
       {
@@ -543,7 +536,7 @@
       		conn1.close();
       	}
       }
-      
+
    }
 
 

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusteringTestBase.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusteringTestBase.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/ClusteringTestBase.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -58,30 +58,30 @@
    // Static ---------------------------------------------------------------------------------------
 
    // Attributes -----------------------------------------------------------------------------------
-  
+
    protected String config = "all+http";
 
    protected static InitialContext[] ic;
    protected static Queue queue[];
    protected static Topic topic[];
-   
+
    // No need to have multiple connection factories since a clustered connection factory will create
    // connections in a round robin fashion on different servers.
 
    protected static JBossConnectionFactory cf;
-   
+
    protected int nodeCount = 4;
    protected ServiceAttributeOverrides overrides;
-   
+
    protected static ServiceAttributeOverrides currentOverrides;
-   
+
    // Constructors ---------------------------------------------------------------------------------
 
    public ClusteringTestBase(String name)
    {
       super(name);
    }
-   
+
    // Public ---------------------------------------------------------------------------------------
 
    // Package protected ----------------------------------------------------------------------------
@@ -91,140 +91,132 @@
    protected int getFailoverNodeForNode(JBossConnectionFactory factory, int nodeID)
    {
    	Integer l = (Integer)((ClientClusteredConnectionFactoryDelegate)(factory.getDelegate())).getFailoverMap().get(new Integer(nodeID));
-   	
+
       return l.intValue();
    }
-   
+
    protected int getNodeThatFailsOverOnto(JBossConnectionFactory factory, int nodeID)
    {
    	Map map = ((ClientClusteredConnectionFactoryDelegate)(factory.getDelegate())).getFailoverMap();
-   	
+
    	Iterator iter = map.entrySet().iterator();
-   	
+
    	while (iter.hasNext())
    	{
    		Map.Entry entry = (Map.Entry)iter.next();
-   		
+
    		int val = ((Integer)entry.getValue()).intValue();
    		int key = ((Integer)entry.getKey()).intValue();
-   		
+
    		if (val == nodeID)
    		{
    			return key;
    		}
    	}
-   	
+
    	throw new IllegalStateException("Cannot find node that fails over onto " + nodeID);
    }
-   
+
    protected void setUp() throws Exception
    {
-      super.setUp();            
-             
-      log.info("node count is " + nodeCount);
-      
-      boolean changed = false;
-      
-      if (ic != null && ic.length < nodeCount)
+      super.setUp();
+
+      ic = new InitialContext[nodeCount];
+
+      queue = new Queue[nodeCount];
+
+      topic = new Topic[nodeCount];
+
+      for (int i = 0; i < nodeCount; i++)
       {
-      	log.info("Node count has increased from " + ic.length + " to " + nodeCount);
-      	//Node count has increased
-      	InitialContext[] oldIc = ic;
-      	ic = new InitialContext[nodeCount];
-      	Queue[] oldQueue = queue;
-      	queue = new Queue[nodeCount];
-      	Topic[] oldTopic = topic;
-      	topic = new Topic[nodeCount];
-      	for (int i = 0; i < oldIc.length; i++)
-      	{
-      		ic[i] = oldIc[i];
-      		queue[i] = oldQueue[i];
-      		topic[i] = oldTopic[i];
-      	}
+         startDefaultServer(i, overrides, i == 0);
+
+         ic[i] = new InitialContext(ServerManagement.getJNDIEnvironment(i));
+
+         queue[i] = (Queue)ic[i].lookup("queue/testDistributedQueue");
+
+         topic[i] = (Topic)ic[i].lookup("topic/testDistributedTopic");
       }
-      else if (ic != null && ic.length > nodeCount)
+
+      cf = (JBossConnectionFactory)ic[0].lookup("/ClusteredConnectionFactory");
+   }
+
+   protected void tearDown() throws Exception
+   {
+      super.tearDown();
+
+      log.info("************* TEARING DOWN");
+
+      String failString = null;
+
+      try
       {
-      	log.info("Node count has decreased from " + ic.length + " to " + nodeCount);
-      	//Node count has decreased
-      	InitialContext[] oldIc = ic;
-      	ic = new InitialContext[nodeCount];
-      	Queue[] oldQueue = queue;
-      	queue = new Queue[nodeCount];
-      	Topic[] oldTopic = topic;
-      	topic = new Topic[nodeCount];
-      	for (int i = 0; i < nodeCount; i++)
-      	{
-      		ic[i] = oldIc[i];
-      		queue[i] = oldQueue[i];
-      		topic[i] = oldTopic[i];
-      	}
-      	
-      	for (int i = nodeCount; i < oldIc.length; i++)
-      	{
-      		log.info("*** killing server");
-      		ServerManagement.kill(i);
-      	}
-      	
-      	changed = true;
-      }
-      
-      if (overridesChanged(overrides, currentOverrides))
-      {
-      	log.info("Overrides have changed so stopping and restarting all servers");
-      	currentOverrides = overrides;
-      	
-      	for (int i = 0; i < nodeCount; i++)
+
+         if (ResourceManagerFactory.instance.size() != 0)
          {
-      		ServerManagement.stop(i);
+            ResourceManagerFactory.instance.dump();
+
+            failString  = "Connection(s) have been left open";
          }
-      	
-      	changed = true;
-      }
-      
-      for (int i = 0; i < nodeCount; i++)
-      {
-	      if (!ServerManagement.isStarted(i))
-	      {
-	      	log.info("Server " + i + " is not started - starting it");
 
-            startDefaultServer(i, overrides, ic == null);
-	         
-            if (ic == null)
+         for (int i = 0; i < nodeCount; i++)
+         {
+            if (ServerManagement.isStarted(i))
             {
-               ic = new InitialContext[nodeCount];
-               queue = new Queue[nodeCount];
-               topic = new Topic[nodeCount];
-            }
+               if (!isEmpty(queue[i], i))
+               {
+                  failString = "Queue " + queue[i].getQueueName() + " is not empty";
 
-	         ic[i] = new InitialContext(ServerManagement.getJNDIEnvironment(i));
-	          
-	         queue[i] = (Queue)ic[i].lookup("queue/testDistributedQueue");
-	         topic[i] = (Topic)ic[i].lookup("topic/testDistributedTopic");
-	         
-	         changed = true;
+                  break;
+               }
 
-	      }
-	      
-	      checkEmpty(queue[i], i);
-	      
-	      // Check no subscriptions left lying around
-	            
-	      checkNoSubscriptions(topic[i], i);	
-	      
-	      ServerManagement.getServer(i).resetAllSuckers();
+               // Check no subscriptions left lying around
+
+               Integer messageCount = getNoSubscriptions(topic[i], i);
+
+               if (messageCount.intValue() != 0)
+               {
+                  failString = "Topic " + topic[i].getTopicName() + " has subscriptions";
+
+                  break;
+               }
+            }
+         }
       }
-      
-      if (changed)
+      catch (Throwable ignore)
       {
-      	//Wait a little while before starting the test to ensure the new view propagates
-      	//otherwise the view change might hit after the test has started
-      	Thread.sleep(10000);
       }
-      
-      if (ic != null)
+
+      for (int i = 9 ; i >= 0; i--)
       {
-      	cf = (JBossConnectionFactory)ic[0].lookup("/ClusteredConnectionFactory");
+         try
+         {
+            ic[i].close();
+         }
+         catch (Throwable ignore)
+         {
+         }
+
+         log.info("********** TRYING TO KILL SERVER " + i);
+         try
+         {
+            ServerManagement.kill(i);
+         }
+         catch (Throwable ignore)
+         {
+         }
       }
+
+      ic = null;
+
+      queue = null;
+
+      topic = null;
+
+      if (failString != null)
+      {
+         fail(failString);
+      }
    }
 
    protected void startDefaultServer(int serverNumber, ServiceAttributeOverrides attributes, boolean cleanDatabase)
@@ -237,55 +229,6 @@
       ServerManagement.deployTopic("testDistributedTopic", serverNumber);
    }
 
-   private boolean overridesChanged(ServiceAttributeOverrides sao1, ServiceAttributeOverrides sao2)
-   {
-   	Map map1 = sao1 == null ? null : sao1.getMap();
-   	
-   	Map map2 = sao2 == null ? null : sao2.getMap();
-   	
-   	if (map1 == null && map2 == null)
-   	{
-   		return false;
-   	}
-   	if ((map1 == null && map2 != null) || (map2 == null && map1 != null))
-   	{
-   		return true;
-   	}
-   	
-   	if (map1.size() != map2.size())
-   	{
-   		return true;
-   	}
-   	
-   	Iterator iter = map1.entrySet().iterator();
-   	while (iter.hasNext())
-   	{
-   		Map.Entry entry = (Map.Entry)iter.next();
-   		Object otherVal = map2.get(entry.getKey());
-   		if (otherVal == null)
-   		{
-   			return true;
-   		}
-   		if (!otherVal.equals(entry.getValue()))
-   		{
-   			return true;
-   		}
-   	}   	
-   	return false;
-   }
-   
-   protected void tearDown() throws Exception
-   {
-      super.tearDown();
-                 
-      if (ResourceManagerFactory.instance.size() != 0)
-      {
-      	ResourceManagerFactory.instance.dump();
-      	
-      	fail("Connection(s) have been left open");
-      }
-   }
-
    protected String getLocatorURL(Connection conn)
    {
       return getConnectionState(conn).getRemotingConnection().
@@ -303,7 +246,7 @@
       return (ConnectionState) (((DelegateSupport) ((JBossConnection) conn).
          getDelegate()).getState());
    }
-  
+
    protected void waitForFailoverComplete(int serverID, Connection conn1)
       throws Exception
    {
@@ -394,7 +337,7 @@
    // Private --------------------------------------------------------------------------------------
 
    // Inner classes --------------------------------------------------------------------------------
-   
+
    protected class SimpleFailoverListener implements FailoverListener
    {
       private LinkedQueue buffer;

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DisableLoadBalancingAndFailoverTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DisableLoadBalancingAndFailoverTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DisableLoadBalancingAndFailoverTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -35,15 +35,15 @@
    // Static ---------------------------------------------------------------------------------------
 
    // Attributes -----------------------------------------------------------------------------------
-	
+
 	protected ConnectionFactory nonClusteredCF1;
-	
+
 	protected ConnectionFactory nonClusteredCF2;
-	
+
 	protected ConnectionFactory lbCF1;
-	
+
 	protected ConnectionFactory lbCF2;
-	
+
 	protected ConnectionFactory foCF;
 
    // Constructors ---------------------------------------------------------------------------------
@@ -54,83 +54,83 @@
    }
 
    // Public ---------------------------------------------------------------------------------------
-   
+
    public void testNoFailoverNoLoadBalancing1() throws Exception
    {
    	//If no load balancing then always on local node
    	this.noFailover(nonClusteredCF1);
    }
-   
+
    public void testNoFailoverNoLoadBalancing2() throws Exception
    {
-   	this.noFailoverWithExceptionListener(nonClusteredCF1, nonClusteredCF2);   	
+   	this.noFailoverWithExceptionListener(nonClusteredCF1, nonClusteredCF2);
    }
-   	
+
    public void testNoFailoverNoLoadBalancing3() throws Exception
    {
    	this.noLoadBalancing(nonClusteredCF1);
    }
-   
+
    public void testNoFailoverLoadBalancing1() throws Exception
    {
    	this.noFailover(lbCF1);
    }
-   
+
    public void testNoFailoverLoadBalancing2() throws Exception
    {
-   	this.noFailoverWithExceptionListener(lbCF1, lbCF2);   	
+   	this.noFailoverWithExceptionListener(lbCF1, lbCF2);
    }
-   	
+
    public void testNoFailoverLoadBalancing3() throws Exception
    {
    	this.loadBalancing(lbCF1);
    }
-   
+
    public void testFailoverNoLoadBalancing1() throws Exception
    {
    	this.failover(foCF);
    }
-   	
+
    public void testFailoverNoLoadBalancing2() throws Exception
    {
    	this.noLoadBalancing(foCF);
    }
-   
+
    // Protected -------------------------------------------------------------------------------------
 
    protected void noLoadBalancing(ConnectionFactory theCF) throws Exception
    {
-   	Connection conn = null;      
+   	Connection conn = null;
 
       try
       {
       	conn = theCF.createConnection();
-      	
+
       	int serverID = getServerId(conn);
-      	
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
+
          assertEquals(serverID, getServerId(conn));
-         
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
+
          assertEquals(serverID, getServerId(conn));
-         
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
+
          assertEquals(serverID, getServerId(conn));
-         
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
-         assertEquals(serverID, getServerId(conn));                
+
+         assertEquals(serverID, getServerId(conn));
       }
       finally
       {
@@ -140,49 +140,49 @@
          }
       }
    }
-   
+
    protected void loadBalancing(ConnectionFactory theCF) throws Exception
    {
-   	Connection conn = null;      
+   	Connection conn = null;
 
       try
       {
       	log.info("In test **************");
-      	      	
+
       	conn = theCF.createConnection();
-      	
+
       	int serverID = getServerId(conn);
       	log.info("server id is " + serverID);
-      	
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
+
          serverID = ++serverID % 3;
          assertEquals(serverID, getServerId(conn));
-         
+
       	log.info("server id is " + serverID);
-         
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
+
          serverID = ++serverID % 3;
          assertEquals(serverID, getServerId(conn));
       	log.info("server id is " + serverID);
-         
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
+
          serverID = ++serverID % 3;
          assertEquals(serverID, getServerId(conn));
       	log.info("server id is " + serverID);
-         
+
          conn.close();
-         
+
          conn = theCF.createConnection();
-      	
+
          serverID = ++serverID % 3;
          assertEquals(serverID, getServerId(conn));
       	log.info("server id is " + serverID);
@@ -195,39 +195,39 @@
          }
       }
    }
-   
-   
+
+
    protected void noFailover(ConnectionFactory theCF) throws Exception
    {
-      Connection conn = null;      
+      Connection conn = null;
 
       try
       {
          conn = createConnectionOnServer(theCF, 1);
-      	
+
          assertEquals(1, getServerId(conn));
-         
+
          Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-         
+
          MessageProducer prod = sess.createProducer(queue[1]);
-         
+
          conn.start();
-         
+
          TextMessage tm = sess.createTextMessage("uhasduihd");
-         
+
          //Now kill server 1
-         
+
          log.info("KILLING SERVER 1");
          ServerManagement.kill(1);
          log.info("KILLED SERVER 1");
-         
+
          Thread.sleep(5000);
-         
+
          long start = System.currentTimeMillis();
          try
          {
          	prod.send(tm);
-         		
+
          	// We shouldn't get here
             fail();
          }
@@ -235,10 +235,10 @@
          {
          	//OK - this is what we should get
          	long end = System.currentTimeMillis();
-         	
+
          	//Make sure it doesn't take too long
          	assertTrue((end - start) <= 100);
-         }                 
+         }
       }
       finally
       {
@@ -248,57 +248,57 @@
          }
       }
    }
-         
+
    protected void noFailoverWithExceptionListener(ConnectionFactory theCF1, ConnectionFactory theCF2) throws Exception
    {
-      Connection conn = null;      
+      Connection conn = null;
 
       try
       {
          conn = createConnectionOnServer(theCF1, 1);
-      	
+
       	MyListener listener = new MyListener();
-      	
+
       	conn.setExceptionListener(listener);
-      	
+
          assertEquals(1, getServerId(conn));
-         
+
          //Now kill server 1
-         
+
          log.info("KILLING SERVER 1");
          ServerManagement.kill(1);
          log.info("KILLED SERVER 1");
-         
+
          JMSException e = listener.waitForException(20000);
-         
+
          assertNotNull(e);
-         
+
          assertTrue(e.getMessage().equals("Failure on underlying remoting connection"));
-         
+
          //Now try and recreate connection on different node
-         
+
          conn.close();
-         
+
          conn = theCF2.createConnection();
-         
+
          Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
          MessageProducer prod = sess.createProducer(queue[2]);
-         
+
          MessageConsumer cons = sess.createConsumer(queue[2]);
 
          conn.start();
 
          TextMessage tm = sess.createTextMessage("uhasduihd");
-         
+
          prod.send(tm);
-         
+
          TextMessage rm = (TextMessage)cons.receive(1000);
-         
+
          assertNotNull(rm);
-         
+
          assertEquals(tm.getText(), rm.getText());
-           
+
       }
       finally
       {
@@ -308,37 +308,37 @@
          }
       }
    }
-   
+
    protected void failover(ConnectionFactory theCF) throws Exception
    {
-      Connection conn = null;      
+      Connection conn = null;
 
       try
       {
          conn = createConnectionOnServer(theCF, 1);
-      	
+
       	// register a failover listener
          SimpleFailoverListener failoverListener = new SimpleFailoverListener();
          ((JBossConnection)conn).registerFailoverListener(failoverListener);
-      	
+
          assertEquals(1, getServerId(conn));
-         
+
          Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-         
+
          MessageProducer prod = sess.createProducer(queue[1]);
-         
+
          MessageConsumer cons = sess.createConsumer(queue[1]);
-         
+
          conn.start();
-         
+
          TextMessage tm = sess.createTextMessage("uhasduihd");
-         
+
          //Now kill server 1
-         
+
          log.info("KILLING SERVER 1");
          ServerManagement.kill(1);
          log.info("KILLED SERVER 1");
-         
+
          // wait for the client-side failover to complete
 
          while (true)
@@ -356,14 +356,14 @@
 
          // failover complete
          log.info("failover completed");
-         
+
          prod.send(tm);
-         
+
          TextMessage rm = (TextMessage)cons.receive(2000);
-         
+
          assertNotNull(rm);
-         
-         assertEquals(tm.getText(), rm.getText());         		                
+
+         assertEquals(tm.getText(), rm.getText());
       }
       finally
       {
@@ -373,41 +373,41 @@
          }
       }
    }
-   
+
    protected void setUp() throws Exception
    {
       nodeCount = 3;
 
       super.setUp();
-      
+
       nonClusteredCF1 = (ConnectionFactory)ic[1].lookup("/ConnectionFactory");
-      
+
       nonClusteredCF2 = (ConnectionFactory)ic[2].lookup("/ConnectionFactory");
-      
+
       //Deploy a connection factory with load balancing but no failover on node0
       ServerManagement.getServer(0).deployConnectionFactory("org.jboss.messaging:service=LBConnectionFactory",
       		                                   new String[] { "/LBConnectionFactory" }, false, true);
-      
+
       //Deploy a connection factory with load balancing but no failover on node1
       ServerManagement.getServer(1).deployConnectionFactory("org.jboss.messaging:service=LBConnectionFactory",
       		                                   new String[] { "/LBConnectionFactory" }, false, true);
-      
+
       //Deploy a connection factory with load balancing but no failover on node2
       ServerManagement.getServer(2).deployConnectionFactory("org.jboss.messaging:service=LBConnectionFactory",
       		                                   new String[] { "/LBConnectionFactory" }, false, true);
-      
-      this.lbCF1 = (ConnectionFactory)ic[1].lookup("/LBConnectionFactory");      
-      
+
+      this.lbCF1 = (ConnectionFactory)ic[1].lookup("/LBConnectionFactory");
+
       this.lbCF2 = (ConnectionFactory)ic[2].lookup("/LBConnectionFactory");
-      
+
       //Deploy a connection factory with failover but no load balancing on node 0
       ServerManagement.getServer(0).deployConnectionFactory("org.jboss.messaging:service=FOConnectionFactory",
             new String[] { "/FOConnectionFactory" }, true, false);
-      
+
       //Deploy a connection factory with failover but no load balancing on node 1
       ServerManagement.getServer(1).deployConnectionFactory("org.jboss.messaging:service=FOConnectionFactory",
             new String[] { "/FOConnectionFactory" }, true, false);
-      
+
       //Deploy a connection factory with failover but no load balancing on node 2
       ServerManagement.getServer(2).deployConnectionFactory("org.jboss.messaging:service=FOConnectionFactory",
             new String[] { "/FOConnectionFactory" }, true, false);
@@ -417,84 +417,30 @@
       log.debug("setup done");
    }
 
-   protected void tearDown() throws Exception
-   {
-   	try
-   	{
-   		ServerManagement.getServer(0).undeployConnectionFactory(new ObjectName("org.jboss.messaging:service=LBConnectionFactory"));
-   	}
-   	catch (Exception ignore)
-   	{   		
-   	}
-      
-   	try
-   	{
-         ServerManagement.getServer(1).undeployConnectionFactory(new ObjectName("org.jboss.messaging:service=LBConnectionFactory"));
-   	}
-   	catch (Exception ignore)
-   	{   		
-   	}
-   	
-   	try
-   	{
-         ServerManagement.getServer(2).undeployConnectionFactory(new ObjectName("org.jboss.messaging:service=LBConnectionFactory"));
-   	}
-   	catch (Exception ignore)
-   	{   		
-   	}
-   	
-   	try
-   	{
-   		ServerManagement.getServer(0).undeployConnectionFactory(new ObjectName("org.jboss.messaging:service=FOConnectionFactory"));
-   	}
-   	catch (Exception ignore)
-   	{   		
-   	}
-      
-   	try
-   	{
-         ServerManagement.getServer(1).undeployConnectionFactory(new ObjectName("org.jboss.messaging:service=FOConnectionFactory"));
-   	}
-   	catch (Exception ignore)
-   	{   		
-   	}
-   	
-   	try
-   	{
-         ServerManagement.getServer(2).undeployConnectionFactory(new ObjectName("org.jboss.messaging:service=FOConnectionFactory"));
-   	}
-   	catch (Exception ignore)
-   	{   		
-   	}
-   	
-      super.tearDown();      
-   }
 
-
-
    // Inner classes --------------------------------------------------------------------------------
-   
+
 	private class MyListener implements ExceptionListener
 	{
 		private JMSException e;
-		
+
 		Latch l = new Latch();
 
 		public void onException(JMSException e)
 		{
 			this.e = e;
-			
+
 			l.release();
 		}
-		
+
 		JMSException waitForException(long timeout) throws Exception
 		{
 			l.attempt(timeout);
-			
+
 			return e;
 		}
-		
-	}	
-   
-   
+
+	}
+
+
 }

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DistributedTopicTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DistributedTopicTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/DistributedTopicTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -39,9 +39,9 @@
 
 
 /**
- * 
+ *
  * A DistributedTopicTest
- * 
+ *
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @version <tt>$Revision$</tt>
  *
@@ -75,7 +75,7 @@
    {
       clusteredTopicNonDurable(true);
    }
-   
+
    public void testClusteredTopicNonDurableNoLocalNonPersistent() throws Exception
    {
       clusteredTopicNoLocal(false);
@@ -125,7 +125,7 @@
    {
       clusteredTopicSharedDurableNoLocalSub(true);
    }
-   
+
    public void testNonClusteredTopicNonDurableNonPersistent() throws Exception
    {
    	nonClusteredTopicNonDurable(false);
@@ -135,7 +135,7 @@
    {
    	nonClusteredTopicNonDurable(true);
    }
-   
+
    public void testNonClusteredTopicDurableNonPersistent() throws Exception
    {
    	nonClusteredTopicDurable(false);
@@ -240,7 +240,7 @@
          }
 
          checkNoSubscriptions(topic[0]);
-         
+
       }
       finally
       {
@@ -250,14 +250,14 @@
       }
    }
 
-   
+
    // http://jira.jboss.org/jira/browse/JBMESSAGING-1216
    public void testDestinationTypeOnMessage() throws Exception
    {
       Connection connection0 = null;
       Connection connection1 = null;
       Connection connection2 = null;
-      
+
       Session session0 = null;
       Session session1 = null;
       Session session2 = null;
@@ -288,8 +288,8 @@
 
          MessageConsumer subscriber1 = session1.createDurableSubscriber(
                topic[0], "sub2");
-         
-         
+
+
          TestListener messageListener1 = new TestListener();
          subscriber1.setMessageListener(messageListener1);
 
@@ -312,7 +312,7 @@
 
          message = (TextMessage) m0;
          assertTrue(m0.getJMSDestination() instanceof Topic);
-         
+
          Topic topicDest = (Topic)m0.getJMSDestination();
          assertEquals(topic[0].getTopicName(), topicDest.getTopicName());
          assertEquals("Hello!", message.getText());
@@ -326,22 +326,22 @@
          assertEquals(topic[1].getTopicName(), topicDest.getTopicName());
 
          assertEquals("Hello!", message.getText());
-         
-         
+
+
          Message m2 = messageListener2.waitForMessage();
          message = (TextMessage) m2;
          Destination d2 = m2.getJMSDestination();
          assertTrue(d2 instanceof Topic);
          assertEquals(topic[0].getTopicName(),((Topic)d2).getTopicName());
-         
+
          session0.commit();
          session1.commit();
          session2.commit();
-         
+
          subscriber0.close();
          subscriber1.close();
          subscriber2.close();
-         
+
          session0.unsubscribe("sub");
          session1.unsubscribe("sub2");
          session2.unsubscribe("sub3");
@@ -384,7 +384,7 @@
 
       }
    }
-   
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
@@ -396,41 +396,12 @@
       super.setUp();
 
       ServerManagement.deployTopic("nonClusteredTopic", "nonClusteredTopic", 300000, 3000, 3000, 0, false);
-      
+
       ServerManagement.deployTopic("nonClusteredTopic", "nonClusteredTopic", 300000, 3000, 3000, 1, false);
-      
+
       ServerManagement.deployTopic("nonClusteredTopic", "nonClusteredTopic", 300000, 3000, 3000, 2, false);
    }
 
-   protected void tearDown() throws Exception
-   {
-      super.tearDown();
-      
-      try
-      {
-      	ServerManagement.undeployTopic("nonClusteredTopic",  0);
-      }
-      catch (Exception ignore)
-      {      	
-      }
-      
-      try
-      {
-      	ServerManagement.undeployTopic("nonClusteredTopic",  1);
-      }
-      catch (Exception ignore)
-      {      	
-      }
-      
-      try
-      {
-      	ServerManagement.undeployTopic("nonClusteredTopic",  2);
-	   }
-	   catch (Exception ignore)
-	   {      	
-	   }
-   }
-
    // Private -------------------------------------------------------
 
    /*
@@ -449,7 +420,7 @@
          conn0 = this.createConnectionOnServer(cf, 0);
          conn1 = this.createConnectionOnServer(cf, 1);
          conn2 = this.createConnectionOnServer(cf, 2);
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn0, conn1, conn2});
 
          Session sess0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -486,12 +457,12 @@
             TextMessage tm = (TextMessage)cons0.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          Message msg = cons0.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -499,13 +470,13 @@
             TextMessage tm = (TextMessage)cons1.receive(3000);
 
             assertNotNull(tm);
-            
- 
+
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons1.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -513,12 +484,12 @@
             TextMessage tm = (TextMessage)cons2.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons2.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -526,12 +497,12 @@
             TextMessage tm = (TextMessage)cons3.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons3.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -539,12 +510,12 @@
             TextMessage tm = (TextMessage)cons4.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons4.receive(3000);
-         
+
          assertNull(msg);
       }
       finally
@@ -565,8 +536,8 @@
          }
       }
    }
-   
-   
+
+
    /* Test with noLocal set to true */
    private void clusteredTopicNoLocal(boolean persistent) throws Exception
    {
@@ -580,7 +551,7 @@
          conn0 = this.createConnectionOnServer(cf, 0);
          conn1 = this.createConnectionOnServer(cf, 1);
          conn2 = this.createConnectionOnServer(cf, 2);
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn0, conn1, conn2});
 
          Session sess0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -589,7 +560,7 @@
 
          MessageConsumer cons0 = sess0.createConsumer(topic[0], null, true);
          MessageConsumer cons1 = sess1.createConsumer(topic[1], null, true);
-         MessageConsumer cons2 = sess2.createConsumer(topic[2], null, true);        
+         MessageConsumer cons2 = sess2.createConsumer(topic[2], null, true);
 
          conn0.start();
          conn1.start();
@@ -611,7 +582,7 @@
          }
 
          Message msg = cons0.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -619,13 +590,13 @@
             TextMessage tm = (TextMessage)cons1.receive(3000);
 
             assertNotNull(tm);
-            
- 
+
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons1.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -633,13 +604,13 @@
             TextMessage tm = (TextMessage)cons2.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons2.receive(3000);
-         
-         assertNull(msg);         
+
+         assertNull(msg);
       }
       finally
       {
@@ -678,7 +649,7 @@
       	conn0 = this.createConnectionOnServer(cf, 0);
          conn1 = this.createConnectionOnServer(cf, 1);
          conn2 = this.createConnectionOnServer(cf, 2);
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn0, conn1, conn2});
 
          Session sess0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -728,9 +699,9 @@
 
             assertEquals("message" + i, tm.getText());
          }
-         
+
          Message msg = cons0.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -741,9 +712,9 @@
 
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons1.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -754,9 +725,9 @@
 
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = cons2.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -772,9 +743,9 @@
                assertEquals("message" + i, tm.getText());
             }
          }
-         
+
          msg = cons3.receive(3000);
-         
+
          assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
@@ -790,9 +761,9 @@
                assertEquals("message" + i, tm.getText());
             }
          }
-         
+
          msg = cons4.receive(3000);
-         
+
          assertNull(msg);
       }
       finally
@@ -826,7 +797,7 @@
       	conn0 = this.createConnectionOnServer(cf, 0);
          conn1 = this.createConnectionOnServer(cf, 1);
          conn2 = this.createConnectionOnServer(cf, 2);
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn0, conn1, conn2});
 
          conn0.setClientID("wib1");
@@ -862,23 +833,23 @@
             sess1.unsubscribe("epsilon");
          }
          catch (Exception ignore) {}
-         
+
          MessageConsumer alpha = sess0.createDurableSubscriber(topic[0], "alpha");
-         
+
          MessageConsumer beta = sess1.createDurableSubscriber(topic[1], "beta");
-         
+
          MessageConsumer gamma = sess2.createDurableSubscriber(topic[2], "gamma");
-         
+
          MessageConsumer delta = sess0.createDurableSubscriber(topic[0], "delta");
-         
+
          MessageConsumer epsilon = sess1.createDurableSubscriber(topic[1], "epsilon");
-         
+
          Thread.sleep(2000);
-         
+
          conn0.start();
          conn1.start();
          conn2.start();
-         
+
          // Send at node 0 - and make sure the messages are consumable from all the durable subs
 
          MessageProducer prod = sess0.createProducer(topic[0]);
@@ -891,16 +862,16 @@
          {
             prod.send(sess0.createTextMessage("message" + i));
          }
-         
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)alpha.receive(3000);
             assertNotNull(tm);
             assertEquals("message" + i, tm.getText());
          }
-         
+
          Message msg = alpha.receive(3000);
-         assertNull(msg);         
+         assertNull(msg);
 
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
@@ -908,7 +879,7 @@
             assertNotNull(tm);
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = beta.receive(3000);
          assertNull(msg);
 
@@ -918,7 +889,7 @@
             assertNotNull(tm);
             assertEquals("message" + i, tm.getText());
          }
-         
+
          msg = gamma.receive(3000);
          assertNull(msg);
 
@@ -938,21 +909,21 @@
             assertNotNull(tm);
             assertEquals("message" + i, tm.getText());
          }
- 
+
          msg = epsilon.receive(3000);
          assertNull(msg);
-                 
+
          //close beta
          beta.close();
 
          // Create another beta - this one node 0
          MessageConsumer beta0 = sess0.createDurableSubscriber(topic[0], "beta");
-         
+
          //And one node node1
          MessageConsumer beta1 = sess1.createDurableSubscriber(topic[1], "beta");
-         
+
          //Now send some more messages at node 2
-         
+
          MessageProducer prod2 = sess2.createProducer(topic[2]);
 
          prod2.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
@@ -961,11 +932,11 @@
          {
             prod2.send(sess1.createTextMessage("message2-" + i));
          }
-         
+
          //They should be round - robined - but we don't know which one will get them first
 
          int offset = 0;
-         
+
          for (int i = 0; i < NUM_MESSAGES / 2; i++)
          {
             TextMessage tm = (TextMessage)beta0.receive(3000);
@@ -975,13 +946,13 @@
             {
             	offset = 1;
             }
-            
+
             assertEquals("message2-" + (i * 2 + offset), tm.getText());
          }
-         
+
          msg = beta0.receive(3000);
          assertNull(msg);
-         
+
          if (offset == 1)
          {
          	offset = 0;
@@ -989,41 +960,41 @@
          else
          {
          	offset = 1;
-         }      
-         
+         }
+
          for (int i = 0; i < NUM_MESSAGES / 2; i++)
          {
             TextMessage tm = (TextMessage)beta1.receive(3000);
             assertNotNull(tm);
             assertEquals("message2-" + (i * 2 + offset), tm.getText());
          }
-         
+
          msg = beta1.receive(3000);
          assertNull(msg);
-         
+
          //Send some more at node 0
-         
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             prod.send(sess1.createTextMessage("message3-" + i));
          }
-         
+
          //This should go straight to the local queue
-         
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)beta0.receive(3000);
             assertNotNull(tm);
             assertEquals("message3-" + i, tm.getText());
          }
-         
+
          msg = beta0.receive(3000);
          assertNull(msg);
-         
+
          //So now we have a beta on node 1 and a beta on node 0 and the messages are on node2
-         
+
          beta0.close();
-         beta1.close();	
+         beta1.close();
 
          alpha.close();
          beta.close();
@@ -1056,8 +1027,8 @@
          }
       }
    }
-   
-  
+
+
    /*
     * Create shared durable subs on multiple nodes, the local instance should always get the message
     */
@@ -1074,7 +1045,7 @@
       	conn1 = this.createConnectionOnServer(cf, 0);
          conn2 = this.createConnectionOnServer(cf, 1);
          conn3 = this.createConnectionOnServer(cf, 2);
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn1, conn2, conn3});
          conn1.setClientID("wib1");
          conn2.setClientID("wib1");
@@ -1204,42 +1175,42 @@
 
          cons1.close();
          cons2.close();
-         
+
          //Try and unsubscribe now - this should fail since there is still a consumer open on another node
-         
+
          try
          {
          	sess1.unsubscribe("sub");
-         	
+
          	fail("Did not throw IllegalStateException");
          }
          catch (javax.jms.IllegalStateException e)
          {
-         	//Ok 
+         	//Ok
          }
-         
+
          cons3.close();
-         
+
          // Need to unsubscribe on any node that the durable sub was created on
 
          sess1.unsubscribe("sub");
-         
+
          //Next unsubscribe should fail since it's already unsubscribed from a different node of the cluster
          try
          {
          	sess2.unsubscribe("sub");
-         	
+
          	fail("Did not throw InvalidDestinationException");
          }
          catch (InvalidDestinationException e)
          {
          	//Ok
          }
-         
+
          try
          {
          	sess3.unsubscribe("sub");
-         	
+
          	fail("Did not throw InvalidDestinationException");
          }
          catch (InvalidDestinationException e)
@@ -1286,9 +1257,9 @@
       	conn1 = this.createConnectionOnServer(cf, 0);
          conn2 = this.createConnectionOnServer(cf, 1);
          conn3 = this.createConnectionOnServer(cf, 2);
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn1, conn2, conn3});
-         
+
          conn2.setClientID("wib1");
          conn3.setClientID("wib1");
 
@@ -1324,26 +1295,26 @@
 
             prod.send(tm);
          }
-         
-         
+
+
          int offset = 0;
-         
+
          for (int i = 0; i < NUM_MESSAGES / 2; i++)
          {
             TextMessage tm = (TextMessage)cons1.receive(3000);
             assertNotNull(tm);
- 
+
             if (tm.getText().substring("message2-".length()).equals("1"))
             {
             	offset = 1;
             }
-            
+
             assertEquals("message2-" + (i * 2 + offset), tm.getText());
          }
-         
+
          Message msg = cons1.receive(3000);
          assertNull(msg);
-         
+
          if (offset == 1)
          {
          	offset = 0;
@@ -1351,23 +1322,23 @@
          else
          {
          	offset = 1;
-         }      
-         
+         }
+
          for (int i = 0; i < NUM_MESSAGES / 2; i++)
          {
             TextMessage tm = (TextMessage)cons2.receive(3000);
             assertNotNull(tm);
             assertEquals("message2-" + (i * 2 + offset), tm.getText());
          }
-         
+
          msg = cons2.receive(3000);
          assertNull(msg);
-                 
+
          cons1.close();
          cons2.close();
 
          sess2.unsubscribe("sub");
-         
+
          try
          {
          	sess3.unsubscribe("sub");
@@ -1397,16 +1368,16 @@
          }
       }
    }
-   
-   
+
+
    private void nonClusteredTopicNonDurable(boolean persistent) throws Exception
-   {   	   	
+   {
       Connection conn0 = null;
       Connection conn1 = null;
       Connection conn2 = null;
-   	   
+
    	// Deploy three non clustered topics with same name on different nodes
-      
+
       try
       {
          Topic topic0 = (Topic)ic[0].lookup("/nonClusteredTopic");
@@ -1418,7 +1389,7 @@
          conn0 = this.createConnectionOnServer(cf, 0);
          conn1 = this.createConnectionOnServer(cf, 1);
          conn2 = this.createConnectionOnServer(cf, 2);
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn0, conn1, conn2});
 
          Session sess0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -1428,11 +1399,11 @@
          conn0.start();
          conn1.start();
          conn2.start();
-         
+
          MessageConsumer cons0 = sess0.createConsumer(topic0);
          MessageConsumer cons1 = sess1.createConsumer(topic1);
          MessageConsumer cons2 = sess2.createConsumer(topic2);
-         
+
          // ==============
          // Send at node 0
 
@@ -1448,34 +1419,34 @@
 
             prod0.send(tm);
          }
-         
+
          // Try and consume at node 1
-            
+
          Message m = cons1.receive(3000);
 
          assertNull(m);
-            
+
          //And at node 2
-         
+
          m = cons2.receive(3000);
 
          assertNull(m);
-           
+
          // Now consume at node 0
-          
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)cons0.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
-         }                 
+         }
 
          m = cons0.receive(3000);
 
          assertNull(m);
-         
+
          // ==============
          // Send at node 1
 
@@ -1489,34 +1460,34 @@
 
             prod1.send(tm);
          }
-         
+
          // Try and consume at node 0
-         
+
          m = cons0.receive(3000);
 
          assertNull(m);
-         
+
          //And at node 2
-         
+
          m = cons2.receive(3000);
 
          assertNull(m);
-         
+
          // Now consume at node 1
-            
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)cons1.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
-         }                 
+         }
 
          m = cons1.receive(3000);
 
          assertNull(m);
-         
+
          // ==============
          // Send at node 2
 
@@ -1530,29 +1501,29 @@
 
             prod2.send(tm);
          }
-         
+
          // Try and consume at node 0
-         
+
          m = cons0.receive(3000);
 
          assertNull(m);
-              
+
          //And at node 1
-           
+
          m = cons1.receive(3000);
 
          assertNull(m);
-         
+
          // Now consume at node 2
-               
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)cons2.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
-         }                 
+         }
 
          m = cons2.receive(3000);
 
@@ -1574,27 +1545,27 @@
          {
             conn2.close();
          }
-         
+
          ServerManagement.undeployQueue("nonClusteredTopic", 0);
-         
+
          ServerManagement.undeployQueue("nonClusteredTopic", 1);
-         
+
          ServerManagement.undeployQueue("nonClusteredTopic", 2);
       }
    }
-   
-   
+
+
    private void nonClusteredTopicDurable(boolean persistent) throws Exception
-   {   	   	
+   {
       Connection conn0 = null;
       Connection conn1 = null;
       Connection conn2 = null;
-   	   
+
    	// Deploy three non clustered topics with same name on different nodes
-      
+
       try
       {
- 
+
          Topic topic0 = (Topic)ic[0].lookup("/nonClusteredTopic");
          Topic topic1 = (Topic)ic[1].lookup("/nonClusteredTopic");
          Topic topic2 = (Topic)ic[2].lookup("/nonClusteredTopic");
@@ -1604,11 +1575,11 @@
          conn0 = this.createConnectionOnServer(cf, 0);
          conn1 = this.createConnectionOnServer(cf, 1);
          conn2 = this.createConnectionOnServer(cf, 2);
-         
+
          conn0.setClientID("cl123");
          conn1.setClientID("cl123");
          conn2.setClientID("cl123");
-         
+
          checkConnectionsDifferentServers(new Connection[] {conn0, conn1, conn2});
 
          Session sess0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -1618,14 +1589,14 @@
          conn0.start();
          conn1.start();
          conn2.start();
-         
+
          MessageConsumer cons0 = sess0.createDurableSubscriber(topic0, "mysub1");
          MessageConsumer cons1 = sess1.createDurableSubscriber(topic1, "mysub1");
          MessageConsumer cons2 = sess2.createDurableSubscriber(topic2, "mysub1");
          cons0.close();
          cons1.close();
          cons2.close();
-         
+
          // ==============
          // Send at node 0
 
@@ -1641,46 +1612,46 @@
 
             prod0.send(tm);
          }
-         
+
          // Try and consume at node 1
-            
+
          cons1 = sess1.createDurableSubscriber(topic1, "mysub1");
-         
+
          Message m = cons1.receive(3000);
 
          assertNull(m);
-         
+
          cons1.close();
-            
+
          //And at node 2
-         
+
          cons2 = sess2.createDurableSubscriber(topic2, "mysub1");
-         
+
          m = cons2.receive(3000);
 
          assertNull(m);
-         
+
          cons2.close();
-           
+
          // Now consume at node 0
-         
+
          cons0 = sess0.createDurableSubscriber(topic0, "mysub1");
-          
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)cons0.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
-         }                 
+         }
 
          m = cons0.receive(3000);
 
          assertNull(m);
-         
+
          cons0.close();
-         
+
          // ==============
          // Send at node 1
 
@@ -1694,46 +1665,46 @@
 
             prod1.send(tm);
          }
-         
+
          cons0 = sess0.createDurableSubscriber(topic0, "mysub1");
-         
+
          // Try and consume at node 0
-         
+
          m = cons0.receive(3000);
 
          assertNull(m);
-         
+
          cons0.close();
-         
+
          //And at node 2
-         
+
          cons2 = sess2.createDurableSubscriber(topic2, "mysub1");
-         
+
          m = cons2.receive(3000);
 
          assertNull(m);
-         
+
          cons2.close();
-         
+
          // Now consume at node 1
-            
+
          cons1 = sess1.createDurableSubscriber(topic1, "mysub1");
-         
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)cons1.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
-         }                 
+         }
 
          m = cons1.receive(3000);
 
          assertNull(m);
-         
+
          cons1.close();
-         
+
          // ==============
          // Send at node 2
 
@@ -1747,50 +1718,50 @@
 
             prod2.send(tm);
          }
-         
+
          cons0 = sess0.createDurableSubscriber(topic0, "mysub1");
-                  
+
          // Try and consume at node 0
-         
+
          m = cons0.receive(3000);
 
          assertNull(m);
-         
+
          cons0.close();
-         
+
          sess0.unsubscribe("mysub1");
-                       
+
          //And at node 1
-           
+
          cons1 = sess1.createDurableSubscriber(topic1, "mysub1");
-                  
+
          m = cons1.receive(3000);
 
          assertNull(m);
-         
+
          cons1.close();
-         
-         sess1.unsubscribe("mysub1");         
-         
+
+         sess1.unsubscribe("mysub1");
+
          // Now consume at node 2
-         
+
          cons2 = sess2.createDurableSubscriber(topic2, "mysub1");
-                        
+
          for (int i = 0; i < NUM_MESSAGES; i++)
          {
             TextMessage tm = (TextMessage)cons2.receive(3000);
 
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
-         }                 
+         }
 
          m = cons2.receive(3000);
 
          assertNull(m);
-         
+
          cons2.close();
-         
+
          sess2.unsubscribe("mysub1");
       }
       finally
@@ -1809,18 +1780,18 @@
          {
             conn2.close();
          }
-         
+
          ServerManagement.undeployQueue("nonClusteredTopic", 0);
-         
+
          ServerManagement.undeployQueue("nonClusteredTopic", 1);
-         
+
          ServerManagement.undeployQueue("nonClusteredTopic", 2);
       }
    }
 
-  
+
    // Inner classes -------------------------------------------------
-   
+
    public class TestListener implements MessageListener
    {
       // Constants -----------------------------------------------------
@@ -1855,7 +1826,7 @@
          }
          else
          {
-   
+
             try
             {
                wait(5000);
@@ -1864,7 +1835,7 @@
             {
                // OK
             }
-   
+
             return message;
          }
 

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/FailoverTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/FailoverTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/FailoverTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -56,9 +56,9 @@
    	//We need to sleep and relookup the connection factory due to http://jira.jboss.com/jira/browse/JBMESSAGING-1038
    	//remove this when this task is complete
    	Thread.sleep(2000);
-   	
+
    	ConnectionFactory theCF = (ConnectionFactory)ic[0].lookup("/ClusteredConnectionFactory");
-   	
+
       Connection conn = null;
 
       try
@@ -132,14 +132,14 @@
 
          // failover complete
          assertEquals(0, getServerId(conn));
-         
+
          // use the old session to send/receive a message
          session.createProducer(queue[0]).send(session.createTextMessage("blik"));
-              
+
          TextMessage m = (TextMessage)session.createConsumer(queue[0]).receive(5000);
-         
+
          assertNotNull(m);
-         
+
          assertEquals("blik", m.getText());
       }
       finally
@@ -311,11 +311,11 @@
 
          // failover complete
          assertEquals(0, getServerId(conn));
-         
+
          TextMessage rm = (TextMessage)cons.receive(2000);
          assertNotNull(rm);
          assertEquals("nik", rm.getText());
-         
+
       }
       finally
       {
@@ -349,7 +349,7 @@
          prod.send(session.createTextMessage("click"));
          prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
          prod.send(session.createTextMessage("clack"));
-         
+
          //Give time for the NP message to arrive
          Thread.sleep(2000);
 
@@ -385,7 +385,7 @@
          assertEquals("click", tm.getText());
 
          assertFalse(en.hasMoreElements());
-         
+
          removeAllMessages(queue[1].getQueueName(), true, 0);
       }
       finally
@@ -444,8 +444,8 @@
          prod.send(session.createTextMessage("click"));
          prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
          prod.send(session.createTextMessage("clack"));
-         
-         //Give time for the NP message to arrive         
+
+         //Give time for the NP message to arrive
          Thread.sleep(2000);
 
          en = browser.getEnumeration();
@@ -465,7 +465,7 @@
 
          assertTrue(texts.contains("click"));
          assertTrue(texts.contains("clack"));
-         
+
          removeAllMessages(queue[1].getQueueName(), true, 0);
       }
       finally
@@ -893,7 +893,7 @@
 
          // close the producer
          prod.close();
-         
+
          // create a consumer and receive messages, but don't acknowledge
 
          MessageConsumer cons = session.createConsumer(queue[1]);
@@ -969,7 +969,7 @@
          session.commit();
 
          // close the producer
-   
+
          prod.close();
 
          // create a consumer and receive messages, but don't acknowledge
@@ -1018,8 +1018,8 @@
          }
       }
    }
-   
-  
+
+
    public void testTransactedSessionWithAcknowledgmentsRollbackOnFailover() throws Exception
    {
       Connection conn = null;
@@ -1085,7 +1085,7 @@
          assertEquals("clik-persistent", m.getText());
 
          session.commit();
-         
+
          checkEmpty(queue[1], 0);
       }
       finally
@@ -1182,10 +1182,10 @@
          // test the client-side failover valve
 
          TextMessage tm = (TextMessage)cons.receive(60000);
-    
+
          assertNotNull(tm);
          assertEquals("blip", tm.getText());
-         
+
          tm = (TextMessage)cons.receive(1000);
          assertNull(tm);
       }
@@ -1225,16 +1225,16 @@
          // wait until the failure (not the completion of client-side failover) is detected
 
          assertEquals(FailoverEvent.FAILURE_DETECTED, listener.getEvent(60000).getType());
-         
+
          // create a consumer the very next moment the failure is detected. This way, we also
          // test the client-side failover valve
-         
+
          MessageConsumer cons = session.createConsumer(queue[1]);
-         
+
          // we must receive the message
 
          TextMessage tm = (TextMessage)cons.receive(60000);
-         assertEquals("blip", tm.getText());         
+         assertEquals("blip", tm.getText());
       }
       finally
       {
@@ -1408,7 +1408,7 @@
    public void testFailureRightAfterSendTransaction() throws Exception
    {
       Connection conn = null;
- 
+
       try
       {
          conn = this.createConnectionOnServer(cf, 1);
@@ -1448,10 +1448,10 @@
             assertNotNull(tm);
 
             assertEquals("before-poison" + i, tm.getText());
-         }         
+         }
 
          assertNull(consumer.receive(3000));
-         
+
          session.commit();
       }
       finally
@@ -1463,6 +1463,66 @@
       }
    }
 
+   public void testFailureRightBeforeSendTransaction() throws Exception
+   {
+      Connection conn = null;
+
+      try
+      {
+         conn = this.createConnectionOnServer(cf, 1);
+
+         assertEquals(1, getServerId(conn));
+
+         // we "cripple" the remoting connection by removing ConnectionListener. This way, failures
+         // cannot be "cleanly" detected by the client-side pinger, and we'll fail on an invocation
+         JMSRemotingConnection rc = ((ClientConnectionDelegate)((JBossConnection)conn).
+            getDelegate()).getRemotingConnection();
+         rc.removeConnectionListener();
+
+         // poison the server
+         ServerManagement.poisonTheServer(1, PoisonInterceptor.FAIL_BEFORE_SENDTRANSACTION);
+
+         Session session = conn.createSession(true, Session.SESSION_TRANSACTED);
+
+         conn.start();
+
+         MessageProducer producer = session.createProducer(queue[0]);
+
+         producer.setDeliveryMode(DeliveryMode.PERSISTENT);
+
+         MessageConsumer consumer = session.createConsumer(queue[0]);
+
+         producer.send(session.createTextMessage("before-poison1"));
+         producer.send(session.createTextMessage("before-poison2"));
+         producer.send(session.createTextMessage("before-poison3"));
+         session.commit();
+
+         Thread.sleep(2000);
+
+         for (int i = 1; i <= 3; i++)
+         {
+            TextMessage tm = (TextMessage) consumer.receive(5000);
+
+            assertNotNull(tm);
+
+            assertEquals("before-poison" + i, tm.getText());
+         }
+
+         assertNull(consumer.receive(3000));
+
+         session.commit();
+      }
+      finally
+      {
+         if (conn != null)
+         {
+            conn.close();
+         }
+      }
+   }
+
+
+
    public void testCloseConsumer() throws Exception
    {
       Connection conn0 = null;
@@ -1611,8 +1671,8 @@
       }
    }
 
-   
-   
+
+
    public void testDurableSubscriptionFailover() throws Exception
    {
       Connection conn = null;
@@ -1620,9 +1680,9 @@
       try
       {
          conn = createConnectionOnServer(cf, 1);
-         
+
          conn.setClientID("myclientid1");
-         
+
          conn.start();
 
          Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -1630,15 +1690,15 @@
          // register a failover listener
          SimpleFailoverListener failoverListener = new SimpleFailoverListener();
          ((JBossConnection)conn).registerFailoverListener(failoverListener);
-         
+
          MessageConsumer cons = session.createDurableSubscriber(topic[1], "mysub1");
-         
+
          MessageProducer prod = session.createProducer(topic[1]);
-         
+
          for (int i = 0; i < 5; i++)
          {
             TextMessage tm = session.createTextMessage("message" + i);
-            
+
             prod.send(tm);
          }
 
@@ -1661,25 +1721,25 @@
 
          // failover complete
          assertEquals(0, getServerId(conn));
-         
+
          for (int i = 5; i < 10; i++)
          {
             TextMessage tm = session.createTextMessage("message" + i);
-            
+
             prod.send(tm);
          }
-         
+
          for (int i = 0; i < 10; i++)
          {
             TextMessage tm = (TextMessage)cons.receive(30000);
-            
+
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          cons.close();
-         
+
          session.unsubscribe("mysub1");
       }
       finally
@@ -1690,45 +1750,45 @@
          }
       }
    }
-    
+
    public void testDurableSubscriptionFailoverTwosubscribers() throws Exception
    {
       Connection conn = null;
-      
+
       Connection conn0 = null;
 
       try
       {
          conn = createConnectionOnServer(cf, 1);
-         
+
          conn.setClientID("myclientid1");
-         
+
          conn.start();
-         
+
          conn0 = this.createConnectionOnServer(cf, 0);
-         
+
          //same client id
          conn0.setClientID("myclientid1");
 
          Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-         
+
          Session session0 = conn0.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
          // register a failover listener
          SimpleFailoverListener failoverListener = new SimpleFailoverListener();
          ((JBossConnection)conn).registerFailoverListener(failoverListener);
-         
+
          MessageConsumer cons = session.createDurableSubscriber(topic[1], "mysub1");
-         
+
          //Durable sub on different node with same client id and sub name
          MessageConsumer cons0 = session0.createDurableSubscriber(topic[0], "mysub1");
-         
+
          MessageProducer prod = session.createProducer(topic[1]);
-         
+
          for (int i = 0; i < 5; i++)
          {
             TextMessage tm = session.createTextMessage("message" + i);
-            
+
             prod.send(tm);
          }
 
@@ -1751,27 +1811,27 @@
 
          // failover complete
          assertEquals(0, getServerId(conn));
-         
+
          for (int i = 5; i < 10; i++)
          {
             TextMessage tm = session.createTextMessage("message" + i);
-            
+
             prod.send(tm);
          }
-         
+
          for (int i = 0; i < 10; i++)
          {
             TextMessage tm = (TextMessage)cons.receive(30000);
-            
+
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          cons.close();
-         
+
          cons0.close();
-         
+
          session.unsubscribe("mysub1");
       }
       finally
@@ -1780,19 +1840,19 @@
          {
             conn.close();
          }
-         
+
          if (conn0 != null)
          {
             conn0.close();
          }
       }
    }
-    
-   
+
+
    public void testDurableSubscriptionFailoverWithClientIDOnConnectionFactory() throws Exception
    {
       Connection conn = null;
-      
+
       final String clientID = "ooble";
 
       ServerManagement.getServer(0).deployConnectionFactory("jboss.messaging.connectionfactory:service=WibbleConnectionFactory",
@@ -1801,13 +1861,13 @@
       ServerManagement.getServer(1).deployConnectionFactory("jboss.messaging.connectionfactory:service=WibbleConnectionFactory",
             new String[] { "/WibbleCF"},
             true, true, clientID);
-      
+
       ConnectionFactory myCF = (ConnectionFactory)ic[0].lookup("/WibbleCF");
-      
+
       try
       {
          conn = createConnectionOnServer(myCF, 1);
-               
+
          conn.start();
 
          Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -1815,15 +1875,15 @@
          // register a failover listener
          SimpleFailoverListener failoverListener = new SimpleFailoverListener();
          ((JBossConnection)conn).registerFailoverListener(failoverListener);
-         
+
          MessageConsumer cons = session.createDurableSubscriber(topic[1], "mysub1");
-         
+
          MessageProducer prod = session.createProducer(topic[1]);
-         
+
          for (int i = 0; i < 5; i++)
          {
             TextMessage tm = session.createTextMessage("message" + i);
-            
+
             prod.send(tm);
          }
 
@@ -1846,25 +1906,25 @@
 
          // failover complete
          assertEquals(0, getServerId(conn));
-         
+
          for (int i = 5; i < 10; i++)
          {
             TextMessage tm = session.createTextMessage("message" + i);
-            
+
             prod.send(tm);
          }
-         
+
          for (int i = 0; i < 10; i++)
          {
             TextMessage tm = (TextMessage)cons.receive(30000);
-            
+
             assertNotNull(tm);
-            
+
             assertEquals("message" + i, tm.getText());
          }
-         
+
          cons.close();
-         
+
          session.unsubscribe("mysub1");
       }
       finally
@@ -1873,11 +1933,11 @@
          {
             conn.close();
          }
-         
+
          ServerManagement.getServer(0).undeployConnectionFactory(new ObjectName("jboss.messaging.connectionfactory:service=WibbleConnectionFactory"));
       }
    }
-   
+
    public void testFailoverDeliveryRecoveryTransacted() throws Exception
    {
       Connection conn0 = null;
@@ -1886,7 +1946,7 @@
       try
       {
          conn0 = this.createConnectionOnServer(cf, 0);
-         
+
          assertEquals(0, ((JBossConnection)conn0).getServerID());
 
          // Objects Server1
@@ -1895,43 +1955,43 @@
          assertEquals(1, ((JBossConnection)conn1).getServerID());
 
          Session session1 = conn1.createSession(true, Session.SESSION_TRANSACTED);
-         
+
          Session session2 = conn1.createSession(true, Session.SESSION_TRANSACTED);
 
          MessageConsumer cons1 = session1.createConsumer(queue[1]);
-         
+
          MessageConsumer cons2 = session2.createConsumer(queue[1]);
-         
+
          MessageProducer prod = session1.createProducer(queue[1]);
-         
+
          conn1.start();
-                  
+
          TextMessage tm1 = session1.createTextMessage("message1");
-         
+
          TextMessage tm2 = session1.createTextMessage("message2");
-         
+
          TextMessage tm3 = session1.createTextMessage("message3");
-         
+
          prod.send(tm1);
-         
+
          prod.send(tm2);
-         
+
          prod.send(tm3);
-         
+
          session1.commit();
-                           
+
          TextMessage rm1 = (TextMessage)cons1.receive(3000);
-         
+
          assertNotNull(rm1);
-         
+
          assertEquals(tm1.getText(), rm1.getText());
-                                    
+
          TextMessage rm2 = (TextMessage)cons2.receive(3000);
-         
+
          assertNotNull(rm2);
-         
+
          assertEquals(tm2.getText(), rm2.getText());
-         
+
          SimpleFailoverListener failoverListener = new SimpleFailoverListener();
          ((JBossConnection)conn1).registerFailoverListener(failoverListener);
 
@@ -1953,27 +2013,27 @@
          }
 
          // failover complete
-         
+
          //now commit
-         
+
          session1.commit();
-         
+
          session2.commit();
-         
+
          session1.close();
-         
+
          session2.close();;
-         
+
          Session session3 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
-         
+
          MessageConsumer cons3 = session3.createConsumer(queue[0]);
-         
+
          TextMessage rm3 = (TextMessage)cons3.receive(2000);
-         
+
          assertNotNull(rm3);
-         
+
          assertEquals(tm3.getText(), rm3.getText());
-         
+
          checkEmpty(queue[1], 0);
       }
       finally
@@ -2002,7 +2062,7 @@
    }
 
    // Private --------------------------------------------------------------------------------------
-   
+
    private void simpleFailover(String userName, String password) throws Exception
    {
       Connection conn = null;
@@ -2017,7 +2077,7 @@
          {
             conn = createConnectionOnServer(cf, 1);
          }
-         
+
          conn.start();
 
          // Disable Lease for this test.. as the ValveAspect should capture this
@@ -2108,7 +2168,7 @@
          	assertNull(tm);
          }
          else
-         {        
+         {
             assertNotNull(tm);
 
             assertEquals("before-poison", tm.getText());
@@ -2128,9 +2188,9 @@
          }
       }
    }
-   
-   
 
+
+
    // Inner classes --------------------------------------------------------------------------------
-   
+
 }

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/GroupManagementTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/GroupManagementTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/GroupManagementTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -60,7 +60,7 @@
       try
       {
          ServerManagement.start(0, "all", false);
-         
+
          log.info("Started server 0");
 
          ServerManagement.addNotificationListener(0, postOfficeObjectName, listener);
@@ -387,11 +387,11 @@
          ServerManagement.kill(9);
       }
    }
-   
+
    public void testStartServersSimultaneously() throws Exception
    {
       final int numServers = 5;
-      
+
       try
       {
          class ServerStarter extends Thread
@@ -402,20 +402,20 @@
             {
                this.nodeID = nodeID;
             }
-            
+
             public void run()
             {
                try
                {
                   log.info("Starting " + nodeID);
                   ServerManagement.start(nodeID, "all", false);
-                  
+
                   ServerManagement.deployQueue("testDistributedQueue1", nodeID);
                   ServerManagement.deployTopic("testDistributedTopic1", nodeID);
-                  
+
                   ServerManagement.deployQueue("testDistributedQueue2", nodeID);
                   ServerManagement.deployTopic("testDistributedTopic2", nodeID);
-                  
+
                   ServerManagement.deployQueue("testDistributedQueue3", nodeID);
                   ServerManagement.deployTopic("testDistributedTopic3", nodeID);
                   log.info("Done start");
@@ -427,24 +427,24 @@
                }
             }
          }
-         
-         ServerStarter[] starters = new ServerStarter[numServers];         
+
+         ServerStarter[] starters = new ServerStarter[numServers];
          for (int i = 0; i < 5; i++)
          {
             starters[i] = new ServerStarter(i);
             starters[i].start();
          }
-         
+
          boolean failed = false;
          for (int i = 0; i < 5; i++)
-         {          
+         {
             starters[i].join();
             if (starters[i].failed)
             {
                failed = true;
             }
          }
-         
+
          assertFalse(failed);
 
          Set view = ServerManagement.getServer(0).getNodeIDView();
@@ -459,7 +459,7 @@
                ServerManagement.stop(i);
             }
             catch (Exception ignore)
-            {               
+            {
             }
          }
       }
@@ -472,16 +472,16 @@
    protected void setUp() throws Exception
    {
       super.setUp();
-      
-      for (int i = ServerManagement.MAX_SERVER_COUNT - 1; i >=0; i--)
-      {
-      	ServerManagement.kill(i);
-      }
    }
 
    protected void tearDown() throws Exception
    {
       super.tearDown();
+
+      for (int i = ServerManagement.MAX_SERVER_COUNT - 1; i >=0; i--)
+      {
+         ServerManagement.kill(i);
+      }
    }
 
    // Private -------------------------------------------------------

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LargeClusterTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LargeClusterTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LargeClusterTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -113,7 +113,7 @@
    {
       // By this time, after running setUp(), we should have an already formed cluster of seven
       // nodes
-    
+
       Set view = ServerManagement.getServer(0).getNodeIDView();
 
       assertEquals(7, view.size());
@@ -426,14 +426,6 @@
       log.debug("setup done");
    }
 
-   protected void tearDown() throws Exception
-   {
-      super.tearDown();
-      
-      assertEquals(0, ResourceManagerFactory.instance.size());	
-   }
-
-
    // Private -------------------------------------------------------
 
    // Inner classes -------------------------------------------------

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LoadBalancingTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LoadBalancingTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/LoadBalancingTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -58,24 +58,24 @@
          clusteredDelegate.getLoadBalancingPolicy().getClass());
 
       Connection conn0 = cf.createConnection();
-      
+
       final int oneId = getServerId(conn0);
       final int otherId = 1 - oneId;
 
       Connection conn1 = cf.createConnection();
-      
+
       assertEquals(otherId, getServerId(conn1));
 
       Connection conn2 = cf.createConnection();
-      
+
       assertEquals(oneId, getServerId(conn2));
 
       conn0.close();
       conn1.close();
       conn2.close();
    }
-   
 
+
    public void testRoundRobinLoadBalancingTwoNodes() throws Exception
    {
       JBossConnectionFactory jbcf = (JBossConnectionFactory)cf;
@@ -86,7 +86,7 @@
          clusteredDelegate.getLoadBalancingPolicy().getClass());
 
       Connection conn0 = cf.createConnection();
-      
+
       final int oneId = getServerId(conn0);
       final int otherId = 1 - oneId;
 
@@ -114,7 +114,7 @@
       conn3.close();
       conn4.close();
    }
-   
+
    public void testRoundRobinLoadBalancingStartsWithRandomNode() throws Exception
    {
       // Make sure all servers are created and started; make sure that database is zapped ONLY for
@@ -122,7 +122,7 @@
       // clear the database for those.
 
       int[] counts = new int[2];
-      
+
       for (int i = 0; i < 10; i++)
       {
          InitialContext ic = new InitialContext(ServerManagement.getJNDIEnvironment(0));
@@ -134,12 +134,12 @@
 
          counts[serverPeerID]++;
       }
-      
+
       assertTrue("Should have connected to ServerPeer 0 at least once", counts[0] > 0);
       assertTrue("Should have connected to ServerPeer 1 at least once", counts[1] > 0);
    }
 
- 
+
    // Package protected ----------------------------------------------------------------------------
 
    // Protected ------------------------------------------------------------------------------------
@@ -153,18 +153,9 @@
    protected void setUp() throws Exception
    {
    	nodeCount = 2;
-   	
+
       super.setUp();
-      
-      assertEquals(0, ResourceManagerFactory.instance.size());	
    }
-   
-   protected void tearDown() throws Exception
-   {
-   	super.tearDown();
-   	
-   	assertEquals(0, ResourceManagerFactory.instance.size());	
-   }
 
    // Private --------------------------------------------------------------------------------------
 

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MergeQueueTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MergeQueueTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MergeQueueTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -106,7 +106,7 @@
 
          //At this point there should be 5 messages on the node 0 queue (5-9)
          //and 10 messages on the node 1 queue (10-19)
-         
+
          ServerManagement.kill(1);
 
          consumer0 = session0.createConsumer(queue[0]);
@@ -119,7 +119,7 @@
             log.info("msg = " + msg.getText());
             ids.add(msg.getText());
          }
-         
+
          for (int i = 5; i < 20; i++)
          {
          	assertTrue(ids.contains("message " + i));
@@ -175,7 +175,7 @@
 
          TextMessage msg;
 
-         
+
          //Consume messages 0 - 4 on node node 0 transactionally
          for (int i = 0; i < 5; i++)
          {
@@ -190,7 +190,7 @@
          consumer0.close();
 
          log.info("Consumed messages 0 - 4 on node 0");
-         
+
          // node 1
          conn1 = createConnectionOnServer(cf, 1);
 
@@ -211,21 +211,21 @@
          }
 
          session1.commit();
-         
+
          log.info("Sent messages 10 - 19 on node 1");
-         
+
          //At this point we should have messages 5 - 9 sitting in queue on node 0
          //and messages 10 - 19 sitting in queue on node 1
 
          //Create a consumer on node 1
-         
+
          log.info("Creating consumer on node 1");
-         
+
          // This will actually end up sucking messages from node 0
          MessageConsumer consumer1 = session1.createConsumer(queue[1]);
-         
+
          //Give it enough time to suck
-         
+
          log.info("Waiting for suck");
          Thread.sleep(5000);
 
@@ -236,31 +236,31 @@
          // close the consumer .. .and this should cause failover to kick in
          log.info("closing the consumer");
          consumer1.close();
-         
+
          log.info("closed the consumer");
 
          consumer0 = session0.createConsumer(queue[0]);
-         
+
          log.info("creating new consumer");
-         
+
          //We should now be able to consume the messages 5 to 19.
          //Note that they will be in a different order since 10 to 10 were sucked to node 0 before crashing
          //Also there is the possibility that after crashing the queue attempted to delivery to one or more of the remote consumers
          //for the node that crashed, (YES it is possible to send more than one message on a failed connection before getting
-         //an exception), so this won't be cancelled until the connection checker kicks in any closes the consumer         
-         
+         //an exception), so this won't be cancelled until the connection checker kicks in any closes the consumer
+
          Set msgs = new HashSet();
-         
+
          for (int i = 5; i < 20; i++)
          {
             msg = (TextMessage)consumer0.receive(60000);
             assertNotNull(msg);
-            
+
             log.info("Got message " + msg.getText());
-            
+
             msgs.add(msg.getText());
          }
-         
+
          for (int i = 5; i < 20; i++)
          {
             assertTrue(msgs.contains("message " + i));
@@ -269,7 +269,7 @@
          assertNull(consumer0.receive(5000));
 
          session0.commit();
-         
+
          log.info("end");
       }
       finally
@@ -297,13 +297,13 @@
          conn0 = createConnectionOnServer(cf, 0);
 
          assertEquals(0, getServerId(conn0));
-         
+
          conn1 = createConnectionOnServer(cf, 1);
-         
+
          assertEquals(1, getServerId(conn1));
-         
+
          //Send some messages on node 0
-         
+
          Session session0 = conn0.createSession(true, Session.SESSION_TRANSACTED);
 
          MessageProducer producer0 = session0.createProducer(queue[0]);
@@ -312,12 +312,12 @@
          {
             producer0.send(session0.createTextMessage("message " + i));
          }
-         
+
          session0.commit();
-         
-         
+
+
          //Send some more on node 1
-         
+
          Session session1 = conn1.createSession(true, Session.SESSION_TRANSACTED);
 
          MessageProducer producer1 = session1.createProducer(queue[1]);
@@ -326,41 +326,41 @@
          {
             producer1.send(session1.createTextMessage("message " + i));
          }
-         
+
          session1.commit();
-         
-         
+
+
          //Don't consume them or they will be pulled from one node to another
-         
-         
+
+
          //Now kill the server
          waitForFailoverComplete(1, conn1);
 
          //Messages should all be available on node 0
-         
+
          MessageConsumer cons0 = session0.createConsumer(queue[0]);
-         
+
          TextMessage tm;
-         
+
          conn0.start();
-         
+
          for (int i = 0; i < 20; i++)
          {
             tm = (TextMessage)cons0.receive(60000);
-            
+
             assertNotNull(tm);
-            
+
             log.info("received message " + tm.getText());
-                        
+
             assertEquals("message " + i, tm.getText());
          }
-         
+
          tm = (TextMessage)cons0.receive(1000);
-         
+
          assertNull(tm);
-         
+
          session0.commit();
-         
+
       }
       finally
       {
@@ -376,15 +376,15 @@
       }
    }
    // Fil consumer
-   
+
    /*
     * Both queues paging > fullsize
     */
    public void testMergeQueuePagingFill1() throws Exception
-   {      
+   {
       mergeQueuePaging(20, 20, 10, 10, true);
    }
-   
+
    /*
     * Both queues paging = fullsize
     */
@@ -392,7 +392,7 @@
    {
       mergeQueuePaging(10, 10, 10, 10, true);
    }
-   
+
    /*
     * First queue paging, second queue not > full size
     */
@@ -400,7 +400,7 @@
    {
       mergeQueuePaging(20, 5, 10, 10, true);
    }
-   
+
    /*
     * Second queue paging, first queue not > full size
     */
@@ -408,7 +408,7 @@
    {
       mergeQueuePaging(5, 20, 10, 10, true);
    }
-   
+
    /*
     * First queue paging, second queue not = full size
     */
@@ -416,7 +416,7 @@
    {
       mergeQueuePaging(10, 5, 10, 10, true);
    }
-   
+
    /*
     * Second queue paging, first queue not = full size
     */
@@ -424,17 +424,17 @@
    {
       mergeQueuePaging(5, 10, 10, 10, true);
    }
-   
+
    // Don't fill consumer
-   
+
    /*
     * Both queues paging > fullsize
     */
    public void testMergeQueuePagingNoFill1() throws Exception
-   {      
+   {
       mergeQueuePaging(20, 20, 10, 10, false);
    }
-   
+
    /*
     * Both queues paging = fullsize
     */
@@ -442,7 +442,7 @@
    {
       mergeQueuePaging(10, 10, 10, 10, false);
    }
-   
+
    /*
     * First queue paging, second queue not > full size
     */
@@ -450,7 +450,7 @@
    {
       mergeQueuePaging(20, 5, 10, 10, false);
    }
-   
+
    /*
     * Second queue paging, first queue not > full size
     */
@@ -458,7 +458,7 @@
    {
       mergeQueuePaging(5, 20, 10, 10, false);
    }
-   
+
    /*
     * First queue paging, second queue not = full size
     */
@@ -466,7 +466,7 @@
    {
       mergeQueuePaging(10, 5, 10, 10, false);
    }
-   
+
    /*
     * Second queue paging, first queue not = full size
     */
@@ -474,7 +474,7 @@
    {
       mergeQueuePaging(5, 10, 10, 10, false);
    }
-   
+
    /*
     * Both queues paging on merge
     */
@@ -486,46 +486,46 @@
       try
       {
          //Deploy queue with fullSize of 10
-         
+
          ServerManagement.deployQueue("constrainedQueue", "queue/constrainedQueue",full0, 2, 2, 0, true);
-         
+
          ServerManagement.deployQueue("constrainedQueue", "queue/constrainedQueue",full1, 2, 2, 1, true);
-         
+
          Queue queue0 = (Queue)ic[0].lookup("queue/constrainedQueue");
-         
+
          Queue queue1 = (Queue)ic[1].lookup("queue/constrainedQueue");
-         
+
          // Objects Server0
          conn0 = createConnectionOnServer(cf, 0);
 
          assertEquals(0, getServerId(conn0));
-         
+
          conn1 = createConnectionOnServer(cf, 1);
-         
+
          assertEquals(1, getServerId(conn1));
-         
+
          //Send some messages on node 0
-         
+
          Session session0 = conn0.createSession(true, Session.SESSION_TRANSACTED);
 
          MessageProducer producer0 = session0.createProducer(queue0);
 
          log.info("sending messages on node 0");
-         
+
          for (int i = 0; i < messages0; i++)
          {
             producer0.send(session0.createTextMessage("message " + i));
-            
+
             log.info("Sent message: message " + i);
          }
-         
+
          session0.commit();
-         
-         
+
+
          //Send some more on node 1
-         
+
          log.info("Sending some messages on node 1");
-         
+
          Session session1 = conn1.createSession(true, Session.SESSION_TRANSACTED);
 
          MessageProducer producer1 = session1.createProducer(queue1);
@@ -533,65 +533,65 @@
          for (int i = messages0; i < messages0 + messages1; i++)
          {
             producer1.send(session1.createTextMessage("message " + i));
-            
+
             log.info("Sent message: message " + i);
          }
-         
+
          session1.commit();
-         
+
          MessageConsumer cons0 = null;
-         
+
          if (fillConsumer)
          {
             //Creating the consumer immediately after kill should ensure that all the messages are in the consumer and
             //not paged to disk
             cons0 = session0.createConsumer(queue0);
          }
-                 
+
          //Now kill the server
 
          waitForFailoverComplete(1, conn1);
-         
+
          if (!fillConsumer)
          {
             cons0 = session0.createConsumer(queue0);
          }
 
          //Messages should all be available on node 0
-         
+
          //Note they may be in a different order due to being pulled in to the consumer before killing the server
          //And also because they may have been attempted to have been delivered to a remote consumer corresponding to a
          //remote consumer for the failed node, so that delivery or one after may fail, so those messages may not get cancelled
          //back until the connection checker kicks in and closes the consumer
-         
-         conn0.start();                 
-                 
-         
+
+         conn0.start();
+
+
          Set msgs = new HashSet();
-         
+
          TextMessage tm;
-         
+
          for (int i = 0; i < messages0 + messages1; i++)
          {
          	//Need a long timeout to allow for connection checker to kick in and close consumer
          	tm = (TextMessage)cons0.receive(60000);
-            
+
             assertNotNull(tm);
-            
+
             log.info("Got message " + tm.getText());
-            
+
             msgs.add(tm.getText());
          }
-         
+
          for (int i = 0; i < messages0 + messages1; i++)
          {
             assertTrue(msgs.contains("message " + i));
          }
-                  
+
          tm = (TextMessage)cons0.receive(2000);
-         
-         assertNull(tm);    
-         
+
+         assertNull(tm);
+
          session0.commit();
       }
       finally
@@ -601,17 +601,17 @@
             ServerManagement.undeployQueue("constrainedQueue", 0);
          }
          catch (Exception ignore)
-         {            
+         {
          }
-         
+
          try
          {
             ServerManagement.undeployQueue("constrainedQueue", 1);
          }
          catch (Exception ignore)
-         {            
+         {
          }
-                  
+
          if (conn0!=null)
          {
             conn0.close();
@@ -623,7 +623,7 @@
          }
       }
    }
-   
+
    // Package protected ----------------------------------------------------------------------------
 
    // Protected ------------------------------------------------------------------------------------
@@ -638,5 +638,5 @@
    // Private --------------------------------------------------------------------------------------
 
    // Inner classes --------------------------------------------------------------------------------
-   
+
 }

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MultiThreadFailoverTest.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MultiThreadFailoverTest.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/jms/clustering/MultiThreadFailoverTest.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -280,8 +280,8 @@
 //
 //   }
 
-   
 
+
    // I kept this method on public area on purpose.. just to be easier to read the code
    // As this is the real test being executed by test methods here.
    private void multiThreadFailover(int producerThread, int consumerThread, boolean transacted,
@@ -466,24 +466,6 @@
       super.setUp();
    }
 
-   protected void tearDown() throws Exception
-   {
-
-      if (ServerManagement.getServer(0) != null)
-      {      
-         this.removeAllMessages(queue[0].getQueueName(), true, 0);
-      }
-      if (ServerManagement.getServer(1) != null)
-      {
-         this.removeAllMessages(queue[1].getQueueName(), true, 1);
-      }
-      if (ServerManagement.getServer(2) != null)
-      {
-         this.removeAllMessages(queue[2].getQueueName(), true, 2);
-      }
-      super.tearDown();
-   }
-
    // Private --------------------------------------------------------------------------------------
 
    // Inner classes --------------------------------------------------------------------------------
@@ -533,7 +515,7 @@
             this.exception = e;
          }
       }
-      
+
    }
 
    // Inner classes used by testMultiThreadFailover ------------------------------------------------

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/aop/PoisonInterceptor.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/aop/PoisonInterceptor.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/aop/PoisonInterceptor.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -35,11 +35,11 @@
    // Constants ------------------------------------------------------------------------------------
 
    private static final Logger log = Logger.getLogger(PoisonInterceptor.class);
-   
+
    public static final int NULL = -1;
 
    public static final int TYPE_CREATE_SESSION = 0;
-   
+
    public static final int TYPE_2PC_COMMIT = 1;
 
    public static final int FAIL_AFTER_ACKNOWLEDGE_DELIVERY = 2;
@@ -53,18 +53,20 @@
    public static final int FAIL_SYNCHRONIZED_SEND_RECEIVE = 6;
 
    public static final int FAIL_AFTER_SENDTRANSACTION = 7;
-   
+
    public static final int LONG_SEND = 8;
 
    public static final int CF_CREATE_CONNECTION= 9;
 
    public static final int CF_GET_CLIENT_AOP_STACK = 10;
+
+   public static final int FAIL_BEFORE_SENDTRANSACTION = 11;
    // Static ---------------------------------------------------------------------------------------
-   
+
    private static int type = NULL;
 
    private static Object sync = new Object();
-   
+
    public static void setType(int type)
    {
       PoisonInterceptor.type = type;
@@ -88,7 +90,7 @@
       {
          return invocation.invokeNext();
       }
-      
+
       MethodInvocation mi = (MethodInvocation)invocation;
       String methodName = mi.getMethod().getName();
       Object target = mi.getTargetObject();
@@ -101,20 +103,20 @@
          // Used by the failover tests to kill server in the middle of an invocation.
 
          log.info("##### Crashing on createSessionDelegate!!");
-         
+
          crash(target);
       }
       else if (target instanceof ConnectionAdvised && "sendTransaction".equals(methodName))
       {
          TransactionRequest request = (TransactionRequest)mi.getArguments()[0];
-         
+
          if (request.getRequestType() == TransactionRequest.TWO_PHASE_COMMIT_REQUEST
              && type == TYPE_2PC_COMMIT)
          {
             //Crash before 2pc commit (after prepare)- used in message bridge tests
-            
+
             log.info("##### Crashing on 2PC commit!!");
-            
+
             crash(target);
          }
          else if (request.getRequestType() == TransactionRequest.ONE_PHASE_COMMIT_REQUEST &&
@@ -124,6 +126,12 @@
             log.info("#### Crash after sendTransaction");
             crash(target);
          }
+         else if (request.getRequestType() == TransactionRequest.ONE_PHASE_COMMIT_REQUEST &&
+               type == FAIL_BEFORE_SENDTRANSACTION)
+        {
+           log.info("#### Crash before sendTransaction");
+           crash(target);
+        }
       }
       else if (target instanceof SessionAdvised && "acknowledgeDelivery".equals(methodName)
                  && type == FAIL_AFTER_ACKNOWLEDGE_DELIVERY)
@@ -196,7 +204,7 @@
             //Pause for 1 mins before processing send
             log.info("Sleeping for 1 minutes before sending....");
             Thread.sleep(60000);
-            
+
             invocation.invokeNext();
          }
       }
@@ -209,8 +217,8 @@
 
       return invocation.invokeNext();
    }
-  
 
+
    // Public ---------------------------------------------------------------------------------------
 
    // Package protected ----------------------------------------------------------------------------

Modified: branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/container/ServiceContainer.java
===================================================================
--- branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/container/ServiceContainer.java	2008-02-20 20:31:57 UTC (rev 3747)
+++ branches/Branch_Stable/tests/src/org/jboss/test/messaging/tools/container/ServiceContainer.java	2008-02-20 21:44:11 UTC (rev 3748)
@@ -108,7 +108,7 @@
 
    // Used only on testcases where Socket and HTTP are deployed at the same time
    public static ObjectName HTTP_REMOTING_OBJECT_NAME;
-   
+
    public static ObjectName SERVER_PEER_OBJECT_NAME;
 
    public static String DATA_SOURCE_JNDI_NAME = "java:/DefaultDS";
@@ -158,7 +158,7 @@
 
          HTTP_REMOTING_OBJECT_NAME =
          new ObjectName("jboss.messaging:service=Connector,transport=http");
-         
+
          SERVER_PEER_OBJECT_NAME =
          new ObjectName("jboss.messaging:service=ServerPeer");
          SECURITYSTORE_OBJECT_NAME = new ObjectName("jboss.messaging:service=SecurityStore");
@@ -368,7 +368,7 @@
          initialContext = new InitialContext();
 
          System.setProperty("javax.management.builder.initial",
-                               "org.jboss.test.messaging.tools.container.MBeanServerBuilder");         
+                               "org.jboss.test.messaging.tools.container.MBeanServerBuilder");
 
          mbeanServer = MBeanServerFactory.createMBeanServer("jboss");
 
@@ -445,7 +445,7 @@
          throw new Exception("Failed to start ServiceContainer", e);
       }
    }
-   
+
    public void dropTables() throws Exception
    {
    	dropAllTables();
@@ -492,17 +492,17 @@
       connFactoryObjectNames.clear();
 
    }
-   
+
    public void flushManagedConnectionPool()
    {
    	mcp.flush();
    }
-   
 
+
    public void stop() throws Exception
    {
    	log.info("Stopping serviceconatiner");
-   	
+
       unloadJNDIContexts();
 
       stopService(REMOTING_OBJECT_NAME);
@@ -536,7 +536,7 @@
       {
          initialContext.unbind(MockJBossSecurityManager.TEST_SECURITY_DOMAIN);
       }
-      
+
       cleanJNDI();
 
       initialContext.close();
@@ -595,14 +595,14 @@
    {
       String databaseName = getDatabaseName();
 
-      return "server/default/deploy/" + databaseName + "-persistence-service.xml";      
+      return "server/default/deploy/" + databaseName + "-persistence-service.xml";
    }
-   
+
    public Properties getPersistenceManagerSQLProperties() throws Exception
    {
       String persistenceConfigFile = getPersistenceConfigFile(false);
       log.info("Persistence config file: .... " + persistenceConfigFile);
-      
+
       MBeanConfigurationElement persistenceManagerConfig =
          ServiceConfigHelper.loadServiceConfiguration(persistenceConfigFile, "PersistenceManager");
 
@@ -615,7 +615,7 @@
          Properties sqlProperties = new Properties();
 
          sqlProperties.load(is);
-         
+
          return sqlProperties;
       }
       else
@@ -673,7 +673,7 @@
    {
       ObjectName on = mbeanConfig.getObjectName();
       serviceCreator.install(on, CLASS_LOADER_OBJECT_NAME, mbeanConfig.getDelegate());
-      
+
       // inject dependencies
       for(Iterator i = mbeanConfig.dependencyOptionalAttributeNames().iterator(); i.hasNext(); )
       {
@@ -819,7 +819,7 @@
       stopManagedConnectionPool(JMS_MANAGED_CONNECTION_POOL_OBJECT_NAME);
       undeployJBossJMSRA(JMS_MANAGED_CONNECTION_FACTORY_OBJECT_NAME);
    }
-   
+
    public String getDatabaseName()
    {
       return config.getDatabaseName();
@@ -845,7 +845,7 @@
    {
       initialContext.unbind(jndi);
    }
-   
+
    public void startRecoveryManager()
    {
       log.info("Starting arjuna recovery manager");
@@ -858,7 +858,7 @@
 
       log.info("Started recovery manager");
    }
-   
+
    public void stopRecoveryManager()
    {
       if (recoveryManager != null)
@@ -888,7 +888,7 @@
          {
          	//Delete the old one
          	//deleteDirectory(new File(objectStoreDir));
-         	
+
             newObjectStore = objectStoreDir + "/" + newObjectStore;
          }
 
@@ -908,8 +908,8 @@
       }
    }
 
-   
 
+
    public String toString()
    {
       return "ServiceContainer[" + Integer.toHexString(hashCode()) + "]";
@@ -1156,7 +1156,7 @@
       log.info("driver:" + config.getDatabaseConnectionURL());
       log.info("username:" + config.getDatabaseUserName());
       log.info("password:" + config.getDatabasePassword());
-      
+
       mcf.setConnectionURL(config.getDatabaseConnectionURL());
       mcf.setDriverClass(config.getDatabaseDriverClass());
       mcf.setUserName(config.getDatabaseUserName());
@@ -1195,8 +1195,8 @@
       mbeanServer.registerMBean(mcp, on);
       mbeanServer.invoke(on, "start", new Object[0], new String[0]);
       log.debug("started " + on);
-      
-      
+
+
    }
 
    /**
@@ -1285,12 +1285,12 @@
    {
       stopService(managedConnFactoryObjectName);
    }
-   
+
    private String buildLocatorURI(String transport, Map overrideMap) throws Exception
    {
       // We use this from thirdparty remoting tests when we don't want to send stuff through
       // JMSWireFormat, but we want everything else in the connector's configuration to be
-      // identical with what we use in Messaging         
+      // identical with what we use in Messaging
       boolean overrideMarshallers =
          overrideMap != null && overrideMap.get(DO_NOT_USE_MESSAGING_MARSHALLERS) != null;
 
@@ -1301,15 +1301,15 @@
 
       MBeanConfigurationElement connectorServiceConfig =
          ServiceConfigHelper.loadServiceConfiguration(configFileName, "Connector");
-      
+
       String invokerConfig = connectorServiceConfig.getAttributeValue("Configuration");
-      
+
       Element invokerElement = (Element) XMLUtil
          .stringToElement(invokerConfig)
          .getElementsByTagName("invoker").item(0);
-      
+
       NodeList invokerAttributes = invokerElement.getElementsByTagName("attribute");
-      
+
       StringBuffer paramsBuffer = new StringBuffer();
 
       for (int i = 0; i < invokerAttributes.getLength(); i++)
@@ -1321,7 +1321,7 @@
          {
             continue;
          }
-         
+
          String value = attr.getTextContent().trim();
 
          if (overrideMarshallers &&
@@ -1348,7 +1348,7 @@
       }
 
       int freePort = PortUtil.findFreePort(ipAddressOrHostName);
-      
+
       return new StringBuffer()
          .append(transport).append("://")
          .append(ipAddressOrHostName).append(':').append(freePort)
@@ -1409,7 +1409,7 @@
    {
       MockJBossSecurityManager sm = new MockJBossSecurityManager();
       this.initialContext.bind(MockJBossSecurityManager.TEST_SECURITY_DOMAIN, sm);
-      
+
       toUnbindAtExit.add(MockJBossSecurityManager.TEST_SECURITY_DOMAIN);
 
       log.debug("started JBoss Mock Security Manager, using ic: " + this.initialContext + " id " + System.identityHashCode(this.initialContext));
@@ -1430,33 +1430,33 @@
       for (Iterator i = toUnbindAtExit.iterator(); i.hasNext(); )
       {
          String name = (String)i.next();
-         
+
          initialContext.unbind(name);
       }
    }
-   
+
    private void executeStatement(TransactionManager mgr, DataSource ds, String statement) throws Exception
    {
       Connection conn = null;
       boolean exception = false;
-   
+
       try
       {
          try
          {
-            mgr.begin();            
-            
+            mgr.begin();
+
             conn = ds.getConnection();
-            
+
             log.debug("executing " + statement);
-            
+
             PreparedStatement ps = conn.prepareStatement(statement);
-      
+
             ps.executeUpdate();
-      
+
             log.debug(statement + " executed");
-      
-            ps.close();           
+
+            ps.close();
          }
          catch (SQLException e)
          {
@@ -1470,8 +1470,8 @@
          if (conn != null)
          {
             conn.close();
-         }         
-         
+         }
+
          if (exception)
          {
             mgr.rollback();
@@ -1481,8 +1481,8 @@
             mgr.commit();
          }
       }
-      
-     
+
+
    }
 
    protected void dropAllTables() throws Exception
@@ -1490,7 +1490,7 @@
       log.info("DROPPING ALL TABLES FROM DATABASE!");
 
       InitialContext ctx = new InitialContext();
-      
+
       // We need to execute each drop in its own transaction otherwise postgresql will not execute
       // further commands after one fails
 
@@ -1498,19 +1498,19 @@
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
 
       javax.transaction.Transaction txOld = mgr.suspend();
-                  
+
       executeStatement(mgr, ds, "DROP TABLE JBM_POSTOFFICE");
-      
+
       executeStatement(mgr, ds, "DROP TABLE JBM_MSG_REF");
 
       executeStatement(mgr, ds, "DROP TABLE JBM_MSG");
-     
+
       executeStatement(mgr, ds, "DROP TABLE JBM_TX");
-      
+
       executeStatement(mgr, ds, "DROP TABLE JBM_COUNTER");
-      
+
       executeStatement(mgr, ds, "DROP TABLE JBM_USER");
-      
+
       executeStatement(mgr, ds, "DROP TABLE JBM_ROLE");
 
       executeStatement(mgr, ds, "DROP TABLE JBM_DUAL");
@@ -1522,13 +1522,13 @@
 
       log.debug("done with dropping tables");
    }
-   
+
    protected void deleteAllData() throws Exception
    {
       log.info("DELETING ALL DATA FROM DATABASE!");
 
       InitialContext ctx = new InitialContext();
-      
+
       // We need to execute each drop in its own transaction otherwise postgresql will not execute
       // further commands after one fails
 
@@ -1536,21 +1536,23 @@
       DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
 
       javax.transaction.Transaction txOld = mgr.suspend();
-                  
+
       executeStatement(mgr, ds, "DELETE FROM JBM_POSTOFFICE");
-      
+
       executeStatement(mgr, ds, "DELETE FROM JBM_MSG_REF");
 
       executeStatement(mgr, ds, "DELETE FROM JBM_MSG");
-     
+
       executeStatement(mgr, ds, "DELETE FROM JBM_TX");
-      
+
       executeStatement(mgr, ds, "DELETE FROM JBM_COUNTER");
-      
+
       executeStatement(mgr, ds, "DELETE FROM JBM_USER");
-      
+
       executeStatement(mgr, ds, "DELETE FROM JBM_ROLE");
-      
+
+      executeStatement(mgr, ds, "DELETE FROM JBM_ID_CACHE");
+
       if (txOld != null)
       {
          mgr.resume(txOld);
@@ -1630,7 +1632,7 @@
          invoke(on, "start", new Object[0], new String[0]);
          connFactoryObjectNames.add(on);
       }
-      
+
       connFactoryElements = cfdd.query("service", "ClusteredConnectionFactory");
 
       for (Iterator i = connFactoryElements.iterator(); i.hasNext();)
@@ -1643,7 +1645,7 @@
          invoke(on, "start", new Object[0], new String[0]);
          connFactoryObjectNames.add(on);
       }
-      
+
       connFactoryElements = cfdd.query("service", "HTTPConnectionFactory");
 
       for (Iterator i = connFactoryElements.iterator(); i.hasNext();)
@@ -1656,7 +1658,7 @@
          invoke(on, "start", new Object[0], new String[0]);
          connFactoryObjectNames.add(on);
       }
-      
+
       connFactoryElements = cfdd.query("service", "ClusterPullConnectionFactory");
 
       for (Iterator i = connFactoryElements.iterator(); i.hasNext();)
@@ -1670,7 +1672,7 @@
          connFactoryObjectNames.add(on);
       }
    }
-   
+
    private void parseConfig(String config)
    {
       config = config.toLowerCase();
@@ -1693,7 +1695,7 @@
             remoting = true;
             security = true;
          }
-         else         
+         else
          if ("all+http".equals(tok))
          {
          	transaction = true;
@@ -1766,6 +1768,6 @@
          }
       }
    }
-   
+
    // Inner classes --------------------------------------------------------------------------------
 }




More information about the jboss-cvs-commits mailing list