[jboss-cvs] JBoss Messaging SVN: r3839 - in trunk: src/main/org/jboss/messaging/core/client and 38 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Tue Mar 4 09:08:59 EST 2008


Author: timfox
Date: 2008-03-04 09:08:59 -0500 (Tue, 04 Mar 2008)
New Revision: 3839

Added:
   trunk/src/main/org/jboss/messaging/core/postoffice/FlowController.java
   trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java
   trunk/src/main/org/jboss/messaging/util/TokenBucketLimiter.java
   trunk/tests/src/org/jboss/messaging/core/message/
   trunk/tests/src/org/jboss/messaging/core/message/impl/
   trunk/tests/src/org/jboss/messaging/core/message/impl/test/
   trunk/tests/src/org/jboss/messaging/core/message/impl/test/unit/
   trunk/tests/src/org/jboss/messaging/core/message/impl/test/unit/MessageTest.java
   trunk/tests/src/org/jboss/messaging/core/postoffice/
   trunk/tests/src/org/jboss/messaging/core/postoffice/impl/
   trunk/tests/src/org/jboss/messaging/core/postoffice/impl/test/
   trunk/tests/src/org/jboss/messaging/core/postoffice/impl/test/unit/
   trunk/tests/src/org/jboss/messaging/core/postoffice/impl/test/unit/PostOfficeTest.java
   trunk/tests/src/org/jboss/messaging/core/transaction/
   trunk/tests/src/org/jboss/messaging/core/transaction/impl/
   trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/
   trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/
   trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/MessagingXidTest.java
   trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/TransactionTest.java
   trunk/tests/src/org/jboss/messaging/core/util/
   trunk/tests/src/org/jboss/messaging/core/util/test/
   trunk/tests/src/org/jboss/messaging/core/util/test/unit/
   trunk/tests/src/org/jboss/messaging/core/util/test/unit/TokenBucketLimiterTest.java
Removed:
   trunk/src/main/org/jboss/messaging/core/server/FlowController.java
   trunk/src/main/org/jboss/messaging/core/server/impl/FlowControllerImpl.java
   trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessageTest.java
   trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessagingXidTest.java
   trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/PostOfficeTest.java
   trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/TransactionTest.java
Modified:
   trunk/src/etc/server/default/deploy/jbm-jndi.xml
   trunk/src/main/org/jboss/messaging/core/client/ClientSession.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionFactoryImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
   trunk/src/main/org/jboss/messaging/core/management/MessagingServerManagement.java
   trunk/src/main/org/jboss/messaging/core/management/impl/MessagingServerManagementImpl.java
   trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java
   trunk/src/main/org/jboss/messaging/core/message/impl/MessageReferenceImpl.java
   trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java
   trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerMessageCodec.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerResponseMessageCodec.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerResponseMessage.java
   trunk/src/main/org/jboss/messaging/core/server/Queue.java
   trunk/src/main/org/jboss/messaging/core/server/QueueFactory.java
   trunk/src/main/org/jboss/messaging/core/server/ServerProducer.java
   trunk/src/main/org/jboss/messaging/core/server/ServerSession.java
   trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java
   trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java
   trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java
   trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
   trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
   trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
   trunk/tests/etc/log4j.xml
   trunk/tests/src/org/jboss/messaging/core/remoting/impl/wireformat/test/unit/PacketTypeTest.java
   trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSL.java
   trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSLTest.java
   trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/QueueTest.java
   trunk/tests/src/org/jboss/test/messaging/jms/AcknowledgementTest.java
   trunk/tests/src/org/jboss/test/messaging/jms/MessageConsumerTest.java
   trunk/tests/src/org/jboss/test/messaging/jms/server/JMSServerManagerTest.java
   trunk/tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
Log:
Producer flow control mainly


Modified: trunk/src/etc/server/default/deploy/jbm-jndi.xml
===================================================================
--- trunk/src/etc/server/default/deploy/jbm-jndi.xml	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/etc/server/default/deploy/jbm-jndi.xml	2008-03-04 14:08:59 UTC (rev 3839)
@@ -27,7 +27,7 @@
       <entry name="java:/connectionfactories/acme/connection_factory"/>
       <!-- You can specify the default Client ID to use for connections created using this factory -->
       <client-id>MyClientID</client-id>
-      <!-- PrefetchSize determines the approximate maximum number of messages the client consumer will buffer locally -->
+      <!-- PrefetchSize determines the maximum number of messages the client consumer will buffer locally -->
       <prefetch-size>150</prefetch-size>
       <!-- The batch size to use when using the DUPS_OK_ACKNOWLEDGE acknowledgement mode -->
       <dups-ok-batch-size>5000</dups-ok-batch-size>
@@ -39,6 +39,13 @@
       <load-balancing-factory>org.jboss.messaging.jms.client.plugin.RoundRobinLoadBalancingFactory</load-balancing-factory>
       <!-- Whether we should be strict TCK compliant, i.e. how we deal with foreign messages, defaults to false-->
       <strict-tck>true</strict-tck>
+      
+      <!-- This is the window size in number of messages to use when using producer window based flow control -->
+      <producer-window-size>1000</producer-window-size>
+      
+      <!-- This is the maximum producer send rate that will be applied when using rate based producer flow control -->
+      <producer-max-rate>100</producer-max-rate>
+      
    </connection-factory>
 
    <queue name="DLQ">

Modified: trunk/src/main/org/jboss/messaging/core/client/ClientSession.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/ClientSession.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/client/ClientSession.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -40,6 +40,10 @@
    
    ClientProducer createProducer(String address) throws MessagingException;
    
+   ClientProducer createRateLimitedProducer(String address, int rate) throws MessagingException;
+   
+   ClientProducer createProducerWithWindowSize(String address, int windowSize) throws MessagingException;
+   
    XAResource getXAResource();
 
    void commit() throws MessagingException;

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionFactoryImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionFactoryImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionFactoryImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -73,21 +73,43 @@
 
    private final boolean strictTck;
    
+   private final int maxProducerRate;
+   
+   private final int producerWindowSize;
+   
    // Static ---------------------------------------------------------------------------------------
     
    // Constructors ---------------------------------------------------------------------------------
 
    public ClientConnectionFactoryImpl(final int serverID, final RemotingConfiguration remotingConfig,
    		                             final Version serverVersion, final boolean strictTck,
-                                      final int prefetchSize)
+                                      final int prefetchSize,
+                                      final int producerWindowSize, final int maxProducerRate)
    {
       this.serverID = serverID;
       this.remotingConfig = remotingConfig;
       this.serverVersion = serverVersion;
       this.strictTck = strictTck;
-      this.prefetchSize = prefetchSize;
+      this.prefetchSize = prefetchSize;      
+      this.maxProducerRate = maxProducerRate;
+      this.producerWindowSize = producerWindowSize;
       this.dispatcher = new PacketDispatcherImpl();
+      
+      log.info("creating cf with ws: "+ this.producerWindowSize + " and maxrate " + maxProducerRate);
    }
+   
+   public ClientConnectionFactoryImpl(final int serverID, final RemotingConfiguration remotingConfig,
+                                      final Version serverVersion)
+   {
+      this.serverID = serverID;
+      this.remotingConfig = remotingConfig;
+      this.serverVersion = serverVersion;
+      this.strictTck = false;
+      this.prefetchSize = 150;      
+      this.maxProducerRate = -1;
+      this.producerWindowSize = 1000;
+      this.dispatcher = new PacketDispatcherImpl();
+   }
 
    public ClientConnection createConnection() throws MessagingException
    {
@@ -115,7 +137,8 @@
             (CreateConnectionResponse)remotingConnection.send(id, request);
          
          ClientConnectionImpl connection =
-            new ClientConnectionImpl(response.getConnectionID(), serverID, strictTck, remotingConnection);
+            new ClientConnectionImpl(response.getConnectionID(), serverID, strictTck, remotingConnection,
+            		maxProducerRate, producerWindowSize);
 
          return connection;
       }
@@ -158,6 +181,33 @@
    {
       return serverVersion;
    }
+
+	public int getPrefetchSize()
+	{
+		return prefetchSize;
+	}
+
+	public int getProducerWindowSize()
+	{
+		return producerWindowSize;
+	}
+
+	public int getServerID()
+	{
+		return serverID;
+	}
+
+	public boolean isStrictTck()
+	{
+		return strictTck;
+	}
+
+	public int getMaxProducerRate()
+	{
+		return maxProducerRate;
+	}
+	
+	
    
    // Public ---------------------------------------------------------------------------------------
       

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientConnectionImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -69,13 +69,18 @@
    private final Map<String, ClientSession> children = new ConcurrentHashMap<String, ClientSession>();
 
    private volatile boolean closed;
+   
+   private final int maxProducerRate;
+   
+   private final int producerWindowSize;
 
    // Static ---------------------------------------------------------------------------------------
 
    // Constructors ---------------------------------------------------------------------------------
 
    public ClientConnectionImpl(final String id, final int serverID, final boolean strictTck,
-                               final RemotingConnection connection)
+                               final RemotingConnection connection, final int maxProducerRate,
+                               final int producerWindowSize)
    {
       this.id = id;
       
@@ -84,6 +89,10 @@
       this.strictTck = strictTck;
       
       this.remotingConnection = connection;
+      
+      this.maxProducerRate = maxProducerRate;
+      
+      this.producerWindowSize = producerWindowSize;
    }
    
    // ClientConnection implementation --------------------------------------------------------------
@@ -97,7 +106,9 @@
 
       ConnectionCreateSessionResponseMessage response = (ConnectionCreateSessionResponseMessage)remotingConnection.send(id, request);   
 
-      ClientSession session =  new ClientSessionImpl(this, response.getSessionID(), ackBatchSize, cacheProducers);
+      ClientSession session =
+      	new ClientSessionImpl(this, response.getSessionID(), ackBatchSize, cacheProducers, maxProducerRate,
+      			                producerWindowSize);
 
       children.put(response.getSessionID(), session);
 

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -275,7 +275,9 @@
          // This is ok - we just ignore the message
          return;
       }
-
+      
+      log.info("Got message " + message.getMessage().getMessageID() + " del id " + message.getDeliveryID());
+      
       if (ignoreDeliveryMark >= 0)
       {
          long delID = message.getDeliveryID();
@@ -284,14 +286,20 @@
          {
             // Ignore - the session is recovering and these are inflight
             // messages
+         	log.info("Ignoring");
             return;
          }
-         else
+         else if (delID == ignoreDeliveryMark)
          {
             // We have hit the begining of the recovered messages - we can
             // stop ignoring
+         	log.info("Stopping ignoring");
             ignoreDeliveryMark = -1;
          }
+         else
+         {
+         	throw new IllegalStateException("Invalid delivery id " + delID);
+         }
       }
       
       if (handler != null)
@@ -329,6 +337,8 @@
       	
       	synchronized (this)
       	{
+      		log.info("Adding to buffer: " + message.getMessage().getMessageID());
+      		
       		buffer.addLast(message, message.getMessage().getPriority());
          	      		
       		notify();
@@ -338,9 +348,12 @@
 
    public void recover(final long lastDeliveryID)
    {
+   	log.info("Calling recover " +lastDeliveryID);
+   	
       ignoreDeliveryMark = lastDeliveryID;
 
       buffer.clear();      
+      log.info("Called recover");
    }
 
    // Public

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -25,8 +25,8 @@
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.Message;
-import org.jboss.messaging.core.remoting.PacketDispatcher;
 import org.jboss.messaging.core.remoting.impl.wireformat.ProducerSendMessage;
+import org.jboss.messaging.util.TokenBucketLimiter;
 
 /**
  * The client-side Producer connectionFactory class.
@@ -58,15 +58,24 @@
    
    private volatile boolean closed;
    
-   private volatile int availableTokens;
+   //For limit throttling
    
+   private volatile int windowSize;
+   
+   //For rate throttling
+     
+   private final TokenBucketLimiter rateLimiter;
+     
    // Static ---------------------------------------------------------------------------------------
 
    // Constructors ---------------------------------------------------------------------------------
       
    public ClientProducerImpl(final ClientSessionInternal session, final String id, final String address,
-   		                    final RemotingConnection remotingConnection, final int availableTokens)
+   		                    final RemotingConnection remotingConnection, final int windowSize,
+   		                    final int maxRate)
    {   	
+   	log.info("Creating producer with window size " + windowSize + " and max rate " + maxRate);
+   	
       this.session = session;
       
       this.id = id;
@@ -75,7 +84,16 @@
       
       this.remotingConnection = remotingConnection;
       
-      this.availableTokens = availableTokens;
+      this.windowSize = windowSize;
+      
+      if (maxRate != -1)
+      {
+      	this.rateLimiter = new TokenBucketLimiter(maxRate, false);
+      }
+      else
+      {
+      	this.rateLimiter = null;
+      }
    }
    
    // ClientProducer implementation ----------------------------------------------------------------
@@ -103,30 +121,34 @@
    {
    	ProducerSendMessage message = new ProducerSendMessage(address, msg.copy());
    	
-//   	if (address == null)
-//   	{
-//   		//flow control
-//   		
-//   		//TODO guard against waiting for ever - interrupt the thread???
-//   		
-//   		while (availableTokens == 0)
-//   		{
-//				synchronized (this)
-//				{
-//					try
-//					{						
-//					   wait();						
-//					}
-//					catch (InterruptedException e)
-//					{   						
-//					}
-//				}		
-//   		}
-//   	}
+   	//Window size of -1 means disable window flow control
+   	if (windowSize != -1 && address == null)
+   	{
+   		while (windowSize == 0)
+   		{
+				synchronized (this)
+				{
+					try
+					{						
+					   wait();						
+					}
+					catch (InterruptedException e)
+					{   						
+					}
+				}		
+   		}
+   		
+   		windowSize--;
+   	}
    	
    	remotingConnection.send(id, message, !msg.isDurable());
-   	
-   	//availableTokens--;
+   	 	   	
+   	if (rateLimiter != null)
+   	{
+   	   // Rate flow control
+      	   		
+   		rateLimiter.limit();
+   	}
    }
             
    public void registerAcknowledgementHandler(final AcknowledgementHandler handler)
@@ -145,6 +167,7 @@
       {
          return;         
       }
+      
       session.removeProducer(this);
       
       remotingConnection.getPacketDispatcher().unregister(id);
@@ -161,8 +184,8 @@
    
    public synchronized void receiveTokens(int tokens)
    {
-   	availableTokens += tokens;
-   	
+   	windowSize += tokens;
+   		
    	notify();
    }
    
@@ -181,7 +204,7 @@
          throw new MessagingException(MessagingException.OBJECT_CLOSED, "Producer is closed");
       }
    }
-   
+
    // Inner Classes --------------------------------------------------------------------------------
 
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -38,7 +38,6 @@
 import org.jboss.messaging.core.client.ClientProducer;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.PacketDispatcher;
 import org.jboss.messaging.core.remoting.impl.wireformat.AbstractPacket;
 import org.jboss.messaging.core.remoting.impl.wireformat.CloseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.ConsumerFlowTokenMessage;
@@ -106,6 +105,10 @@
    
    private final boolean cacheProducers;
    
+   private final int maxProducerRate;
+   
+   private final int producerWindowSize;
+   
    private final ExecutorService executor;
    
    private volatile boolean closed;
@@ -135,11 +138,19 @@
    //For testing only
    private boolean forceNotSameRM;
    
+   private long lastCommittedID = -1;
+   
    // Constructors ---------------------------------------------------------------------------------
    
    public ClientSessionImpl(final ClientConnectionInternal connection, final String id,
-                            final int lazyAckBatchSize, final boolean cacheProducers) throws MessagingException
+                            final int lazyAckBatchSize, final boolean cacheProducers,
+                            final int maxProducerRate, final int producerWindowSize) throws MessagingException
    {
+   	if (lazyAckBatchSize < -1 || lazyAckBatchSize == 0)
+   	{
+   		throw new IllegalArgumentException("Invalid lazyAckbatchSize, valid values are > 0 or -1 (infinite)");
+   	}
+   	
       this.id = id;
       
       this.connection = connection;
@@ -148,6 +159,10 @@
       
       this.cacheProducers = cacheProducers;
       
+      this.maxProducerRate = maxProducerRate;
+      
+      this.producerWindowSize = producerWindowSize;
+      
       executor = Executors.newSingleThreadExecutor();
       
       this.lazyAckBatchSize = lazyAckBatchSize;
@@ -273,8 +288,15 @@
 
    public ClientProducer createProducer(final String address) throws MessagingException
    {
+      return createProducer(address, producerWindowSize, maxProducerRate);
+   }
+   
+   public ClientProducer createProducer(final String address, final int windowSize, final int maxRate) throws MessagingException
+   {
       checkClosed();
       
+      log.info("Creating prod, ws:" + windowSize);
+      
       ClientProducerInternal producer = null;
       
       if (cacheProducers)
@@ -284,13 +306,14 @@
 
       if (producer == null)
       {
-      	SessionCreateProducerMessage request = new SessionCreateProducerMessage(address);
+      	SessionCreateProducerMessage request = new SessionCreateProducerMessage(address, windowSize);
       	
       	SessionCreateProducerResponseMessage response =
       		(SessionCreateProducerResponseMessage)remotingConnection.send(id, request);
       	
       	producer = new ClientProducerImpl(this, response.getProducerID(), address,
-      			                            remotingConnection, response.getInitialTokens());  
+      			                            remotingConnection, response.getWindowSize(),
+      			                            maxRate);  
       	
       	remotingConnection.getPacketDispatcher().register(new ClientProducerPacketHandler(producer, response.getProducerID()));
       }
@@ -300,6 +323,16 @@
       return producer;
    }
    
+   public ClientProducer createRateLimitedProducer(String address, int rate) throws MessagingException
+   {
+   	return createProducer(address, -1, rate);
+   }
+   
+   public ClientProducer createProducerWithWindowSize(String address, int windowSize) throws MessagingException
+   {
+   	return createProducer(address, windowSize, 0);
+   }
+   
    public XAResource getXAResource()
    {
       return this;
@@ -312,6 +345,8 @@
       acknowledgeInternal(false);
       
       remotingConnection.send(id, new SessionCommitMessage());
+      
+      lastCommittedID = lastID;
    }
    
    public void rollback() throws MessagingException
@@ -319,11 +354,11 @@
       checkClosed();
             
       //First we tell each consumer to clear it's buffers and ignore any deliveries with
-      //delivery id > last delivery id
+      //delivery id > last delivery id, until it gets delivery id = lastID again
       
       for (ClientConsumerInternal consumer: consumers.values())
       {
-         consumer.recover(lastID + 1);
+         consumer.recover(lastCommittedID + 1);
       }
       
       acknowledgeInternal(false);      
@@ -366,6 +401,14 @@
             toAckCount = 0;
          }                       
       }            
+      
+      //FIXME - temp hack - make server sessions alwyas transacted!!
+      
+      if (this.lazyAckBatchSize != -1)
+      {
+      	lastCommittedID = lastID;
+      }
+      
    }
 
    public synchronized void close() throws MessagingException

Modified: trunk/src/main/org/jboss/messaging/core/management/MessagingServerManagement.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/management/MessagingServerManagement.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/management/MessagingServerManagement.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -23,17 +23,15 @@
 
 import java.util.Collection;
 import java.util.List;
+import java.util.Set;
 
 import org.jboss.messaging.core.client.ClientConnectionFactory;
 import org.jboss.messaging.core.filter.Filter;
-import org.jboss.messaging.core.filter.impl.FilterImpl;
 import org.jboss.messaging.core.message.Message;
 import org.jboss.messaging.core.messagecounter.MessageCounter;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.ServerConnection;
 
-import java.util.Set;
-
 /**
  * This interface describes the management interface exposed by the server
  * 
@@ -48,13 +46,13 @@
 
    void destroyQueue(String name) throws Exception;
    
-   boolean addAddress(String address);
+   boolean addAddress(String address) throws Exception;
 
-   boolean removeAddress(String address);
+   boolean removeAddress(String address) throws Exception;
    
    List<Queue> getQueuesForAddress(String address) throws Exception;
 
-   ClientConnectionFactory createClientConnectionFactory(boolean strictTck,int prefetchSize);
+   ClientConnectionFactory createClientConnectionFactory(boolean strictTck,int prefetchSize, int producerWindowSize, int producerMaxRate);
 
    void removeAllMessagesForAddress(String address) throws Exception;
 

Modified: trunk/src/main/org/jboss/messaging/core/management/impl/MessagingServerManagementImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/management/impl/MessagingServerManagementImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/management/impl/MessagingServerManagementImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -130,7 +130,7 @@
       }
    }
 
-   public boolean addAddress(String address)
+   public boolean addAddress(String address) throws Exception
    {
       if (!messagingServer.getPostOffice().containsAllowableAddress(address))
       {
@@ -140,7 +140,7 @@
       return false;
    }
 
-   public boolean removeAddress(String address)
+   public boolean removeAddress(String address) throws Exception
    {
       if (messagingServer.getPostOffice().containsAllowableAddress(address))
       {
@@ -150,10 +150,15 @@
       return false;
    }
 
-   public ClientConnectionFactory createClientConnectionFactory(boolean strictTck, int prefetchSize)
+   public ClientConnectionFactory createClientConnectionFactory(boolean strictTck, int prefetchSize,
+   		                                                       int producerWindowSize, int producerMaxRate)
    {
       return new ClientConnectionFactoryImpl(messagingServer.getConfiguration().getMessagingServerID(),
-              messagingServer.getConfiguration().getRemotingConfiguration(), messagingServer.getVersion(), messagingServer.getConfiguration().isStrictTck() || strictTck, prefetchSize);
+              messagingServer.getConfiguration().getRemotingConfiguration(),
+              messagingServer.getVersion(),
+              messagingServer.getConfiguration().isStrictTck() || strictTck,
+              prefetchSize,
+              producerWindowSize, producerMaxRate);
    }
 
    public void removeAllMessagesForAddress(String address) throws Exception

Modified: trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -34,6 +34,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.Message;
 import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.server.HandleStatus;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.util.StreamUtils;
 
@@ -382,7 +383,10 @@
       {      
          for (MessageReference ref: references)
          {
-            ref.getQueue().addLast(ref);
+            if (ref.getQueue().addLast(ref) == HandleStatus.BUSY)
+            {
+            	log.warn("Message not added to queue " + ref.getQueue().getName() + " since it is full");
+            }
          }
       }
       finally

Modified: trunk/src/main/org/jboss/messaging/core/message/impl/MessageReferenceImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/message/impl/MessageReferenceImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/message/impl/MessageReferenceImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -125,7 +125,7 @@
          persistenceManager.deleteReference(this);
       }
       
-      queue.decrementDeliveringCount();
+      queue.referenceAcknowledged();
    }
    
    public boolean cancel(final PersistenceManager persistenceManager) throws Exception
@@ -135,14 +135,12 @@
          persistenceManager.updateDeliveryCount(queue, this);
       }
               
-      queue.decrementDeliveringCount();
+      queue.referenceCancelled();
 
       int maxDeliveries = queue.getQueueSettings().getMatch(queue.getName()).getMaxDeliveryAttempts();
       
       if (maxDeliveries > 0 && deliveryCount >= maxDeliveries)
-      {
-      	
-      	
+      {      	      	
          Queue DLQ = queue.getQueueSettings().getMatch(queue.getName()).getDLQ();
          
          if (DLQ != null)
@@ -171,6 +169,7 @@
    public void expire(final PersistenceManager persistenceManager) throws Exception
    {
       Queue expiryQueue = queue.getQueueSettings().getMatch(queue.getName()).getExpiryQueue();
+      
       if (expiryQueue != null)
       {
          Message copyMessage = makeCopyForDLQOrExpiry(false, persistenceManager);

Copied: trunk/src/main/org/jboss/messaging/core/postoffice/FlowController.java (from rev 3828, trunk/src/main/org/jboss/messaging/core/server/FlowController.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/FlowController.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/FlowController.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,41 @@
+/*
+ * 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.postoffice;
+
+import org.jboss.messaging.core.server.ServerProducer;
+
+
+/**
+ * 
+ * A FlowController
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public interface FlowController
+{
+	void messageAcknowledged() throws Exception;
+	
+	void messageReceived(ServerProducer producer, int windowSize) throws Exception;
+	
+	int getInitialTokens(int windowSize, ServerProducer producer);
+}

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -43,15 +43,18 @@
  * 
  * The PostOffice also maintains a set of "allowable addresses". These are the addresses that it is legal to
  * route to.
+ * 
+ * Finally, a PostOffice maintains a set of FlowControllers - one for each unique address. These are used, where
+ * appropriate to control the flow of messages sent to a particular address
  *  
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  *
  */
 public interface PostOffice extends MessagingComponent
 {   
-   void addAllowableAddress(String address);
+   void addAllowableAddress(String address) throws Exception;
    
-   boolean removeAllowableAddress(String address);
+   boolean removeAllowableAddress(String address) throws Exception;
    
    boolean containsAllowableAddress(String address);
 
@@ -67,6 +70,10 @@
    void route(String address, Message message) throws Exception;
    
    void routeFromCluster(String address, Message message) throws Exception;
+   
+   //Flow control
+   
+   FlowController getFlowController(String address);
      
    //For testing only
    Map<String, List<Binding>> getMappings();

Copied: trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java (from rev 3828, trunk/src/main/org/jboss/messaging/core/server/impl/FlowControllerImpl.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,162 @@
+/*
+ * 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.postoffice.impl;
+
+import java.util.List;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.postoffice.Binding;
+import org.jboss.messaging.core.postoffice.FlowController;
+import org.jboss.messaging.core.postoffice.PostOffice;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.ServerProducer;
+
+/**
+ * 
+ * A FlowControllerImpl
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class FlowControllerImpl implements FlowController
+{
+	private static final Logger log = Logger.getLogger(FlowControllerImpl.class);
+	
+	private int lastPot;
+		
+	private int tokenPot;
+	
+	private final PostOffice postOffice;
+	
+	private final String address;
+	
+	private final java.util.Queue<ServerProducer> waitingList = new ConcurrentLinkedQueue<ServerProducer>();
+	
+	public FlowControllerImpl(String address, PostOffice postOffice) throws Exception
+	{
+		this.address = address;
+		
+		this.postOffice = postOffice;
+		
+		fillPot();
+	}
+	
+	public synchronized int getInitialTokens(int windowSize, ServerProducer producer)
+	{
+		int num = Math.min(windowSize, tokenPot);
+		
+		tokenPot -= num;
+		
+		if (num == 0)
+		{
+			//Register producer as a waiter or will never get any messages
+			
+			producer.setWaiting(true);
+			
+			waitingList.add(producer);
+		}
+		
+		return num;
+	}
+				
+	//FIXME - sort out the synchronization on this - don't want to lock the whole thing
+	//also don't want to execute the whole method if already waiting
+	public synchronized void messageAcknowledged() throws Exception
+	{		
+		fillPot();
+			
+		while (tokenPot > 0)
+		{
+			ServerProducer producer = waitingList.poll();
+			
+			if (producer == null)
+			{
+				break;
+			}
+			
+			tokenPot--;
+			
+			producer.setWaiting(false);
+			
+			producer.sendCredits();
+		}					
+	}
+		
+	public synchronized void messageReceived(ServerProducer producer, int windowSize) throws Exception
+	{		
+		if (tokenPot == 0)
+		{
+			if (!producer.isWaiting())
+			{
+				producer.setWaiting(true);
+				
+				waitingList.add(producer);
+			}
+		}
+		else
+		{
+			tokenPot--;
+			
+			producer.sendCredits();
+		}
+	}
+			
+	private void fillPot() throws Exception
+	{
+		List<Binding> bindings = postOffice.getBindingsForAddress(address);
+		
+		int minAvailable = Integer.MAX_VALUE;
+		
+		for (Binding binding: bindings)
+		{
+			Queue queue = binding.getQueue();
+			
+			int maxSize = queue.getMaxSize();
+			
+			int available;
+			
+			if (maxSize == -1)
+			{
+				available = Integer.MAX_VALUE;
+			}
+			else
+			{
+				available = maxSize - queue.getMessageCount();
+			}
+			
+			if (available < 0)
+			{
+				available = 0;
+			}
+			
+			minAvailable = Math.min(available, minAvailable);			
+		}
+						
+		if (minAvailable > lastPot)
+		{
+			tokenPot += minAvailable - lastPot;
+			
+			lastPot = minAvailable;
+		}
+	}
+}

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -37,6 +37,7 @@
 import org.jboss.messaging.core.message.MessageReference;
 import org.jboss.messaging.core.persistence.PersistenceManager;
 import org.jboss.messaging.core.postoffice.Binding;
+import org.jboss.messaging.core.postoffice.FlowController;
 import org.jboss.messaging.core.postoffice.PostOffice;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.QueueFactory;
@@ -61,6 +62,8 @@
    
    private final ConcurrentMap<String, Binding> nameMap = new ConcurrentHashMap<String, Binding>();
    
+   private final ConcurrentMap<String, FlowController> flowControllers = new ConcurrentHashMap<String, FlowController>();
+   
    private final PersistenceManager persistenceManager;
    
    private final QueueFactory queueFactory;
@@ -95,14 +98,23 @@
    
    // PostOffice implementation -----------------------------------------------
 
-   public void addAllowableAddress(final String address)
+   public void addAllowableAddress(final String address) throws Exception
    {      
       allowableAddresses.add(address);
+      
+      flowControllers.put(address, new FlowControllerImpl(address, this));
    }
    
-   public boolean removeAllowableAddress(final String address)
+   public boolean removeAllowableAddress(final String address) throws Exception
    {      
-      return allowableAddresses.remove(address);
+      boolean removed = allowableAddresses.remove(address);
+      
+      if (removed)
+      {
+      	flowControllers.remove(address);
+      }
+      
+      return removed;
    }
    
    public boolean containsAllowableAddress(final String address)
@@ -110,7 +122,6 @@
       return allowableAddresses.contains(address);
    }
 
-
    public Set<String> listAvailableAddresses()
    {
       return allowableAddresses;
@@ -245,8 +256,11 @@
       return mappings;
    }
 
+   public FlowController getFlowController(String address)
+   {   	
+   	return flowControllers.get(address);
+   }
 
-
    // Private -----------------------------------------------------------------
    
    private Binding createBinding(final String address, final String name, final Filter filter,
@@ -259,7 +273,7 @@
       return binding;
    }
    
-   private void addBindingInMemory(final Binding binding)
+   private void addBindingInMemory(final Binding binding) throws Exception
    {              
       List<Binding> bindings = new CopyOnWriteArrayList<Binding>();
       
@@ -276,6 +290,10 @@
       {
          throw new IllegalStateException("Binding already exists " + binding);
       }     
+      
+      FlowController flowController = flowControllers.get(binding.getAddress());
+           
+      binding.getQueue().setFlowController(flowController);
    }
    
    private Binding removeQueueInMemory(final String queueName) throws Exception
@@ -311,6 +329,8 @@
       if (bindings.isEmpty())
       {
          mappings.remove(binding.getAddress());
+                           
+         binding.getQueue().setFlowController(null);
       }
                
       return binding;

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerMessageCodec.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerMessageCodec.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerMessageCodec.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -42,10 +42,11 @@
    {
       String address = request.getAddress();
      
-      int bodyLength = sizeof(address);
+      int bodyLength = sizeof(address) + INT_LENGTH;
 
       out.putInt(bodyLength);
       out.putNullableString(address);
+      out.putInt(request.getWindowSize());
    }
 
    @Override
@@ -59,8 +60,10 @@
       }
 
       String address = in.getNullableString();
+      
+      int windowSize = in.getInt();
 
-      return new SessionCreateProducerMessage(address);
+      return new SessionCreateProducerMessage(address, windowSize);
    }
 
    // Package protected ---------------------------------------------

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerResponseMessageCodec.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerResponseMessageCodec.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/codec/SessionCreateProducerResponseMessageCodec.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -47,7 +47,7 @@
        
       out.putInt(bodyLength);
       out.putNullableString(producerID);
-      out.putInt(response.getInitialTokens());
+      out.putInt(response.getWindowSize());
    }
 
    @Override
@@ -61,9 +61,9 @@
       }
 
       String producerID = in.getNullableString();
-      int initialTokens = in.getInt();
+      int windowSize = in.getInt();
  
-      return new SessionCreateProducerResponseMessage(producerID, initialTokens);
+      return new SessionCreateProducerResponseMessage(producerID, windowSize);
    }
 
    // Package protected ---------------------------------------------

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerMessage.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerMessage.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -19,16 +19,20 @@
    // Attributes ----------------------------------------------------
 
    private final String address;
+   
+   private final int windowSize;
       
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
 
-   public SessionCreateProducerMessage(final String address)
+   public SessionCreateProducerMessage(final String address, final int windowSize)
    {
       super(PacketType.SESS_CREATEPRODUCER);
 
       this.address = address;
+      
+      this.windowSize = windowSize;
    }
 
    // Public --------------------------------------------------------
@@ -38,6 +42,7 @@
    {
       StringBuffer buff = new StringBuffer(getParentString());
       buff.append(", address=" + address);
+      buff.append(", windowSize=" + windowSize);
       buff.append("]");
       return buff.toString();
    }
@@ -46,6 +51,11 @@
    {
       return address;
    }
+   
+   public int getWindowSize()
+   {
+   	return windowSize;
+   }
 
    // Package protected ---------------------------------------------
 

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerResponseMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerResponseMessage.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateProducerResponseMessage.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -22,19 +22,19 @@
 
    private final String producerID;
    
-   private final int initialTokens;
+   private final int windowSize;
 
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
 
-   public SessionCreateProducerResponseMessage(final String producerID, final int initialTokens)
+   public SessionCreateProducerResponseMessage(final String producerID, final int windowSize)
    {
       super(SESS_CREATEPRODUCER_RESP);
 
       this.producerID = producerID;
       
-      this.initialTokens = initialTokens;
+      this.windowSize = windowSize;
    }
 
    // Public --------------------------------------------------------
@@ -44,9 +44,9 @@
       return producerID;
    }
    
-   public int getInitialTokens()
+   public int getWindowSize()
    {
-   	return initialTokens;
+   	return windowSize;
    }
 
    @Override
@@ -54,7 +54,7 @@
    {
       StringBuffer buf = new StringBuffer(getParentString());
       buf.append(", producerID=" + producerID);
-      buf.append(", initialTokens=" + initialTokens);
+      buf.append(", windowSize=" + windowSize);
       buf.append("]");
       return buf.toString();
    }

Deleted: trunk/src/main/org/jboss/messaging/core/server/FlowController.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/FlowController.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/FlowController.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -1,39 +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.messaging.core.server;
-
-
-/**
- * 
- * A FlowController
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public interface FlowController
-{
-	void registerProducer(ServerProducer producer);
-	
-	void messageAcknowledged() throws Exception;
-	
-	void checkTokens(ServerProducer producer) throws Exception;
-}

Modified: trunk/src/main/org/jboss/messaging/core/server/Queue.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/Queue.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/Queue.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -21,16 +21,16 @@
   */
 package org.jboss.messaging.core.server;
 
+import java.util.LinkedList;
+import java.util.List;
+
 import org.jboss.messaging.core.filter.Filter;
-import org.jboss.messaging.core.filter.impl.FilterImpl;
 import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.postoffice.FlowController;
 import org.jboss.messaging.core.settings.HierarchicalRepository;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 
-import java.util.LinkedList;
-import java.util.List;
 
-
 /**
  * 
  * A Queue
@@ -84,7 +84,9 @@
    
    int getDeliveringCount();
    
-   void decrementDeliveringCount();
+   void referenceAcknowledged() throws Exception;
+  
+   void referenceCancelled();
    
    int getScheduledCount();
           
@@ -107,4 +109,8 @@
    int getMessagesAdded();
 
    HierarchicalRepository<QueueSettings> getQueueSettings();
+   
+   FlowController getFlowController();
+   
+   void setFlowController(FlowController flowController);
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/QueueFactory.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/QueueFactory.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/QueueFactory.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -23,8 +23,6 @@
 
 import org.jboss.messaging.core.filter.Filter;
 
-
-
 /**
  * 
  * A QueueFactory

Modified: trunk/src/main/org/jboss/messaging/core/server/ServerProducer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/ServerProducer.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/ServerProducer.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -17,7 +17,9 @@
 	
 	void send(String address, Message msg) throws Exception;
 	
-	void sendCredits(int credits) throws Exception;
+	void sendCredits() throws Exception;
 	
-	int getNumCredits();
+	void setWaiting(boolean waiting);
+	
+	boolean isWaiting();
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/ServerSession.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -106,7 +106,7 @@
    SessionCreateConsumerResponseMessage  createConsumer(String queueName, String filterString,
                      boolean noLocal, boolean autoDeleteQueue, int prefetchSize) throws Exception;
    
-   SessionCreateProducerResponseMessage createProducer(String address) throws Exception;   
+   SessionCreateProducerResponseMessage createProducer(String address, int windowSize) throws Exception;   
 
    SessionQueueQueryResponseMessage executeQueueQuery(SessionQueueQueryMessage request) throws Exception;
 

Deleted: trunk/src/main/org/jboss/messaging/core/server/impl/FlowControllerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/FlowControllerImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/FlowControllerImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -1,139 +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.messaging.core.server.impl;
-
-import java.util.List;
-
-import org.jboss.messaging.core.postoffice.Binding;
-import org.jboss.messaging.core.postoffice.PostOffice;
-import org.jboss.messaging.core.server.FlowController;
-import org.jboss.messaging.core.server.Queue;
-import org.jboss.messaging.core.server.ServerProducer;
-
-/**
- * 
- * A FlowControllerImpl
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public class FlowControllerImpl implements FlowController
-{
-	private int tokenPot;
-	
-	private final int batchSize = 50;
-	
-	private final PostOffice postOffice;
-	
-	private final int limit;
-	
-	private ServerProducer producer;
-	
-	private volatile boolean waiting;
-	
-	private final String address;
-	
-	public FlowControllerImpl(String address, PostOffice postOffice, int limit) throws Exception
-	{
-		this.address = address;
-		
-		this.postOffice = postOffice;
-		
-		this.limit = limit;
-		
-		getTokens();
-	}
-	
-	public void registerProducer(ServerProducer producer)
-	{
-		this.producer = producer;
-	}
-	
-	private void getTokens() throws Exception
-	{
-		List<Binding> bindings = postOffice.getBindingsForAddress(address);
-		
-		int minAvailable = Integer.MAX_VALUE;
-		
-		for (Binding binding: bindings)
-		{
-			Queue queue = binding.getQueue();
-			
-			int available = limit - queue.getMessageCount();
-			
-			if (available < 0)
-			{
-				available = 0;
-			}
-			
-			minAvailable = Math.min(available, minAvailable);			
-		}
-		
-      tokenPot += minAvailable;		
-	}
-		
-	public void messageAcknowledged() throws Exception
-	{
-		if (waiting)
-		{
-			getTokens();
-			
-			if (tokenPot >= batchSize)
-			{
-				tokenPot -= batchSize;
-				
-				waiting = false;
-				
-				producer.sendCredits(batchSize);
-			}			
-		}
-	}
-	
-	public void checkTokens(ServerProducer producer) throws Exception
-	{						
-		if (tokenPot < batchSize)
-		{
-			if (!waiting)
-			{
-				//Try and get some more
-				getTokens();
-				
-				if (tokenPot >= batchSize)
-				{
-					tokenPot -= batchSize;
-					
-					producer.sendCredits(batchSize);
-				}
-				else
-				{
-					waiting = true;
-				}
-			}
-		}
-		else
-		{
-			tokenPot -= batchSize;
-			
-			producer.sendCredits(batchSize);	
-		}
-	}
-}

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -37,6 +37,7 @@
 import org.jboss.messaging.core.list.impl.PriorityLinkedListImpl;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.postoffice.FlowController;
 import org.jboss.messaging.core.server.Consumer;
 import org.jboss.messaging.core.server.DistributionPolicy;
 import org.jboss.messaging.core.server.HandleStatus;
@@ -96,6 +97,8 @@
 
    private AtomicInteger deliveringCount = new AtomicInteger(0);
    
+   private volatile FlowController flowController;
+   
    public QueueImpl(final long persistenceID, final String name, final Filter filter, final boolean clustered,
                     final boolean durable, final boolean temporary, final int maxSize, final ScheduledExecutorService scheduledExecutor,
                     final HierarchicalRepository<QueueSettings> queueSettings)
@@ -117,7 +120,7 @@
       this.scheduledExecutor = scheduledExecutor;
    	
    	this.queueSettings = queueSettings;
-
+   	
       direct = true;        	
    }
    
@@ -336,12 +339,12 @@
       this.persistenceID = id;
    }
 
-   public synchronized Filter getFilter()
+   public Filter getFilter()
    {
       return filter;
    }
 
-   public synchronized void setFilter(final Filter filter)
+   public void setFilter(final Filter filter)
    {
       this.filter = filter;
    }
@@ -361,12 +364,22 @@
       return deliveringCount.get();
    }
 
-   public void decrementDeliveringCount()
+   public void referenceAcknowledged() throws Exception
    {
       deliveringCount.decrementAndGet();
+      
+      if (flowController != null)
+      {
+      	flowController.messageAcknowledged();
+      }
    }
+   
+   public void referenceCancelled()
+   {
+      deliveringCount.decrementAndGet();
+   }
 
-   public synchronized int getMaxSize()
+   public int getMaxSize()
    {
       return maxSize;
    }
@@ -379,15 +392,16 @@
       {
          throw new IllegalArgumentException("Cannot set maxSize to " + maxSize + " since there are " + num + " refs");
       }
+      
       this.maxSize = maxSize;
    }
 
-   public synchronized DistributionPolicy getDistributionPolicy()
+   public DistributionPolicy getDistributionPolicy()
    {
       return distributionPolicy;
    }
 
-   public synchronized void setDistributionPolicy(final DistributionPolicy distributionPolicy)
+   public void setDistributionPolicy(final DistributionPolicy distributionPolicy)
    {
       this.distributionPolicy = distributionPolicy;
    }
@@ -402,6 +416,16 @@
       return queueSettings;
    }
    
+   public void setFlowController(final FlowController flowController)
+   {
+   	this.flowController = flowController;
+   }
+   
+   public FlowController getFlowController()
+   {
+   	return flowController;
+   }
+   
    // Public -----------------------------------------------------------------------------
 
    public boolean equals(Object other)
@@ -519,8 +543,8 @@
    }
 
    private boolean checkFull()
-   {
-      if (maxSize != -1 && (messageReferences.size() + scheduledRunnables.size()) >= maxSize)
+   {   	
+      if (maxSize != -1 && (deliveringCount.get() + messageReferences.size() + scheduledRunnables.size()) >= maxSize)
       {
          if (trace) { log.trace(this + " queue is full, rejecting message"); }
 

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -25,10 +25,10 @@
 
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.postoffice.FlowController;
 import org.jboss.messaging.core.remoting.PacketSender;
 import org.jboss.messaging.core.remoting.impl.wireformat.Packet;
 import org.jboss.messaging.core.remoting.impl.wireformat.ProducerReceiveTokensMessage;
-import org.jboss.messaging.core.server.FlowController;
 import org.jboss.messaging.core.server.ServerProducer;
 import org.jboss.messaging.core.server.ServerSession;
 
@@ -53,11 +53,8 @@
 	
 	private final PacketSender sender;
 	
-	private volatile int numberSent;
+	private volatile boolean waiting;
 	
-	private final int batchSize = 10;
-			
-	
 	// Constructors ----------------------------------------------------------------
 	
 	public ServerProducerImpl(final ServerSession session, final String address, 
@@ -96,32 +93,32 @@
 			session.send(address, message);
 		}
 		else
-		{			
+		{						
 			session.send(this.address, message);
 			
-//			numberSent++;
-//			
-//			if (numberSent == batchSize)
-//			{
-//				numberSent = 0;
-//						
-//				flowController.checkTokens(this);
-//			}
+			if (flowController != null)
+		   {
+				flowController.messageReceived(this, 1);			
+			}
 		}
 	}
-	
-	public int getNumCredits()
-	{
-		// TODO Auto-generated method stub
-		return 0;
-	}
 
-	public void sendCredits(final int credits) throws Exception
+	public void sendCredits() throws Exception
 	{
-		Packet packet = new ProducerReceiveTokensMessage(credits);
+		Packet packet = new ProducerReceiveTokensMessage(1);
 		
 		packet.setTargetID(id);
 			
 		sender.send(packet);		
 	}
+	
+	public void setWaiting(final boolean waiting)
+	{
+		this.waiting = waiting;
+	}
+	
+	public boolean isWaiting()
+	{
+		return waiting;
+	}
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -44,6 +44,7 @@
 import org.jboss.messaging.core.message.MessageReference;
 import org.jboss.messaging.core.persistence.PersistenceManager;
 import org.jboss.messaging.core.postoffice.Binding;
+import org.jboss.messaging.core.postoffice.FlowController;
 import org.jboss.messaging.core.postoffice.PostOffice;
 import org.jboss.messaging.core.remoting.PacketDispatcher;
 import org.jboss.messaging.core.remoting.PacketSender;
@@ -58,7 +59,6 @@
 import org.jboss.messaging.core.security.CheckType;
 import org.jboss.messaging.core.security.SecurityStore;
 import org.jboss.messaging.core.server.Delivery;
-import org.jboss.messaging.core.server.FlowController;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.ServerConnection;
 import org.jboss.messaging.core.server.ServerConsumer;
@@ -333,6 +333,7 @@
 
    public synchronized void acknowledge(final long deliveryID, final boolean allUpTo) throws Exception
    {
+   	//log.info("acknowledge called " + deliveryID + " all " + allUpTo);
       // Note that we do not consider it an error if the deliveries cannot be found to be acked.
    	// This can legitimately occur if a connection/session/consumer is closed
       // from inside a MessageHandlers onMessage method. In this situation the close will cancel any unacked
@@ -418,6 +419,7 @@
 
    public void rollback() throws Exception
    {
+   	//log.info("Roll back called");
       if (tx == null)
       {
          // Might be null if XA
@@ -428,9 +430,8 @@
       // Synchronize to prevent any new deliveries arriving during this recovery
       synchronized (this)
       {
-         // Add any unacked deliveries into the tx
-         // Doing this ensures all references are rolled back in the correct
-         // orderin a single contiguous block
+         // Add any unacked deliveries into the tx. Doing this ensures all references are rolled back in the correct
+         // order in a single contiguous block
 
          for (Delivery del : deliveries)
          {
@@ -1000,19 +1001,32 @@
       return new SessionCreateBrowserResponseMessage(browser.getID());
    }
    
-   public SessionCreateProducerResponseMessage createProducer(final String address) throws Exception
+   /**
+    * Create a producer for the specified address
+    * @param address The address to produce too
+    * @param windowSize - the producer window size to use for flow control.
+    * Specify -1 to disable flow control completely
+    * The actual window size used may be less than the specified window size if the queue's maxSize attribute
+    * is set and there are not sufficient empty spaces in the queue
+    */
+   public SessionCreateProducerResponseMessage createProducer(final String address, final int windowSize) throws Exception
    { 	
-   	//FlowController flowController = new FlowControllerImpl(address, postOffice, 10);		
+   	FlowController flowController = null;
    	
-   	ServerProducerImpl producer = new ServerProducerImpl(this, address, sender, null);
+   	if (address != null)
+   	{
+   		flowController = windowSize == -1 ? null : postOffice.getFlowController(address);
+   	}
    	
+   	ServerProducerImpl producer = new ServerProducerImpl(this, address, sender, flowController);
+
    	producers.put(producer.getID(), producer);
    	
    	dispatcher.register(new ServerProducerPacketHandler(producer));
    	
-   	int initialTokens = 10;
-   	
-   	return new SessionCreateProducerResponseMessage(producer.getID(), initialTokens);
+   	int windowToUse = flowController == null ? -1 : flowController.getInitialTokens(windowSize, producer);
+   	   	   	
+   	return new SessionCreateProducerResponseMessage(producer.getID(), windowToUse);
    }
    
    // Public ---------------------------------------------------------------------------------------------

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -131,7 +131,7 @@
       case SESS_CREATEPRODUCER:
       {
          SessionCreateProducerMessage request = (SessionCreateProducerMessage) packet;
-         response = session.createProducer(request.getAddress());
+         response = session.createProducer(request.getAddress(), request.getWindowSize());
          break;
       }
       case CLOSE:

Modified: trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -27,8 +27,6 @@
 import org.jboss.messaging.core.message.MessageReference;
 import org.jboss.messaging.core.persistence.PersistenceManager;
 
-
-
 /**
  * 
  * A JBoss Messaging internal transaction

Modified: trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -145,7 +145,7 @@
       
       for (MessageReference reference: acknowledgements)
       {
-         reference.getQueue().decrementDeliveringCount();
+         reference.getQueue().referenceAcknowledged();
       }
       
       callSynchronizations(SyncType.AFTER_COMMIT);

Modified: trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -35,9 +35,15 @@
 
    Set<String> listTemporaryDestinations();
 
-   boolean createConnectionFactory(String name, String clientID, int dupsOKBatchSize, boolean strictTck, int prefetchSize, String jndiBinding) throws Exception;
+   boolean createConnectionFactory(String name, String clientID,
+   		                          int dupsOKBatchSize, boolean strictTck, int prefetchSize,
+   		                          int producerWindowSize, int producerMaxRate,
+   		                          String jndiBinding) throws Exception;
 
-   boolean createConnectionFactory(String name, String clientID, int dupsOKBatchSize, boolean strictTck, int prefetchSize, List<String> jndiBindings) throws Exception;
+   boolean createConnectionFactory(String name, String clientID, int dupsOKBatchSize,
+   		                          boolean strictTck, int prefetchSize,
+   		                          int producerWindowSize, int producerMaxRate,
+   		                          List<String> jndiBindings) throws Exception;
 
    boolean destroyConnectionFactory(String name) throws Exception;
 

Modified: trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -43,7 +43,9 @@
 
    private static final String CLIENTID_ELEMENT = "client-id";
    private static final String DUPS_OK_BATCH_SIZE_ELEMENT = "dups-ok-batch-size";
-   private static final String PREFETECH_SIZE_ELEMENT = "prefetch-size";
+   private static final String PREFETCH_SIZE_ELEMENT = "prefetch-size";
+   private static final String PRODUCER_WINDOW_SIZE = "producer-window-size";
+   private static final String PRODUCER_MAX_RATE = "producer-max-rate";
    private static final String SUPPORTS_FAILOVER = "supports-failover";
    private static final String SUPPORTS_LOAD_BALANCING = "supports-load-balancing";
    private static final String LOAD_BALANCING_FACTORY = "load-balancing-factory";
@@ -124,16 +126,26 @@
          int prefetchSize = 150;
          String clientID = null;
          int dupsOKBatchSize = 1000;
+         int producerWindowSize = 1000;
+         int producerMaxRate = -1;
          for (int j = 0; j < attributes.getLength(); j++)
          {
             if (STRICT_TCK.equalsIgnoreCase(attributes.item(j).getNodeName()))
             {
                cfStrictTck = Boolean.parseBoolean(attributes.item(j).getTextContent().trim());
             }
-            else if (PREFETECH_SIZE_ELEMENT.equalsIgnoreCase(attributes.item(j).getNodeName()))
+            else if (PREFETCH_SIZE_ELEMENT.equalsIgnoreCase(attributes.item(j).getNodeName()))
             {
                prefetchSize = Integer.parseInt(attributes.item(j).getTextContent().trim());
             }
+            else if (PRODUCER_WINDOW_SIZE.equalsIgnoreCase(attributes.item(j).getNodeName()))
+            {
+               producerWindowSize = Integer.parseInt(attributes.item(j).getTextContent().trim());
+            }
+            else if (PRODUCER_MAX_RATE.equalsIgnoreCase(attributes.item(j).getNodeName()))
+            {
+               producerMaxRate = Integer.parseInt(attributes.item(j).getTextContent().trim());
+            }
             else if (CLIENTID_ELEMENT.equalsIgnoreCase(attributes.item(j).getNodeName()))
             {
                clientID = attributes.item(j).getTextContent();
@@ -163,9 +175,13 @@
 
             if (ENTRY_NODE_NAME.equalsIgnoreCase(children.item(i).getNodeName()))
             {
+            	
+            	log.info("CReating cf ** with ws:" + producerWindowSize);
+            	
                String jndiName = child.getAttributes().getNamedItem("name").getNodeValue();
                String name = node.getAttributes().getNamedItem(getKeyAttribute()).getNodeValue();
-               jmsServerManager.createConnectionFactory(name, clientID, dupsOKBatchSize, cfStrictTck, prefetchSize, jndiName);
+               jmsServerManager.createConnectionFactory(name, clientID, dupsOKBatchSize, cfStrictTck,
+               		prefetchSize, producerWindowSize, producerMaxRate, jndiName);
             }
          }
       }

Modified: trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -241,12 +241,17 @@
       return tempDests;
    }
 
-   public boolean createConnectionFactory(String name, String clientID, int dupsOKBatchSize, boolean strictTck, int prefetchSize, String jndiBinding) throws Exception
+   public boolean createConnectionFactory(String name, String clientID,
+   		int dupsOKBatchSize, boolean strictTck, int prefetchSize,
+   		int producerWindowSize, int producerMaxRate, String jndiBinding) throws Exception
    {
       JBossConnectionFactory cf = connectionFactories.get(name);
       if (cf == null)
       {
-         ClientConnectionFactory clientConnectionFactory = messagingServerManagement.createClientConnectionFactory(strictTck, prefetchSize);
+      	log.info("^^^ creating cf with qws:" + producerWindowSize);
+      	
+         ClientConnectionFactory clientConnectionFactory =
+         	messagingServerManagement.createClientConnectionFactory(strictTck, prefetchSize, producerWindowSize, producerMaxRate);
          log.debug(this + " created local connectionFactory " + clientConnectionFactory);
          cf = new JBossConnectionFactory(clientConnectionFactory, clientID, dupsOKBatchSize);
       }
@@ -263,12 +268,16 @@
    }
 
 
-   public boolean createConnectionFactory(String name, String clientID, int dupsOKBatchSize, boolean strictTck, int prefetchSize, List<String> jndiBindings) throws Exception
+   public boolean createConnectionFactory(String name, String clientID, int dupsOKBatchSize,
+   		                                 boolean strictTck, int prefetchSize,
+   		                                 int producerWindowSize, int producerMaxRate,
+   		                                 List<String> jndiBindings) throws Exception
    {
       JBossConnectionFactory cf = connectionFactories.get(name);
       if (cf == null)
       {
-         ClientConnectionFactory clientConnectionFactory = messagingServerManagement.createClientConnectionFactory(strictTck, prefetchSize);
+         ClientConnectionFactory clientConnectionFactory =
+         	messagingServerManagement.createClientConnectionFactory(strictTck, prefetchSize, producerWindowSize, producerMaxRate);
          log.debug(this + " created local connectionFactory " + clientConnectionFactory);
          cf = new JBossConnectionFactory(clientConnectionFactory, clientID, dupsOKBatchSize);
       }

Added: trunk/src/main/org/jboss/messaging/util/TokenBucketLimiter.java
===================================================================
--- trunk/src/main/org/jboss/messaging/util/TokenBucketLimiter.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/util/TokenBucketLimiter.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,115 @@
+/*
+  * 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.util;
+
+/**
+ * 
+ * A TokenBucketLimiter
+ * 
+ * This class can throttle to a specfic rate, using an algorithm based on the Token Bucket metaphor
+ * http://en.wikipedia.org/wiki/Token_bucket
+ * 
+ * The rate is specified in Hertz
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class TokenBucketLimiter
+{
+	private final int rate;
+	
+	private final boolean spin;
+		
+	private volatile long last;
+	
+	private volatile int tokens;
+	
+	private volatile int tokensAdded;
+		
+	public TokenBucketLimiter(final int rate, final boolean spin)
+	{
+		this.rate = rate;
+		
+		this.spin = spin;
+	}
+		
+	public void limit()
+	{			
+		while (!check())
+		{
+			if (!spin)
+			{
+   			try
+   			{
+   				Thread.sleep(1);
+   			}
+   			catch (Exception e)
+   			{			
+   				//Ignore
+   			}
+			}
+		}
+	}
+	
+	private boolean check()
+	{					
+		long now = System.currentTimeMillis();
+		
+		if (last == 0)
+		{
+			last = now;
+		}
+		
+		long diff = now - last;
+		
+		if (diff >= 1000)
+		{
+			last = last + 1000;
+			
+			tokens = 0;
+			
+			tokensAdded = 0;
+		}
+														
+		int tokensDue = (int)(rate * (diff)  / 1000);
+		
+		int tokensToAdd = tokensDue - tokensAdded;
+		
+		if (tokensToAdd > 0)
+		{
+			tokens += tokensToAdd;
+			
+			tokensAdded += tokensToAdd;
+		}
+							
+		if (tokens > 0)
+		{
+			tokens--;
+			
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}	
+}

Modified: trunk/tests/etc/log4j.xml
===================================================================
--- trunk/tests/etc/log4j.xml	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/etc/log4j.xml	2008-03-04 14:08:59 UTC (rev 3839)
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
-<!-- $Id: log4j.xml 1184 2006-08-03 18:52:12Z ovidiu.feodorov at jboss.com $ -->
+<!-- $Id: log4j.xml 1019 2006-07-17 17:15:04Z timfox $ -->
 
 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
 
@@ -14,8 +14,9 @@
           "crash-server", etc.
       -->
       <param name="File" value="${module.output}/logs/messaging-${test.logfile.suffix}.log"/>
+
       <param name="DatePattern" value="'.'yyyy-MM-dd"/>
-      <param name="Threshold" value="TRACE#org.jboss.logging.XLevel"/>
+      <param name="Threshold" value="INFO"/>
 
       <!-- since majority of the tests are ran in fork mode by ant, the log file is overwritten
            for each test. We need to append if we want to preserve a full testsuite run log.
@@ -31,54 +32,24 @@
    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
       <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
       <param name="Target" value="System.out"/>
-      <param name="Threshold" value="INFO"/>
+      <param name="Threshold" value="TRACE"/>
       <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%t %d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
       </layout>
    </appender>
 
-   <category name="com.arjuna">
-      <priority value="TRACE" class="org.jboss.logging.XLevel"/>
-   </category>
-
    <category name="org.apache">
       <priority value="INFO"/>
    </category>
 
    <category name="org.jgroups">
-      <priority value="WARN"/>
+      <priority value="TRACE"/>
    </category>
 
    <category name="org.jboss">
       <priority value="INFO"/>
    </category>
 
-   <category name="org.jboss.messaging">
-      <priority value="TRACE" class="org.jboss.logging.XLevel"/>
-   </category>
-
-   <category name="org.jboss.jms">
-      <priority value="TRACE" class="org.jboss.logging.XLevel"/>
-   </category>
-
-   <category name="org.jboss.test">
-      <priority value="TRACE" class="org.jboss.logging.XLevel"/>
-   </category>
-
-   <!-- Ignoring trace from these: -->
-
-   <category name="org.jboss.messaging.jms.server.remoting.JMSServerInvocationHandler">
-      <priority value="DEBUG"/>
-   </category>
-
-   <category name="org.jboss.test.messaging.tools.container.MockJBossSecurityManager">
-      <priority value="DEBUG"/>
-   </category>
-
-   <category name="org.jboss.jms.wireformat.JMSWireFormat">
-      <priority value="DEBUG"/>
-   </category>
-
    <root>
       <appender-ref ref="CONSOLE"/>
       <appender-ref ref="FILE"/>

Copied: trunk/tests/src/org/jboss/messaging/core/message/impl/test/unit/MessageTest.java (from rev 3827, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessageTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/message/impl/test/unit/MessageTest.java	                        (rev 0)
+++ trunk/tests/src/org/jboss/messaging/core/message/impl/test/unit/MessageTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,423 @@
+/*
+ * 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.message.impl.test.unit;
+
+import static org.jboss.messaging.test.unit.RandomUtil.randomByte;
+import static org.jboss.messaging.test.unit.RandomUtil.randomInt;
+import static org.jboss.messaging.test.unit.RandomUtil.randomLong;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.message.impl.MessageImpl;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.core.server.impl.test.unit.fakes.FakeQueueFactory;
+import org.jboss.messaging.test.unit.UnitTestCase;
+import org.jboss.messaging.util.StreamUtils;
+
+/**
+ * 
+ * Tests for Message and MessageReference
+ * 
+ * TODO - Test streaming and destreaming
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class MessageTest extends UnitTestCase
+{
+	private QueueFactory queueFactory = new FakeQueueFactory();
+   
+   public void testCreateMessage()
+   {
+      long id = 56465;
+      int type = 655;
+      boolean reliable = true;
+      long expiration = 6712671;
+      long timestamp = 82798172;
+      byte priority = 32;
+      
+      Message message = new MessageImpl(type, reliable, expiration, timestamp, priority);
+      message.setMessageID(id);
+      
+      assertEquals(id, message.getMessageID());
+      assertEquals(type, message.getType());
+      assertEquals(reliable, message.isDurable());
+      assertEquals(timestamp, message.getTimestamp());
+      assertEquals(priority, message.getPriority());
+      
+      reliable = false;
+      
+      message = new MessageImpl(type, reliable, expiration, timestamp, priority);
+      message.setMessageID(id);
+      
+      assertEquals(id, message.getMessageID());
+      assertEquals(type, message.getType());
+      assertEquals(reliable, message.isDurable());
+      assertEquals(timestamp, message.getTimestamp());
+      assertEquals(priority, message.getPriority());
+   }
+   
+   public void testCreateMessageFromStorage() throws Exception
+   {
+      long id = 56465;
+      int type = 655;
+      boolean reliable = true;
+      long expiration = 6712671;
+      long timestamp = 82798172;
+      byte priority = 32;
+      
+      byte[] bytes = "blah blah blah".getBytes();
+ 
+      Message message = new MessageImpl(id, type, reliable, expiration, timestamp, priority,
+            null, bytes);
+      
+      assertEquals(id, message.getMessageID());
+      assertEquals(type, message.getType());
+      assertEquals(reliable, message.isDurable());
+      assertEquals(timestamp, message.getTimestamp());
+      assertEquals(priority, message.getPriority());     
+      
+      assertByteArraysEquivalent(bytes, message.getPayload());   
+      
+      //TODO - headers - they should really be combined into single blob
+   }
+   
+   public void testCopy()
+   {
+      long id = 56465;
+      int type = 655;
+      boolean reliable = true;
+      long expiration = 6712671;
+      long timestamp = 82798172;
+      byte priority = 32;
+      
+      Message message = new MessageImpl(type, reliable, expiration, timestamp, priority);
+      message.setMessageID(id);
+      
+      Message message2 = message.copy();
+      
+      assertEquivalent(message, message2);
+   }
+   
+   public void testSetAndGetMessageID()
+   {
+      Message message = new MessageImpl();
+      
+      assertEquals(0, message.getMessageID());
+      
+      message = new MessageImpl(655, true, 767676, 989898, (byte)32);
+      
+      assertEquals(0, message.getMessageID());
+      
+      long id = 765432;
+      message.setMessageID(id);
+      assertEquals(id, message.getMessageID());
+   }
+   
+   public void testSetAndGetReliable()
+   {
+      Message message = new MessageImpl();
+      
+      boolean reliable = true;
+      message.setDurable(reliable);
+      assertEquals(reliable, message.isDurable());
+      
+      reliable = false;
+      message.setDurable(reliable);
+      assertEquals(reliable, message.isDurable());
+   }
+    
+   public void testSetAndGetExpiration()
+   {
+      Message message = new MessageImpl();
+      
+      long expiration = System.currentTimeMillis() + 10000;
+      message.setExpiration(expiration);
+      assertEquals(expiration, message.getExpiration());
+      assertFalse(message.isExpired());
+      message.setExpiration(System.currentTimeMillis() - 1);
+      assertTrue(message.isExpired());
+      
+      expiration = 0; //O means never expire
+      message.setExpiration(expiration);
+      assertEquals(expiration, message.getExpiration());
+      assertFalse(message.isExpired());
+   }
+      
+   public void testSetAndGetTimestamp()
+   {
+      Message message = new MessageImpl();
+      
+      long timestamp = System.currentTimeMillis();
+      message.setTimestamp(timestamp);
+      assertEquals(timestamp, message.getTimestamp());
+   }
+   
+   public void testSetAndGetPriority()
+   {
+      Message message = new MessageImpl();
+      byte priority = 7;
+      message.setPriority(priority);
+      assertEquals(priority, message.getPriority());
+   }
+   
+   public void testSetAndGetConnectionID()
+   {
+      Message message = new MessageImpl();
+      
+      assertNull(message.getConnectionID());
+      String connectionID = "conn123";
+      message.setConnectionID(connectionID);
+      assertEquals(connectionID, message.getConnectionID());      
+   }
+   
+   public void testSetAndGetPayload()
+   {
+      Message message = new MessageImpl();
+      
+      assertNull(message.getPayload());
+      
+      byte[] bytes = "blah blah blah".getBytes();
+      message.setPayload(bytes);
+      
+      assertByteArraysEquivalent(bytes, message.getPayload());            
+   }
+   
+   public void testHeaders()
+   {
+      Message message = new MessageImpl();
+      
+      assertNotNull(message.getHeaders());
+      assertTrue(message.getHeaders().isEmpty());
+      
+      String key1 = "key1";
+      String val1 = "wibble";
+      String key2 = "key2";
+      Object val2 = new Object();
+      String key3 = "key3";
+      Double val3 = new Double(123.456);
+      Long val4 = new Long(77777);
+      message.putHeader(key1, val1);
+      assertEquals(val1, message.getHeaders().get(key1));
+      assertEquals(1, message.getHeaders().size());
+      assertTrue(message.containsHeader(key1));
+      assertFalse(message.containsHeader("does not exist"));
+      message.putHeader(key2, val2);
+      assertEquals(val2, message.getHeaders().get(key2));
+      assertEquals(2, message.getHeaders().size());
+      assertTrue(message.containsHeader(key2));
+      message.putHeader(key3, val3);
+      assertEquals(val3, message.getHeaders().get(key3));
+      assertEquals(3, message.getHeaders().size());
+      assertTrue(message.containsHeader(key3));
+      message.putHeader(key3, val4);
+      assertEquals(val4, message.getHeaders().get(key3));
+      assertEquals(3, message.getHeaders().size());
+      assertEquals(val2, message.removeHeader(key2));
+      assertEquals(2, message.getHeaders().size());
+      assertFalse(message.containsHeader(key2));
+      assertNull(message.removeHeader("does not exist"));
+      assertEquals(val1, message.removeHeader(key1));
+      assertFalse(message.containsHeader(key2));
+      assertEquals(1, message.getHeaders().size());
+      assertEquals(val4, message.removeHeader(key3));
+      assertFalse(message.containsHeader(key3));
+      assertTrue(message.getHeaders().isEmpty());
+   }
+   
+   public void testEquals()
+   {
+      Message message1 = new MessageImpl();
+      message1.setMessageID(1);
+      
+      Message message2 = new MessageImpl();
+      message2.setMessageID(2);
+      
+      Message message3 = new MessageImpl();
+      message3.setMessageID(1);
+      
+      assertTrue(message1.equals(message1));
+      assertTrue(message2.equals(message2));
+      assertTrue(message3.equals(message3));
+      
+      assertFalse(message1.equals(message2));
+      assertFalse(message2.equals(message1));
+      
+      assertFalse(message2.equals(message3));
+      assertFalse(message3.equals(message2));
+      
+      assertTrue(message1.equals(message3));
+      assertTrue(message3.equals(message1));
+      
+   }
+   
+   public void testHashcode()
+   {
+      long id1 = 6567575;
+      Message message1 = new MessageImpl();
+      message1.setMessageID(id1);
+      
+      assertEquals((int) ((id1 >>> 32) ^ id1), message1.hashCode());
+   }
+   
+   public void testMessageReference()
+   {
+      Message message = new MessageImpl();
+      
+      assertTrue(message.getReferences().isEmpty());
+      
+      Queue queue1 = queueFactory.createQueue(1, "queue1", null, false, true);
+      Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, true);
+
+      List<MessageReference> refs = new ArrayList<MessageReference>();
+      
+      MessageReference ref1 = message.createReference(queue1);
+      refs.add(ref1);
+      MessageReference ref2 = message.createReference(queue2);
+      refs.add(ref2);
+      MessageReference ref3 = message.createReference(queue1);
+      refs.add(ref3);
+      MessageReference ref4 = message.createReference(queue2);
+      refs.add(ref4);
+      
+      assertRefListsIdenticalRefs(refs, message.getReferences());
+      
+      assertEquals(queue1, ref1.getQueue());
+      assertEquals(queue2, ref2.getQueue());
+      assertEquals(queue1, ref3.getQueue());
+      assertEquals(queue2, ref4.getQueue());
+      
+      int deliveryCount = 65235;
+      ref1.setDeliveryCount(deliveryCount);
+      assertEquals(deliveryCount, ref1.getDeliveryCount());
+      
+      long scheduledDeliveryTime = 908298123;
+      ref1.setScheduledDeliveryTime(scheduledDeliveryTime);
+      assertEquals(scheduledDeliveryTime, ref1.getScheduledDeliveryTime());
+      
+      Queue queue3 = queueFactory.createQueue(3, "queue3", null, false, true);
+      MessageReference ref5 = ref1.copy(queue3);
+      
+      assertEquals(deliveryCount, ref5.getDeliveryCount());
+      assertEquals(scheduledDeliveryTime, ref5.getScheduledDeliveryTime());
+      assertEquals(queue3, ref5.getQueue());
+   }
+   
+
+   public void testDurableReferences()
+   {
+      Message messageDurable = new MessageImpl();
+      messageDurable.setDurable(true);
+      
+      Message messageNonDurable = new MessageImpl();
+      messageNonDurable.setDurable(false);
+        
+      //Durable queue
+      Queue queue1 = queueFactory.createQueue(1, "queue1", null, true, false);
+      
+      //Non durable queue
+      Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, false);
+      
+      assertEquals(0, messageDurable.getNumDurableReferences());
+      
+      MessageReference ref1 = messageDurable.createReference(queue1);
+      
+      assertEquals(1, messageDurable.getNumDurableReferences());
+      
+      MessageReference ref2 = messageDurable.createReference(queue2);
+      
+      assertEquals(1, messageDurable.getNumDurableReferences());
+      
+      assertEquals(0, messageNonDurable.getNumDurableReferences());
+      
+      MessageReference ref3 = messageNonDurable.createReference(queue1);
+      
+      assertEquals(0, messageNonDurable.getNumDurableReferences());
+      
+      MessageReference ref4 = messageNonDurable.createReference(queue2);
+      
+      assertEquals(0, messageNonDurable.getNumDurableReferences());
+                  
+   }
+   
+   public void testDurableReferencePos()
+   {
+      Message messageDurable = new MessageImpl();
+      messageDurable.setDurable(true);
+      
+      //Durable queue
+      Queue queue1 = queueFactory.createQueue(1, "queue1", null, true, false);
+      
+      //Non durable queue
+      Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, false);
+      
+      
+      MessageReference ref1 = messageDurable.createReference(queue1);
+      
+      MessageReference ref2 = messageDurable.createReference(queue2);
+      
+      MessageReference ref3 = messageDurable.createReference(queue2);
+      
+      MessageReference ref4 = messageDurable.createReference(queue1);
+      
+      MessageReference ref5 = messageDurable.createReference(queue1);
+      
+      MessageReference ref6 = messageDurable.createReference(queue2);
+      
+      MessageReference ref7 = messageDurable.createReference(queue1);
+      
+      MessageReference ref8 = messageDurable.createReference(queue2);
+      
+      assertEquals(0, messageDurable.getDurableReferencePos(ref1));
+      
+      assertEquals(1, messageDurable.getDurableReferencePos(ref4));
+      
+      assertEquals(2, messageDurable.getDurableReferencePos(ref5));
+      
+      assertEquals(3, messageDurable.getDurableReferencePos(ref7));
+             
+   }
+   
+   public void testMarshalling() throws Exception
+   {
+      Message msg = new MessageImpl(randomLong(), randomInt(), true, randomLong(), randomLong(), randomByte(),null, null);
+      msg.setDeliveryCount(randomInt());
+      
+      byte[] bytes = StreamUtils.toBytes(msg);
+      Message unmarshalledMsg = new MessageImpl();
+      StreamUtils.fromBytes(unmarshalledMsg, bytes);
+      
+      assertEquals(msg, unmarshalledMsg);
+      assertEquals("messageID", msg.getMessageID(), unmarshalledMsg.getMessageID());
+      assertEquals("type", msg.getType(), unmarshalledMsg.getType());
+      assertEquals("durable", msg.isDurable(), unmarshalledMsg.isDurable());
+      assertEquals("expiration", msg.getExpiration(), unmarshalledMsg.getExpiration());
+      assertEquals("timestamp", msg.getTimestamp(), unmarshalledMsg.getTimestamp());
+      assertEquals("priority", msg.getPriority(), unmarshalledMsg.getPriority());
+      assertEquals("deliveryCount", msg.getDeliveryCount(), unmarshalledMsg.getDeliveryCount()); 
+   }
+   
+}

Copied: trunk/tests/src/org/jboss/messaging/core/postoffice/impl/test/unit/PostOfficeTest.java (from rev 3827, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/PostOfficeTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/postoffice/impl/test/unit/PostOfficeTest.java	                        (rev 0)
+++ trunk/tests/src/org/jboss/messaging/core/postoffice/impl/test/unit/PostOfficeTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,262 @@
+/*
+ * 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.postoffice.impl.test.unit;
+
+import java.util.List;
+import java.util.Map;
+
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.filter.Filter;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.persistence.PersistenceManager;
+import org.jboss.messaging.core.postoffice.Binding;
+import org.jboss.messaging.core.postoffice.PostOffice;
+import org.jboss.messaging.core.postoffice.impl.BindingImpl;
+import org.jboss.messaging.core.postoffice.impl.PostOfficeImpl;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.core.server.impl.test.unit.fakes.FakeQueueFactory;
+import org.jboss.messaging.test.unit.UnitTestCase;
+
+/**
+ * 
+ * A PostOfficeTest
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class PostOfficeTest extends UnitTestCase
+{
+	private QueueFactory queueFactory = new FakeQueueFactory();
+   
+   public void testAddQueue() throws Exception
+   {
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      QueueFactory qf = EasyMock.createStrictMock(QueueFactory.class);
+      
+      final int nodeID = 21;
+      
+      PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
+      
+      final long id = 324;
+      final String name = "wibb22";
+      final Filter filter = new FakeFilter();
+      final boolean durable = true;
+      final boolean temporary = true;
+      
+      Queue queue = queueFactory.createQueue(id, name, filter, durable, temporary);
+      
+      EasyMock.expect(qf.createQueue(-1, name, filter, durable, temporary)).andReturn(queue);
+            
+      final String condition = "queue.wibble";
+
+      Binding expected = new BindingImpl(nodeID, condition, queue);
+      
+      pm.addBinding(EasyMock.eq(expected));
+      
+      EasyMock.replay(qf);
+      
+      EasyMock.replay(pm);
+      
+      po.addBinding(condition, name, filter, durable, temporary);
+      
+      EasyMock.verify(qf);
+      
+      EasyMock.verify(pm);
+      
+      EasyMock.reset(qf);
+      
+      EasyMock.reset(pm);
+      
+      final boolean durable2 = false;
+      
+      queue = queueFactory.createQueue(id, name, filter, durable2, temporary);
+      
+      EasyMock.expect(qf.createQueue(-1, name, filter, durable2, temporary)).andReturn(queue);
+      
+      EasyMock.replay(qf);
+      
+      EasyMock.replay(pm);      
+   }   
+   
+   public void testRemoveQueue() throws Exception
+   {
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      QueueFactory qf = EasyMock.createStrictMock(QueueFactory.class);
+      
+      final int nodeID = 21;
+      
+      PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
+      
+      final long id = 324;
+      final String name = "wibb22";
+      final Filter filter = new FakeFilter();
+      final boolean durable = true;
+      final boolean temporary = true;
+      
+      Queue queue = queueFactory.createQueue(id, name, filter, durable, temporary);
+      
+      EasyMock.expect(qf.createQueue(-1, name, filter, durable, temporary)).andReturn(queue);
+            
+      final String condition = "queue.wibble";
+ 
+      Binding expected = new BindingImpl(nodeID, condition, queue);
+      
+      pm.addBinding(EasyMock.eq(expected));
+      
+      pm.deleteBinding(EasyMock.eq(expected));
+      
+      EasyMock.replay(qf);
+      
+      EasyMock.replay(pm);
+      
+      po.addBinding(condition, name, filter, durable, temporary);
+      
+      po.removeBinding(name);
+      
+      EasyMock.verify(qf);
+      
+      EasyMock.verify(pm);
+      
+      EasyMock.reset(qf);
+      
+      EasyMock.reset(pm);
+      
+      final boolean durable2 = false;
+      
+      queue = queueFactory.createQueue(id, name, filter, durable2, temporary);
+      
+      EasyMock.expect(qf.createQueue(-1, name, filter, durable2, temporary)).andReturn(queue);
+      
+      EasyMock.replay(qf);
+      
+      EasyMock.replay(pm);
+      
+      po.addBinding(condition, name, filter, durable2, temporary);
+      
+      po.removeBinding(name);
+      
+      EasyMock.verify(qf);
+      
+      EasyMock.verify(pm);
+   }   
+   
+   public void testAddRemoveMultipleWithDifferentConditions() throws Exception
+   {
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      QueueFactory qf = new FakeQueueFactory();
+      
+      final int nodeID = 21;
+      
+      PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
+      
+      final String condition1 = "queue.wibble";      
+                
+      po.addBinding(condition1, "queue1", null, false, false);      
+      Map<String, List<Binding>> mappings = po.getMappings();      
+      assertEquals(1, mappings.size());
+      
+      po.addBinding(condition1, "queue2", null, false, false);     
+      mappings = po.getMappings();      
+      assertEquals(1, mappings.size());
+      
+      po.addBinding(condition1, "queue3", null, false, false); 
+      mappings = po.getMappings();      
+      assertEquals(1, mappings.size());
+      
+      List<Binding> bindings = mappings.get(condition1);
+      assertNotNull(bindings);
+      assertEquals(3, bindings.size());
+      
+      Binding binding1 = bindings.get(0);
+      Queue queue1 = binding1.getQueue();
+      assertEquals("queue1", queue1.getName());
+            
+      Binding binding2 = bindings.get(1);
+      Queue queue2 = binding2.getQueue();
+      assertEquals("queue2", queue2.getName());
+      
+      Binding binding3 = bindings.get(2);
+      Queue queue3 = binding3.getQueue();
+      assertEquals("queue3", queue3.getName());
+      
+      final String condition2 = "queue.wibble2"; 
+      
+      po.addBinding(condition2, "queue4", null, false, false);       
+      mappings = po.getMappings();      
+      assertEquals(2, mappings.size());
+      
+      po.addBinding(condition2, "queue5", null, false, false); 
+      mappings = po.getMappings();      
+      assertEquals(2, mappings.size());
+      
+      final String condition3 = "topic.wibblexyz"; 
+      
+      po.addBinding(condition3, "queue6", null, false, false);       
+      mappings = po.getMappings();      
+      assertEquals(3, mappings.size());
+      
+      po.removeBinding("queue6");
+      mappings = po.getMappings();      
+      assertEquals(2, mappings.size());
+      
+      po.removeBinding("queue4");
+      mappings = po.getMappings();      
+      assertEquals(2, mappings.size());
+      
+      po.removeBinding("queue5");
+      mappings = po.getMappings();      
+      assertEquals(1, mappings.size());
+      
+      po.removeBinding("queue1");
+      mappings = po.getMappings();      
+      assertEquals(1, mappings.size());
+      
+      po.removeBinding("queue2");
+      mappings = po.getMappings();      
+      assertEquals(1, mappings.size());
+      
+      po.removeBinding("queue3");
+      mappings = po.getMappings();      
+      assertEquals(0, mappings.size());      
+   }
+
+   
+   
+   
+   class FakeFilter implements Filter
+   {
+		public String getFilterString()
+		{
+			return "aardvark";
+		}
+
+		public boolean match(Message message)
+		{
+			return true;
+		}
+   	
+   }
+}

Modified: trunk/tests/src/org/jboss/messaging/core/remoting/impl/wireformat/test/unit/PacketTypeTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/remoting/impl/wireformat/test/unit/PacketTypeTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/remoting/impl/wireformat/test/unit/PacketTypeTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -618,12 +618,13 @@
    public void testCreateProducerRequest() throws Exception
    {      
       String destination = "queue.testCreateProducerRequest";
-      SessionCreateProducerMessage request = new SessionCreateProducerMessage(destination);
+      int windowSize = randomInt();
+      SessionCreateProducerMessage request = new SessionCreateProducerMessage(destination, windowSize);
 
       AbstractPacketCodec codec = new SessionCreateProducerMessageCodec();
       SimpleRemotingBuffer buffer = encode(request, codec);
       checkHeader(buffer, request);
-      checkBody(buffer, request.getAddress());
+      checkBody(buffer, request.getAddress(), request.getWindowSize());
       buffer.rewind();
 
       Packet decodedPacket = codec.decode(buffer);
@@ -632,6 +633,7 @@
       SessionCreateProducerMessage decodedRequest = (SessionCreateProducerMessage) decodedPacket;
       assertEquals(SESS_CREATEPRODUCER, decodedRequest.getType());
       assertEquals(request.getAddress(), decodedRequest.getAddress());
+      assertEquals(request.getWindowSize(), decodedRequest.getWindowSize());
    }
    
    public void testCreateProducerResponse() throws Exception
@@ -642,7 +644,7 @@
       AbstractPacketCodec codec = new SessionCreateProducerResponseMessageCodec();
       SimpleRemotingBuffer buffer = encode(response, codec);
       checkHeader(buffer, response);
-      checkBody(buffer, response.getProducerID(), response.getInitialTokens());
+      checkBody(buffer, response.getProducerID(), response.getWindowSize());
       buffer.rewind();
 
       Packet decodedPacket = codec.decode(buffer);
@@ -651,7 +653,7 @@
       SessionCreateProducerResponseMessage decodedResponse = (SessionCreateProducerResponseMessage) decodedPacket;
       assertEquals(SESS_CREATEPRODUCER_RESP, decodedResponse.getType());
       assertEquals(response.getProducerID(), decodedResponse.getProducerID());
-      assertEquals(response.getInitialTokens(), decodedResponse.getInitialTokens());
+      assertEquals(response.getWindowSize(), decodedResponse.getWindowSize());
    }
 
    public void testStartConnectionMessage() throws Exception

Modified: trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSL.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSL.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSL.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -80,8 +80,7 @@
          // FIXME there should be another way to get a meaningful Version on the
          // client side...
          MessagingServer server = new MessagingServerImpl();
-         ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0,
-               remotingConf, server.getVersion(), false, 0);
+         ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, remotingConf, server.getVersion());
          ClientConnection conn = cf.createConnection(null, null);
          ClientSession session = conn.createClientSession(false, true, true, 0,
                false);

Modified: trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSLTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSLTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/remoting/ssl/integration/CoreClientOverSSLTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -128,8 +128,7 @@
       server = new MessagingServerImpl(remotingConf);
       server.start();
 
-      ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0,
-            remotingConf, server.getVersion(), false, 0);
+      ClientConnectionFactory cf = new ClientConnectionFactoryImpl(0, remotingConf, server.getVersion());
       connection = cf.createConnection(null, null);
       ClientSession session = connection.createClientSession(false, true, true,
             0, false);

Deleted: trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessageTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessageTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessageTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -1,423 +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.messaging.core.server.impl.test.unit;
-
-import static org.jboss.messaging.test.unit.RandomUtil.randomByte;
-import static org.jboss.messaging.test.unit.RandomUtil.randomInt;
-import static org.jboss.messaging.test.unit.RandomUtil.randomLong;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.jboss.messaging.core.message.Message;
-import org.jboss.messaging.core.message.MessageReference;
-import org.jboss.messaging.core.message.impl.MessageImpl;
-import org.jboss.messaging.core.server.Queue;
-import org.jboss.messaging.core.server.QueueFactory;
-import org.jboss.messaging.core.server.impl.test.unit.fakes.FakeQueueFactory;
-import org.jboss.messaging.test.unit.UnitTestCase;
-import org.jboss.messaging.util.StreamUtils;
-
-/**
- * 
- * Tests for Message and MessageReference
- * 
- * TODO - Test streaming and destreaming
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public class MessageTest extends UnitTestCase
-{
-	private QueueFactory queueFactory = new FakeQueueFactory();
-   
-   public void testCreateMessage()
-   {
-      long id = 56465;
-      int type = 655;
-      boolean reliable = true;
-      long expiration = 6712671;
-      long timestamp = 82798172;
-      byte priority = 32;
-      
-      Message message = new MessageImpl(type, reliable, expiration, timestamp, priority);
-      message.setMessageID(id);
-      
-      assertEquals(id, message.getMessageID());
-      assertEquals(type, message.getType());
-      assertEquals(reliable, message.isDurable());
-      assertEquals(timestamp, message.getTimestamp());
-      assertEquals(priority, message.getPriority());
-      
-      reliable = false;
-      
-      message = new MessageImpl(type, reliable, expiration, timestamp, priority);
-      message.setMessageID(id);
-      
-      assertEquals(id, message.getMessageID());
-      assertEquals(type, message.getType());
-      assertEquals(reliable, message.isDurable());
-      assertEquals(timestamp, message.getTimestamp());
-      assertEquals(priority, message.getPriority());
-   }
-   
-   public void testCreateMessageFromStorage() throws Exception
-   {
-      long id = 56465;
-      int type = 655;
-      boolean reliable = true;
-      long expiration = 6712671;
-      long timestamp = 82798172;
-      byte priority = 32;
-      
-      byte[] bytes = "blah blah blah".getBytes();
- 
-      Message message = new MessageImpl(id, type, reliable, expiration, timestamp, priority,
-            null, bytes);
-      
-      assertEquals(id, message.getMessageID());
-      assertEquals(type, message.getType());
-      assertEquals(reliable, message.isDurable());
-      assertEquals(timestamp, message.getTimestamp());
-      assertEquals(priority, message.getPriority());     
-      
-      assertByteArraysEquivalent(bytes, message.getPayload());   
-      
-      //TODO - headers - they should really be combined into single blob
-   }
-   
-   public void testCopy()
-   {
-      long id = 56465;
-      int type = 655;
-      boolean reliable = true;
-      long expiration = 6712671;
-      long timestamp = 82798172;
-      byte priority = 32;
-      
-      Message message = new MessageImpl(type, reliable, expiration, timestamp, priority);
-      message.setMessageID(id);
-      
-      Message message2 = message.copy();
-      
-      assertEquivalent(message, message2);
-   }
-   
-   public void testSetAndGetMessageID()
-   {
-      Message message = new MessageImpl();
-      
-      assertEquals(0, message.getMessageID());
-      
-      message = new MessageImpl(655, true, 767676, 989898, (byte)32);
-      
-      assertEquals(0, message.getMessageID());
-      
-      long id = 765432;
-      message.setMessageID(id);
-      assertEquals(id, message.getMessageID());
-   }
-   
-   public void testSetAndGetReliable()
-   {
-      Message message = new MessageImpl();
-      
-      boolean reliable = true;
-      message.setDurable(reliable);
-      assertEquals(reliable, message.isDurable());
-      
-      reliable = false;
-      message.setDurable(reliable);
-      assertEquals(reliable, message.isDurable());
-   }
-    
-   public void testSetAndGetExpiration()
-   {
-      Message message = new MessageImpl();
-      
-      long expiration = System.currentTimeMillis() + 10000;
-      message.setExpiration(expiration);
-      assertEquals(expiration, message.getExpiration());
-      assertFalse(message.isExpired());
-      message.setExpiration(System.currentTimeMillis() - 1);
-      assertTrue(message.isExpired());
-      
-      expiration = 0; //O means never expire
-      message.setExpiration(expiration);
-      assertEquals(expiration, message.getExpiration());
-      assertFalse(message.isExpired());
-   }
-      
-   public void testSetAndGetTimestamp()
-   {
-      Message message = new MessageImpl();
-      
-      long timestamp = System.currentTimeMillis();
-      message.setTimestamp(timestamp);
-      assertEquals(timestamp, message.getTimestamp());
-   }
-   
-   public void testSetAndGetPriority()
-   {
-      Message message = new MessageImpl();
-      byte priority = 7;
-      message.setPriority(priority);
-      assertEquals(priority, message.getPriority());
-   }
-   
-   public void testSetAndGetConnectionID()
-   {
-      Message message = new MessageImpl();
-      
-      assertNull(message.getConnectionID());
-      String connectionID = "conn123";
-      message.setConnectionID(connectionID);
-      assertEquals(connectionID, message.getConnectionID());      
-   }
-   
-   public void testSetAndGetPayload()
-   {
-      Message message = new MessageImpl();
-      
-      assertNull(message.getPayload());
-      
-      byte[] bytes = "blah blah blah".getBytes();
-      message.setPayload(bytes);
-      
-      assertByteArraysEquivalent(bytes, message.getPayload());            
-   }
-   
-   public void testHeaders()
-   {
-      Message message = new MessageImpl();
-      
-      assertNotNull(message.getHeaders());
-      assertTrue(message.getHeaders().isEmpty());
-      
-      String key1 = "key1";
-      String val1 = "wibble";
-      String key2 = "key2";
-      Object val2 = new Object();
-      String key3 = "key3";
-      Double val3 = new Double(123.456);
-      Long val4 = new Long(77777);
-      message.putHeader(key1, val1);
-      assertEquals(val1, message.getHeaders().get(key1));
-      assertEquals(1, message.getHeaders().size());
-      assertTrue(message.containsHeader(key1));
-      assertFalse(message.containsHeader("does not exist"));
-      message.putHeader(key2, val2);
-      assertEquals(val2, message.getHeaders().get(key2));
-      assertEquals(2, message.getHeaders().size());
-      assertTrue(message.containsHeader(key2));
-      message.putHeader(key3, val3);
-      assertEquals(val3, message.getHeaders().get(key3));
-      assertEquals(3, message.getHeaders().size());
-      assertTrue(message.containsHeader(key3));
-      message.putHeader(key3, val4);
-      assertEquals(val4, message.getHeaders().get(key3));
-      assertEquals(3, message.getHeaders().size());
-      assertEquals(val2, message.removeHeader(key2));
-      assertEquals(2, message.getHeaders().size());
-      assertFalse(message.containsHeader(key2));
-      assertNull(message.removeHeader("does not exist"));
-      assertEquals(val1, message.removeHeader(key1));
-      assertFalse(message.containsHeader(key2));
-      assertEquals(1, message.getHeaders().size());
-      assertEquals(val4, message.removeHeader(key3));
-      assertFalse(message.containsHeader(key3));
-      assertTrue(message.getHeaders().isEmpty());
-   }
-   
-   public void testEquals()
-   {
-      Message message1 = new MessageImpl();
-      message1.setMessageID(1);
-      
-      Message message2 = new MessageImpl();
-      message2.setMessageID(2);
-      
-      Message message3 = new MessageImpl();
-      message3.setMessageID(1);
-      
-      assertTrue(message1.equals(message1));
-      assertTrue(message2.equals(message2));
-      assertTrue(message3.equals(message3));
-      
-      assertFalse(message1.equals(message2));
-      assertFalse(message2.equals(message1));
-      
-      assertFalse(message2.equals(message3));
-      assertFalse(message3.equals(message2));
-      
-      assertTrue(message1.equals(message3));
-      assertTrue(message3.equals(message1));
-      
-   }
-   
-   public void testHashcode()
-   {
-      long id1 = 6567575;
-      Message message1 = new MessageImpl();
-      message1.setMessageID(id1);
-      
-      assertEquals((int) ((id1 >>> 32) ^ id1), message1.hashCode());
-   }
-   
-   public void testMessageReference()
-   {
-      Message message = new MessageImpl();
-      
-      assertTrue(message.getReferences().isEmpty());
-      
-      Queue queue1 = queueFactory.createQueue(1, "queue1", null, false, true);
-      Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, true);
-
-      List<MessageReference> refs = new ArrayList<MessageReference>();
-      
-      MessageReference ref1 = message.createReference(queue1);
-      refs.add(ref1);
-      MessageReference ref2 = message.createReference(queue2);
-      refs.add(ref2);
-      MessageReference ref3 = message.createReference(queue1);
-      refs.add(ref3);
-      MessageReference ref4 = message.createReference(queue2);
-      refs.add(ref4);
-      
-      assertRefListsIdenticalRefs(refs, message.getReferences());
-      
-      assertEquals(queue1, ref1.getQueue());
-      assertEquals(queue2, ref2.getQueue());
-      assertEquals(queue1, ref3.getQueue());
-      assertEquals(queue2, ref4.getQueue());
-      
-      int deliveryCount = 65235;
-      ref1.setDeliveryCount(deliveryCount);
-      assertEquals(deliveryCount, ref1.getDeliveryCount());
-      
-      long scheduledDeliveryTime = 908298123;
-      ref1.setScheduledDeliveryTime(scheduledDeliveryTime);
-      assertEquals(scheduledDeliveryTime, ref1.getScheduledDeliveryTime());
-      
-      Queue queue3 = queueFactory.createQueue(3, "queue3", null, false, true);
-      MessageReference ref5 = ref1.copy(queue3);
-      
-      assertEquals(deliveryCount, ref5.getDeliveryCount());
-      assertEquals(scheduledDeliveryTime, ref5.getScheduledDeliveryTime());
-      assertEquals(queue3, ref5.getQueue());
-   }
-   
-
-   public void testDurableReferences()
-   {
-      Message messageDurable = new MessageImpl();
-      messageDurable.setDurable(true);
-      
-      Message messageNonDurable = new MessageImpl();
-      messageNonDurable.setDurable(false);
-        
-      //Durable queue
-      Queue queue1 = queueFactory.createQueue(1, "queue1", null, true, false);
-      
-      //Non durable queue
-      Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, false);
-      
-      assertEquals(0, messageDurable.getNumDurableReferences());
-      
-      MessageReference ref1 = messageDurable.createReference(queue1);
-      
-      assertEquals(1, messageDurable.getNumDurableReferences());
-      
-      MessageReference ref2 = messageDurable.createReference(queue2);
-      
-      assertEquals(1, messageDurable.getNumDurableReferences());
-      
-      assertEquals(0, messageNonDurable.getNumDurableReferences());
-      
-      MessageReference ref3 = messageNonDurable.createReference(queue1);
-      
-      assertEquals(0, messageNonDurable.getNumDurableReferences());
-      
-      MessageReference ref4 = messageNonDurable.createReference(queue2);
-      
-      assertEquals(0, messageNonDurable.getNumDurableReferences());
-                  
-   }
-   
-   public void testDurableReferencePos()
-   {
-      Message messageDurable = new MessageImpl();
-      messageDurable.setDurable(true);
-      
-      //Durable queue
-      Queue queue1 = queueFactory.createQueue(1, "queue1", null, true, false);
-      
-      //Non durable queue
-      Queue queue2 = queueFactory.createQueue(2, "queue2", null, false, false);
-      
-      
-      MessageReference ref1 = messageDurable.createReference(queue1);
-      
-      MessageReference ref2 = messageDurable.createReference(queue2);
-      
-      MessageReference ref3 = messageDurable.createReference(queue2);
-      
-      MessageReference ref4 = messageDurable.createReference(queue1);
-      
-      MessageReference ref5 = messageDurable.createReference(queue1);
-      
-      MessageReference ref6 = messageDurable.createReference(queue2);
-      
-      MessageReference ref7 = messageDurable.createReference(queue1);
-      
-      MessageReference ref8 = messageDurable.createReference(queue2);
-      
-      assertEquals(0, messageDurable.getDurableReferencePos(ref1));
-      
-      assertEquals(1, messageDurable.getDurableReferencePos(ref4));
-      
-      assertEquals(2, messageDurable.getDurableReferencePos(ref5));
-      
-      assertEquals(3, messageDurable.getDurableReferencePos(ref7));
-             
-   }
-   
-   public void testMarshalling() throws Exception
-   {
-      Message msg = new MessageImpl(randomLong(), randomInt(), true, randomLong(), randomLong(), randomByte(),null, null);
-      msg.setDeliveryCount(randomInt());
-      
-      byte[] bytes = StreamUtils.toBytes(msg);
-      Message unmarshalledMsg = new MessageImpl();
-      StreamUtils.fromBytes(unmarshalledMsg, bytes);
-      
-      assertEquals(msg, unmarshalledMsg);
-      assertEquals("messageID", msg.getMessageID(), unmarshalledMsg.getMessageID());
-      assertEquals("type", msg.getType(), unmarshalledMsg.getType());
-      assertEquals("durable", msg.isDurable(), unmarshalledMsg.isDurable());
-      assertEquals("expiration", msg.getExpiration(), unmarshalledMsg.getExpiration());
-      assertEquals("timestamp", msg.getTimestamp(), unmarshalledMsg.getTimestamp());
-      assertEquals("priority", msg.getPriority(), unmarshalledMsg.getPriority());
-      assertEquals("deliveryCount", msg.getDeliveryCount(), unmarshalledMsg.getDeliveryCount()); 
-   }
-   
-}

Deleted: trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessagingXidTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessagingXidTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessagingXidTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -1,161 +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.messaging.core.server.impl.test.unit;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-import javax.transaction.xa.Xid;
-
-import org.jboss.messaging.core.transaction.impl.XidImpl;
-import org.jboss.messaging.test.unit.RandomUtil;
-import org.jboss.messaging.test.unit.UnitTestCase;
-
-/**
- * 
- * A MessagingXidTest
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public class MessagingXidTest extends UnitTestCase
-{
-   public void testSerialize() throws Exception
-   {
-      XidImpl xid = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
-                                          RandomUtil.randomBytes());
-      
-      ByteArrayOutputStream baos = new ByteArrayOutputStream();
-      
-      ObjectOutputStream oos = new ObjectOutputStream(baos);
-      
-      oos.writeObject(xid);
-      
-      oos.flush();
-      
-      ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
-      
-      Object obj = ois.readObject();
-      
-      assertTrue(obj instanceof XidImpl);
-      
-      XidImpl xid2 = (XidImpl)obj;
-      
-      assertXidsEquivalent(xid, xid2);
-      
-      assertEquals(xid, xid2);     
-   }
-   
-   public void testStandardConstructor()
-   {
-      byte[] bq = RandomUtil.randomBytes();
-      
-      byte[] globalTXID = RandomUtil.randomBytes();
-      
-      int formatID = RandomUtil.randomInt();
-      
-      XidImpl xid1 = new XidImpl(bq, formatID, globalTXID);
-      
-      assertByteArraysEquivalent(bq, xid1.getBranchQualifier());
-      
-      assertByteArraysEquivalent(globalTXID, xid1.getGlobalTransactionId());
-      
-      assertEquals(formatID, xid1.getFormatId());
-   }
-   
-   public void testCopyConstructor()
-   {
-      XidImpl xid1 = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
-                                          RandomUtil.randomBytes());
-      
-      XidImpl xid2 = new XidImpl(xid1);
-      
-      assertXidsEquivalent(xid1, xid2);
-      
-      assertEquals(xid2, xid2);
-   }
-   
-   public void testEqualsWithForeign()
-   {
-      XidImpl xid1 = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
-            RandomUtil.randomBytes());
-
-      Xid foreign = new ForeignXid(xid1.getBranchQualifier(), xid1.getFormatId(), xid1.getGlobalTransactionId());
-      
-      assertTrue(xid1.equals(foreign));
-      
-      foreign = new ForeignXid(RandomUtil.randomBytes(), RandomUtil.randomInt(),
-                               RandomUtil.randomBytes());
-      
-      assertFalse(xid1.equals(foreign));
-      
-   }
-   
-   // Private ---------------------------------------------------------------------------------
-   
-   private void assertXidsEquivalent(Xid xid1, Xid xid2)
-   {
-      assertByteArraysEquivalent(xid1.getBranchQualifier(), xid2.getBranchQualifier());
-      
-      assertEquals(xid1.getFormatId(), xid2.getFormatId());
-      
-      assertByteArraysEquivalent(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId());
-   }
-   
-   // Inner classes ---------------------------------------------------------------------------
-   
-   class ForeignXid implements Xid
-   {
-      private byte[] branchQualifier;
-      
-      private int formatId;
-      
-      private byte[] globalTransactionId;
-      
-      public ForeignXid(byte[] branchQualifier, int formatId, byte[] globalTransactionId)
-      {
-         this.branchQualifier = branchQualifier;
-         this.formatId = formatId;
-         this.globalTransactionId = globalTransactionId;          
-      }
-           
-      public byte[] getBranchQualifier()
-      {
-         return this.branchQualifier;
-      }
-
-      public int getFormatId()
-      {
-         return this.formatId;
-      }
-
-      public byte[] getGlobalTransactionId()
-      {
-         return this.globalTransactionId;
-      }
-      
-   }
-   
-   
-}

Deleted: trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/PostOfficeTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/PostOfficeTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/PostOfficeTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -1,262 +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.messaging.core.server.impl.test.unit;
-
-import java.util.List;
-import java.util.Map;
-
-import org.easymock.EasyMock;
-import org.jboss.messaging.core.filter.Filter;
-import org.jboss.messaging.core.message.Message;
-import org.jboss.messaging.core.persistence.PersistenceManager;
-import org.jboss.messaging.core.postoffice.Binding;
-import org.jboss.messaging.core.postoffice.PostOffice;
-import org.jboss.messaging.core.postoffice.impl.BindingImpl;
-import org.jboss.messaging.core.postoffice.impl.PostOfficeImpl;
-import org.jboss.messaging.core.server.Queue;
-import org.jboss.messaging.core.server.QueueFactory;
-import org.jboss.messaging.core.server.impl.test.unit.fakes.FakeQueueFactory;
-import org.jboss.messaging.test.unit.UnitTestCase;
-
-/**
- * 
- * A PostOfficeTest
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public class PostOfficeTest extends UnitTestCase
-{
-	private QueueFactory queueFactory = new FakeQueueFactory();
-   
-   public void testAddQueue() throws Exception
-   {
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      QueueFactory qf = EasyMock.createStrictMock(QueueFactory.class);
-      
-      final int nodeID = 21;
-      
-      PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
-      
-      final long id = 324;
-      final String name = "wibb22";
-      final Filter filter = new FakeFilter();
-      final boolean durable = true;
-      final boolean temporary = true;
-      
-      Queue queue = queueFactory.createQueue(id, name, filter, durable, temporary);
-      
-      EasyMock.expect(qf.createQueue(-1, name, filter, durable, temporary)).andReturn(queue);
-            
-      final String condition = "queue.wibble";
-
-      Binding expected = new BindingImpl(nodeID, condition, queue);
-      
-      pm.addBinding(EasyMock.eq(expected));
-      
-      EasyMock.replay(qf);
-      
-      EasyMock.replay(pm);
-      
-      po.addBinding(condition, name, filter, durable, temporary);
-      
-      EasyMock.verify(qf);
-      
-      EasyMock.verify(pm);
-      
-      EasyMock.reset(qf);
-      
-      EasyMock.reset(pm);
-      
-      final boolean durable2 = false;
-      
-      queue = queueFactory.createQueue(id, name, filter, durable2, temporary);
-      
-      EasyMock.expect(qf.createQueue(-1, name, filter, durable2, temporary)).andReturn(queue);
-      
-      EasyMock.replay(qf);
-      
-      EasyMock.replay(pm);      
-   }   
-   
-   public void testRemoveQueue() throws Exception
-   {
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      QueueFactory qf = EasyMock.createStrictMock(QueueFactory.class);
-      
-      final int nodeID = 21;
-      
-      PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
-      
-      final long id = 324;
-      final String name = "wibb22";
-      final Filter filter = new FakeFilter();
-      final boolean durable = true;
-      final boolean temporary = true;
-      
-      Queue queue = queueFactory.createQueue(id, name, filter, durable, temporary);
-      
-      EasyMock.expect(qf.createQueue(-1, name, filter, durable, temporary)).andReturn(queue);
-            
-      final String condition = "queue.wibble";
- 
-      Binding expected = new BindingImpl(nodeID, condition, queue);
-      
-      pm.addBinding(EasyMock.eq(expected));
-      
-      pm.deleteBinding(EasyMock.eq(expected));
-      
-      EasyMock.replay(qf);
-      
-      EasyMock.replay(pm);
-      
-      po.addBinding(condition, name, filter, durable, temporary);
-      
-      po.removeBinding(name);
-      
-      EasyMock.verify(qf);
-      
-      EasyMock.verify(pm);
-      
-      EasyMock.reset(qf);
-      
-      EasyMock.reset(pm);
-      
-      final boolean durable2 = false;
-      
-      queue = queueFactory.createQueue(id, name, filter, durable2, temporary);
-      
-      EasyMock.expect(qf.createQueue(-1, name, filter, durable2, temporary)).andReturn(queue);
-      
-      EasyMock.replay(qf);
-      
-      EasyMock.replay(pm);
-      
-      po.addBinding(condition, name, filter, durable2, temporary);
-      
-      po.removeBinding(name);
-      
-      EasyMock.verify(qf);
-      
-      EasyMock.verify(pm);
-   }   
-   
-   public void testAddRemoveMultipleWithDifferentConditions() throws Exception
-   {
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      QueueFactory qf = new FakeQueueFactory();
-      
-      final int nodeID = 21;
-      
-      PostOffice po = new PostOfficeImpl(nodeID, pm, qf, false);
-      
-      final String condition1 = "queue.wibble";      
-                
-      po.addBinding(condition1, "queue1", null, false, false);      
-      Map<String, List<Binding>> mappings = po.getMappings();      
-      assertEquals(1, mappings.size());
-      
-      po.addBinding(condition1, "queue2", null, false, false);     
-      mappings = po.getMappings();      
-      assertEquals(1, mappings.size());
-      
-      po.addBinding(condition1, "queue3", null, false, false); 
-      mappings = po.getMappings();      
-      assertEquals(1, mappings.size());
-      
-      List<Binding> bindings = mappings.get(condition1);
-      assertNotNull(bindings);
-      assertEquals(3, bindings.size());
-      
-      Binding binding1 = bindings.get(0);
-      Queue queue1 = binding1.getQueue();
-      assertEquals("queue1", queue1.getName());
-            
-      Binding binding2 = bindings.get(1);
-      Queue queue2 = binding2.getQueue();
-      assertEquals("queue2", queue2.getName());
-      
-      Binding binding3 = bindings.get(2);
-      Queue queue3 = binding3.getQueue();
-      assertEquals("queue3", queue3.getName());
-      
-      final String condition2 = "queue.wibble2"; 
-      
-      po.addBinding(condition2, "queue4", null, false, false);       
-      mappings = po.getMappings();      
-      assertEquals(2, mappings.size());
-      
-      po.addBinding(condition2, "queue5", null, false, false); 
-      mappings = po.getMappings();      
-      assertEquals(2, mappings.size());
-      
-      final String condition3 = "topic.wibblexyz"; 
-      
-      po.addBinding(condition3, "queue6", null, false, false);       
-      mappings = po.getMappings();      
-      assertEquals(3, mappings.size());
-      
-      po.removeBinding("queue6");
-      mappings = po.getMappings();      
-      assertEquals(2, mappings.size());
-      
-      po.removeBinding("queue4");
-      mappings = po.getMappings();      
-      assertEquals(2, mappings.size());
-      
-      po.removeBinding("queue5");
-      mappings = po.getMappings();      
-      assertEquals(1, mappings.size());
-      
-      po.removeBinding("queue1");
-      mappings = po.getMappings();      
-      assertEquals(1, mappings.size());
-      
-      po.removeBinding("queue2");
-      mappings = po.getMappings();      
-      assertEquals(1, mappings.size());
-      
-      po.removeBinding("queue3");
-      mappings = po.getMappings();      
-      assertEquals(0, mappings.size());      
-   }
-
-   
-   
-   
-   class FakeFilter implements Filter
-   {
-		public String getFilterString()
-		{
-			return "aardvark";
-		}
-
-		public boolean match(Message message)
-		{
-			return true;
-		}
-   	
-   }
-}

Modified: trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/QueueTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/QueueTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/QueueTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -471,7 +471,7 @@
    }
    
    
-   public void testChangeConsumersAndDeliver()
+   public void testChangeConsumersAndDeliver() throws Exception
    {
       Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
                   
@@ -516,7 +516,7 @@
       
       for (int i = 0; i < numMessages; i++)
       {
-         queue.decrementDeliveringCount();
+         queue.referenceAcknowledged();
       }
       
       for (int i = 0; i < 2 * numMessages; i++)
@@ -541,7 +541,7 @@
       refs.clear();
       for (int i = 0; i < 2 * numMessages; i++)
       {
-         queue.decrementDeliveringCount();
+         queue.referenceAcknowledged();
       }
       
       FakeConsumer cons3 = new FakeConsumer();
@@ -576,7 +576,7 @@
       refs.clear();
       for (int i = 0; i < 3 * numMessages; i++)
       {
-         queue.decrementDeliveringCount();
+         queue.referenceAcknowledged();
       }
       
       for (int i = 0; i < 2 * numMessages; i++)
@@ -602,7 +602,7 @@
       refs.clear();
       for (int i = 0; i < 2 * numMessages; i++)
       {
-         queue.decrementDeliveringCount();
+         queue.referenceAcknowledged();
       }
       
       for (int i = 0; i < numMessages; i++)
@@ -907,12 +907,12 @@
       assertRefListsIdenticalRefs(refs, consumer.getReferences());      
    }
    
-   public void testConsumerWithFiltersDirect()
+   public void testConsumerWithFiltersDirect() throws Exception
    {
       testConsumerWithFilters(true);
    }
    
-   public void testConsumerWithFiltersQueueing()
+   public void testConsumerWithFiltersQueueing() throws Exception
    {
       testConsumerWithFilters(false);
    }
@@ -1016,7 +1016,7 @@
    }
    */
    
-   public void testConsumeWithFiltersAddAndRemoveConsumer()
+   public void testConsumeWithFiltersAddAndRemoveConsumer() throws Exception
    {
       Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
       
@@ -1051,7 +1051,7 @@
             
       assertRefListsIdenticalRefs(refs, consumer.getReferences()); 
       
-      queue.decrementDeliveringCount();
+      queue.referenceAcknowledged();
 
       queue.removeConsumer(consumer);
             
@@ -1089,7 +1089,7 @@
    
    // Private ------------------------------------------------------------------------------
    
-   private void testConsumerWithFilters(boolean direct)
+   private void testConsumerWithFilters(boolean direct) throws Exception
    {
       Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
       
@@ -1159,8 +1159,8 @@
             
       assertRefListsIdenticalRefs(refs, consumer.getReferences()); 
       
-      queue.decrementDeliveringCount();
-      queue.decrementDeliveringCount();
+      queue.referenceAcknowledged();
+      queue.referenceAcknowledged();
       
       queue.removeConsumer(consumer);
       

Deleted: trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/TransactionTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/TransactionTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/TransactionTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -1,371 +0,0 @@
-package org.jboss.messaging.core.server.impl.test.unit;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-
-import javax.transaction.xa.Xid;
-
-import org.easymock.EasyMock;
-import org.jboss.messaging.core.message.Message;
-import org.jboss.messaging.core.message.MessageReference;
-import org.jboss.messaging.core.persistence.PersistenceManager;
-import org.jboss.messaging.core.server.Queue;
-import org.jboss.messaging.core.server.impl.QueueImpl;
-import org.jboss.messaging.core.settings.HierarchicalRepository;
-import org.jboss.messaging.core.settings.impl.HierarchicalObjectRepository;
-import org.jboss.messaging.core.settings.impl.QueueSettings;
-import org.jboss.messaging.core.transaction.Transaction;
-import org.jboss.messaging.core.transaction.TransactionSynchronization;
-import org.jboss.messaging.core.transaction.impl.TransactionImpl;
-import org.jboss.messaging.test.unit.UnitTestCase;
-
-/**
- * 
- * A TransactionTest
- * 
- * TODO test with persistent and non persistent
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public class TransactionTest extends UnitTestCase
-{
-	private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
-
-   private final HierarchicalRepository<QueueSettings> queueSettings = 
-   	new HierarchicalObjectRepository<QueueSettings>();
-	
-   protected void setUp() throws Exception
-   {
-   	super.setUp();
-   	
-   	queueSettings.setDefault(new QueueSettings());
-   }
-   
-   public void test1PCCommit() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-                  
-      Transaction tx = new TransactionImpl();
-      
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      pm.commitTransaction(msgsToAdd, refsToRemove);
-      
-      EasyMock.replay(pm);
-      
-      tx.commit(true, pm);
-      
-      EasyMock.verify(pm);
-      
-      assertEquals(ref1, queue.list(null).get(0));
-   }
-   
-   public void test1PCRollback() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-                  
-      Transaction tx = new TransactionImpl();
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      pm.updateDeliveryCount(queue, ref2);
-      
-      EasyMock.replay(pm);
-      
-      tx.rollback(pm);
-      
-      EasyMock.verify(pm);
- 
-      assertEquals(ref2, queue.list(null).get(0));
-   }
-   
-   public void test1PCPrepare() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-                  
-      Transaction tx = new TransactionImpl();
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      try
-      {
-         tx.prepare(pm);
-         fail("Should throw exception");
-      }
-      catch (IllegalStateException e)
-      {
-         //OK
-      }   
-      
-      assertTrue(queue.list(null).isEmpty());
-   }
-   
-   public void test2PCPrepareCommit() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-      
-      Xid xid = generateXid();
-                  
-      Transaction tx = new TransactionImpl(xid);
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      pm.prepareTransaction(xid, msgsToAdd, refsToRemove);
-      
-      EasyMock.replay(pm);
-      
-      tx.prepare(pm);
-      
-      EasyMock.verify(pm);
-      
-      EasyMock.reset(pm);
-      
-      pm.commitPreparedTransaction(xid);
-      
-      EasyMock.replay(pm);
-      
-      tx.commit(false, pm);
-      
-      EasyMock.verify(pm);
-   }
-   
-   public void test2PCCommitBeforePrepare() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-          
-      Xid xid = generateXid();
-      
-      Transaction tx = new TransactionImpl(xid);
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      try
-      {    
-         tx.commit(false, pm);
-         
-         fail ("Should throw exception");
-      }
-      catch (IllegalStateException e)
-      {
-         //Ok
-      }      
-   }
-   
-   public void test2PCPrepareRollback() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-      
-      Xid xid = generateXid();
-                  
-      Transaction tx = new TransactionImpl(xid);
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      pm.prepareTransaction(xid, msgsToAdd, refsToRemove);
-      
-      EasyMock.replay(pm);
-      
-      tx.prepare(pm);
-      
-      EasyMock.verify(pm);
-      
-      EasyMock.reset(pm);
-      
-      pm.unprepareTransaction(xid, msgsToAdd, refsToRemove);
-      
-      pm.updateDeliveryCount(queue, ref2);
-      
-      EasyMock.replay(pm);
-      
-      tx.rollback(pm);
-      
-      EasyMock.verify(pm);
-   }
-   
-   public void testSynchronizations() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-                  
-      Transaction tx = new TransactionImpl();
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      TransactionSynchronization sync = EasyMock.createStrictMock(TransactionSynchronization.class);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      tx.addSynchronization(sync);
-      
-      sync.beforeCommit();
-      sync.afterCommit();
-      
-      EasyMock.replay(sync);
-      
-      tx.commit(true, pm);
-      
-      EasyMock.verify(sync);
-      
-      EasyMock.reset(sync);
-      
-      tx = new TransactionImpl();
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      tx.addSynchronization(sync);
-      
-      sync.beforeRollback();
-      sync.afterRollback();
-      
-      EasyMock.replay(sync);
-      
-      tx.rollback(pm);
-      
-      EasyMock.verify(sync);            
-   }
-   
-   public void testSynchronizations2PC() throws Exception
-   {
-      List<Message> msgsToAdd = new ArrayList<Message>();
-      
-      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
-      
-      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
-      
-      MessageReference ref1 = this.generateReference(queue, 1);
-      msgsToAdd.add(ref1.getMessage());
-      
-      MessageReference ref2 = this.generateReference(queue, 2);
-      refsToRemove.add(ref2);
-      
-      Xid xid = generateXid();
-                  
-      Transaction tx = new TransactionImpl(xid);
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      TransactionSynchronization sync = EasyMock.createStrictMock(TransactionSynchronization.class);
-      
-      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
-      
-      tx.addSynchronization(sync);
-      
-      sync.beforeCommit();
-      sync.afterCommit();
-      
-      EasyMock.replay(sync);
-      
-      tx.prepare(pm);
-      tx.commit(false, pm);
-      
-      EasyMock.verify(sync);
-      
-      EasyMock.reset(sync);
-      
-      xid = generateXid();
-      
-      tx = new TransactionImpl(xid);
-      tx.addMessage(ref1.getMessage());
-      tx.addAcknowledgement(ref2);
-      
-      tx.addSynchronization(sync);
-      
-      sync.beforeRollback();
-      sync.afterRollback();
-      
-      EasyMock.replay(sync);
-      
-      tx.prepare(pm);
-      tx.rollback(pm);
-      
-      EasyMock.verify(sync);            
-   }
-   
-   // Inner classes -----------------------------------------------------------------------
-   
-}

Copied: trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/MessagingXidTest.java (from rev 3827, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/MessagingXidTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/MessagingXidTest.java	                        (rev 0)
+++ trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/MessagingXidTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,161 @@
+/*
+  * 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.transaction.impl.test.unit;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+import javax.transaction.xa.Xid;
+
+import org.jboss.messaging.core.transaction.impl.XidImpl;
+import org.jboss.messaging.test.unit.RandomUtil;
+import org.jboss.messaging.test.unit.UnitTestCase;
+
+/**
+ * 
+ * A MessagingXidTest
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class MessagingXidTest extends UnitTestCase
+{
+   public void testSerialize() throws Exception
+   {
+      XidImpl xid = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+                                          RandomUtil.randomBytes());
+      
+      ByteArrayOutputStream baos = new ByteArrayOutputStream();
+      
+      ObjectOutputStream oos = new ObjectOutputStream(baos);
+      
+      oos.writeObject(xid);
+      
+      oos.flush();
+      
+      ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
+      
+      Object obj = ois.readObject();
+      
+      assertTrue(obj instanceof XidImpl);
+      
+      XidImpl xid2 = (XidImpl)obj;
+      
+      assertXidsEquivalent(xid, xid2);
+      
+      assertEquals(xid, xid2);     
+   }
+   
+   public void testStandardConstructor()
+   {
+      byte[] bq = RandomUtil.randomBytes();
+      
+      byte[] globalTXID = RandomUtil.randomBytes();
+      
+      int formatID = RandomUtil.randomInt();
+      
+      XidImpl xid1 = new XidImpl(bq, formatID, globalTXID);
+      
+      assertByteArraysEquivalent(bq, xid1.getBranchQualifier());
+      
+      assertByteArraysEquivalent(globalTXID, xid1.getGlobalTransactionId());
+      
+      assertEquals(formatID, xid1.getFormatId());
+   }
+   
+   public void testCopyConstructor()
+   {
+      XidImpl xid1 = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+                                          RandomUtil.randomBytes());
+      
+      XidImpl xid2 = new XidImpl(xid1);
+      
+      assertXidsEquivalent(xid1, xid2);
+      
+      assertEquals(xid2, xid2);
+   }
+   
+   public void testEqualsWithForeign()
+   {
+      XidImpl xid1 = new XidImpl(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+            RandomUtil.randomBytes());
+
+      Xid foreign = new ForeignXid(xid1.getBranchQualifier(), xid1.getFormatId(), xid1.getGlobalTransactionId());
+      
+      assertTrue(xid1.equals(foreign));
+      
+      foreign = new ForeignXid(RandomUtil.randomBytes(), RandomUtil.randomInt(),
+                               RandomUtil.randomBytes());
+      
+      assertFalse(xid1.equals(foreign));
+      
+   }
+   
+   // Private ---------------------------------------------------------------------------------
+   
+   private void assertXidsEquivalent(Xid xid1, Xid xid2)
+   {
+      assertByteArraysEquivalent(xid1.getBranchQualifier(), xid2.getBranchQualifier());
+      
+      assertEquals(xid1.getFormatId(), xid2.getFormatId());
+      
+      assertByteArraysEquivalent(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId());
+   }
+   
+   // Inner classes ---------------------------------------------------------------------------
+   
+   class ForeignXid implements Xid
+   {
+      private byte[] branchQualifier;
+      
+      private int formatId;
+      
+      private byte[] globalTransactionId;
+      
+      public ForeignXid(byte[] branchQualifier, int formatId, byte[] globalTransactionId)
+      {
+         this.branchQualifier = branchQualifier;
+         this.formatId = formatId;
+         this.globalTransactionId = globalTransactionId;          
+      }
+           
+      public byte[] getBranchQualifier()
+      {
+         return this.branchQualifier;
+      }
+
+      public int getFormatId()
+      {
+         return this.formatId;
+      }
+
+      public byte[] getGlobalTransactionId()
+      {
+         return this.globalTransactionId;
+      }
+      
+   }
+   
+   
+}

Copied: trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/TransactionTest.java (from rev 3827, trunk/tests/src/org/jboss/messaging/core/server/impl/test/unit/TransactionTest.java)
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/TransactionTest.java	                        (rev 0)
+++ trunk/tests/src/org/jboss/messaging/core/transaction/impl/test/unit/TransactionTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,371 @@
+package org.jboss.messaging.core.transaction.impl.test.unit;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+
+import javax.transaction.xa.Xid;
+
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.message.MessageReference;
+import org.jboss.messaging.core.persistence.PersistenceManager;
+import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.impl.QueueImpl;
+import org.jboss.messaging.core.settings.HierarchicalRepository;
+import org.jboss.messaging.core.settings.impl.HierarchicalObjectRepository;
+import org.jboss.messaging.core.settings.impl.QueueSettings;
+import org.jboss.messaging.core.transaction.Transaction;
+import org.jboss.messaging.core.transaction.TransactionSynchronization;
+import org.jboss.messaging.core.transaction.impl.TransactionImpl;
+import org.jboss.messaging.test.unit.UnitTestCase;
+
+/**
+ * 
+ * A TransactionTest
+ * 
+ * TODO test with persistent and non persistent
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class TransactionTest extends UnitTestCase
+{
+	private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
+
+   private final HierarchicalRepository<QueueSettings> queueSettings = 
+   	new HierarchicalObjectRepository<QueueSettings>();
+	
+   protected void setUp() throws Exception
+   {
+   	super.setUp();
+   	
+   	queueSettings.setDefault(new QueueSettings());
+   }
+   
+   public void test1PCCommit() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+                  
+      Transaction tx = new TransactionImpl();
+      
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      pm.commitTransaction(msgsToAdd, refsToRemove);
+      
+      EasyMock.replay(pm);
+      
+      tx.commit(true, pm);
+      
+      EasyMock.verify(pm);
+      
+      assertEquals(ref1, queue.list(null).get(0));
+   }
+   
+   public void test1PCRollback() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+                  
+      Transaction tx = new TransactionImpl();
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      pm.updateDeliveryCount(queue, ref2);
+      
+      EasyMock.replay(pm);
+      
+      tx.rollback(pm);
+      
+      EasyMock.verify(pm);
+ 
+      assertEquals(ref2, queue.list(null).get(0));
+   }
+   
+   public void test1PCPrepare() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+                  
+      Transaction tx = new TransactionImpl();
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      try
+      {
+         tx.prepare(pm);
+         fail("Should throw exception");
+      }
+      catch (IllegalStateException e)
+      {
+         //OK
+      }   
+      
+      assertTrue(queue.list(null).isEmpty());
+   }
+   
+   public void test2PCPrepareCommit() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+      
+      Xid xid = generateXid();
+                  
+      Transaction tx = new TransactionImpl(xid);
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      pm.prepareTransaction(xid, msgsToAdd, refsToRemove);
+      
+      EasyMock.replay(pm);
+      
+      tx.prepare(pm);
+      
+      EasyMock.verify(pm);
+      
+      EasyMock.reset(pm);
+      
+      pm.commitPreparedTransaction(xid);
+      
+      EasyMock.replay(pm);
+      
+      tx.commit(false, pm);
+      
+      EasyMock.verify(pm);
+   }
+   
+   public void test2PCCommitBeforePrepare() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+          
+      Xid xid = generateXid();
+      
+      Transaction tx = new TransactionImpl(xid);
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      try
+      {    
+         tx.commit(false, pm);
+         
+         fail ("Should throw exception");
+      }
+      catch (IllegalStateException e)
+      {
+         //Ok
+      }      
+   }
+   
+   public void test2PCPrepareRollback() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+      
+      Xid xid = generateXid();
+                  
+      Transaction tx = new TransactionImpl(xid);
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      pm.prepareTransaction(xid, msgsToAdd, refsToRemove);
+      
+      EasyMock.replay(pm);
+      
+      tx.prepare(pm);
+      
+      EasyMock.verify(pm);
+      
+      EasyMock.reset(pm);
+      
+      pm.unprepareTransaction(xid, msgsToAdd, refsToRemove);
+      
+      pm.updateDeliveryCount(queue, ref2);
+      
+      EasyMock.replay(pm);
+      
+      tx.rollback(pm);
+      
+      EasyMock.verify(pm);
+   }
+   
+   public void testSynchronizations() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+                  
+      Transaction tx = new TransactionImpl();
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      TransactionSynchronization sync = EasyMock.createStrictMock(TransactionSynchronization.class);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      tx.addSynchronization(sync);
+      
+      sync.beforeCommit();
+      sync.afterCommit();
+      
+      EasyMock.replay(sync);
+      
+      tx.commit(true, pm);
+      
+      EasyMock.verify(sync);
+      
+      EasyMock.reset(sync);
+      
+      tx = new TransactionImpl();
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      tx.addSynchronization(sync);
+      
+      sync.beforeRollback();
+      sync.afterRollback();
+      
+      EasyMock.replay(sync);
+      
+      tx.rollback(pm);
+      
+      EasyMock.verify(sync);            
+   }
+   
+   public void testSynchronizations2PC() throws Exception
+   {
+      List<Message> msgsToAdd = new ArrayList<Message>();
+      
+      List<MessageReference> refsToRemove = new ArrayList<MessageReference>();
+      
+      Queue queue = new QueueImpl(1, "queue1", null, false, true, false, -1, scheduledExecutor, queueSettings);
+      
+      MessageReference ref1 = this.generateReference(queue, 1);
+      msgsToAdd.add(ref1.getMessage());
+      
+      MessageReference ref2 = this.generateReference(queue, 2);
+      refsToRemove.add(ref2);
+      
+      Xid xid = generateXid();
+                  
+      Transaction tx = new TransactionImpl(xid);
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      TransactionSynchronization sync = EasyMock.createStrictMock(TransactionSynchronization.class);
+      
+      PersistenceManager pm = EasyMock.createStrictMock(PersistenceManager.class);
+      
+      tx.addSynchronization(sync);
+      
+      sync.beforeCommit();
+      sync.afterCommit();
+      
+      EasyMock.replay(sync);
+      
+      tx.prepare(pm);
+      tx.commit(false, pm);
+      
+      EasyMock.verify(sync);
+      
+      EasyMock.reset(sync);
+      
+      xid = generateXid();
+      
+      tx = new TransactionImpl(xid);
+      tx.addMessage(ref1.getMessage());
+      tx.addAcknowledgement(ref2);
+      
+      tx.addSynchronization(sync);
+      
+      sync.beforeRollback();
+      sync.afterRollback();
+      
+      EasyMock.replay(sync);
+      
+      tx.prepare(pm);
+      tx.rollback(pm);
+      
+      EasyMock.verify(sync);            
+   }
+   
+   // Inner classes -----------------------------------------------------------------------
+   
+}

Added: trunk/tests/src/org/jboss/messaging/core/util/test/unit/TokenBucketLimiterTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/core/util/test/unit/TokenBucketLimiterTest.java	                        (rev 0)
+++ trunk/tests/src/org/jboss/messaging/core/util/test/unit/TokenBucketLimiterTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -0,0 +1,130 @@
+/*
+  * 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.util.test.unit;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.util.TokenBucketLimiter;
+
+/**
+ * 
+ * A TokenBucketLimiterTest
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class TokenBucketLimiterTest extends TestCase
+{
+	private static final Logger log = Logger.getLogger(TokenBucketLimiterTest.class);
+	
+	public void testRateWithSpin1() throws Exception
+	{
+		testRate(1, true);		
+	}
+	
+	public void testRateWithSpin10() throws Exception
+	{
+		testRate(10, true);		
+	}
+	
+	public void testRateWithSpin100() throws Exception
+	{
+		testRate(100, true);		
+	}
+	
+	public void testRateWithSpin1000() throws Exception
+	{
+		testRate(1000, true);		
+	}
+	
+	public void testRateWithSpin10000() throws Exception
+	{
+		testRate(10000, true);		
+	}
+	
+	public void testRateWithSpin100000() throws Exception
+	{
+		testRate(100000, true);		
+	}
+		
+	public void testRateWithoutSpin1() throws Exception
+	{
+		testRate(1, false);		
+	}
+	
+	public void testRateWithoutSpin10() throws Exception
+	{
+		testRate(10, false);		
+	}
+	
+	public void testRateWithoutSpin100() throws Exception
+	{
+		testRate(100, false);		
+	}
+	
+	public void testRateWithoutSpin1000() throws Exception
+	{
+		testRate(1000, false);		
+	}
+	
+	public void testRateWithoutSpin10000() throws Exception
+	{
+		testRate(10000, false);		
+	}
+	
+	public void testRateWithoutSpin100000() throws Exception
+	{
+		testRate(100000, false);		
+	}
+	
+	private void testRate(int rate, boolean spin) throws Exception
+	{		
+		final double error = 0.05;    //Allow for 5% error
+		
+		TokenBucketLimiter tbl = new TokenBucketLimiter(rate, spin);
+		
+		long start = System.currentTimeMillis();
+		
+		int count = 0;
+		
+		final long measureTime = 5000;
+		
+		while (System.currentTimeMillis() - start < measureTime)
+		{				
+			tbl.limit();
+			
+			count++;
+		}
+				
+		long end  = System.currentTimeMillis();
+		
+		double actualRate = ((double)(1000 * count)) / ( end - start);
+    
+      log.info("Desired rate: " + rate + " Actual rate " + actualRate + " invs/sec");
+      
+      assertTrue(actualRate > rate * (1 - error));
+      
+      assertTrue(actualRate < rate * (1 + error));
+		
+	}
+}

Modified: trunk/tests/src/org/jboss/test/messaging/jms/AcknowledgementTest.java
===================================================================
--- trunk/tests/src/org/jboss/test/messaging/jms/AcknowledgementTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/test/messaging/jms/AcknowledgementTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -21,6 +21,8 @@
   */
 package org.jboss.test.messaging.jms;
 
+import java.util.ArrayList;
+
 import javax.jms.Connection;
 import javax.jms.ConnectionFactory;
 import javax.jms.DeliveryMode;
@@ -35,15 +37,9 @@
 import javax.jms.TopicSession;
 import javax.jms.TopicSubscriber;
 
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.jms.client.JBossSession;
-
 import EDU.oswego.cs.dl.util.concurrent.Latch;
 
-import java.util.List;
-import java.util.ArrayList;
 
-
 /**
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  *
@@ -833,8 +829,6 @@
      
    public void testMessageListenerAutoAck() throws Exception
    {
-      // FIXME the test hangs due to a race condition and never finish
-      fail("temporarily fails the test so that it does not hang the test suite");
       Connection conn = null;
       
       try
@@ -974,8 +968,6 @@
    public void testMessageListenerDupsOK() throws Exception
    {
       Connection conn = null;
-       // FIXME the test hangs due to a race condition and never finish
-      fail("temporarily fails the test so that it does not hang the test suite");
       try
       {
 	      
@@ -1048,8 +1040,6 @@
    public void testMessageListenerClientAck() throws Exception
    {
       Connection conn = null;
-       // FIXME the test hangs due to a race condition and never finish
-      fail("temporarily fails the test so that it does not hang the test suite");
       try
       {      
 	      conn = cf.createConnection();
@@ -1095,8 +1085,6 @@
    public void testMessageListenerTransactionalAck() throws Exception
    {
       Connection conn = null;
-       // FIXME the test hangs due to a race condition and never finish
-      fail("temporarily fails the test so that it does not hang the test suite");
       try
       {	      
 	      conn = cf.createConnection();

Modified: trunk/tests/src/org/jboss/test/messaging/jms/MessageConsumerTest.java
===================================================================
--- trunk/tests/src/org/jboss/test/messaging/jms/MessageConsumerTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/test/messaging/jms/MessageConsumerTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -969,9 +969,9 @@
 
           Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
           MessageProducer prod = sess.createProducer(queue1);
-          TextMessage tm1 = sess.createTextMessage("hello1");
-          TextMessage tm2 = sess.createTextMessage("hello2");
-          TextMessage tm3 = sess.createTextMessage("hello3");
+          TextMessage tm1 = sess.createTextMessage("hello1-a");
+          TextMessage tm2 = sess.createTextMessage("hello2-a");
+          TextMessage tm3 = sess.createTextMessage("hello3-a");
           prod.send(tm1);
           prod.send(tm2);
           prod.send(tm3);
@@ -981,7 +981,7 @@
 
           TextMessage rm1 = (TextMessage)cons1.receive(1500);
           assertNotNull(rm1);
-          assertEquals("hello1", rm1.getText());
+          assertEquals("hello1-a", rm1.getText());
 
           cons1.close();
 
@@ -991,11 +991,11 @@
 
           TextMessage rm2 = (TextMessage)cons2.receive(1500);
           assertNotNull(rm2);
-          assertEquals("hello2", rm2.getText());
+          assertEquals("hello2-a", rm2.getText());
 
           TextMessage rm3 = (TextMessage)cons2.receive(1500);
           assertNotNull(rm3);
-          assertEquals("hello3", rm3.getText());
+          assertEquals("hello3-a", rm3.getText());
           
           sess.commit();
        }

Modified: trunk/tests/src/org/jboss/test/messaging/jms/server/JMSServerManagerTest.java
===================================================================
--- trunk/tests/src/org/jboss/test/messaging/jms/server/JMSServerManagerTest.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/test/messaging/jms/server/JMSServerManagerTest.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -191,7 +191,7 @@
 
    public void testCreateAndDestroyConectionFactory() throws Exception
    {
-      jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 100, "newtestcf");
+      jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 100, 0, 0, "newtestcf");
       JBossConnectionFactory jbcf = (JBossConnectionFactory) getInitialContext().lookup("newtestcf");
       assertNotNull(jbcf);
       assertNotNull(jbcf.getDelegate());
@@ -208,7 +208,7 @@
       ArrayList<String> bindings = new ArrayList<String>();
       bindings.add("oranewtestcf");
       bindings.add("newtestcf");
-      jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 100, bindings);
+      jmsServerManager.createConnectionFactory("newtestcf", "anid", 100, true, 100, 1000, 0, bindings);
       jbcf = (JBossConnectionFactory) getInitialContext().lookup("newtestcf");
       assertNotNull(jbcf);
       assertNotNull(jbcf.getDelegate());

Modified: trunk/tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
===================================================================
--- trunk/tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-03-03 20:28:10 UTC (rev 3838)
+++ trunk/tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-03-04 14:08:59 UTC (rev 3839)
@@ -651,7 +651,8 @@
                                        int dupsOkBatchSize) throws Exception
    {
       log.info("deploying connection factory with name: " + objectName + " and dupsok: " + dupsOkBatchSize);
-      getJMSServerManager().createConnectionFactory(objectName, clientId, dupsOkBatchSize, strictTck, prefetchSize, jndiBindings);
+      getJMSServerManager().createConnectionFactory(objectName, clientId, dupsOkBatchSize,
+      		strictTck, prefetchSize, 1000, -1, jndiBindings);
    }
 
 




More information about the jboss-cvs-commits mailing list