You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@activemq.apache.org by an...@apache.org on 2014/11/11 12:00:31 UTC

[01/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Repository: activemq-6
Updated Branches:
  refs/heads/master 8ecd255f9 -> 177e6820b


http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java
new file mode 100644
index 0000000..ad3c514
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSendReceiveTest.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import javax.jms.Connection;
+import javax.jms.Destination;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+import javax.jms.Topic;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JmsDurableTopicSendReceiveTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest
+{
+
+   protected Connection connection2;
+   protected Session session2;
+   protected Session consumeSession2;
+   protected MessageConsumer consumer2;
+   protected MessageProducer producer2;
+   protected Destination consumerDestination2;
+   protected Destination producerDestination2;
+
+   /**
+    * Set up a durable suscriber test.
+    *
+    * @see junit.framework.TestCase#setUp()
+    */
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      this.durable = true;
+      super.setUp();
+   }
+
+   /**
+    * Test if all the messages sent are being received.
+    *
+    * @throws Exception
+    */
+   @Test
+   public void testSendWhileClosed() throws Exception
+   {
+      connection2 = factory.createConnection();
+      connection2.setClientID("test");
+      connection2.start();
+      session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      producer2 = session2.createProducer(null);
+      producer2.setDeliveryMode(deliveryMode);
+      producerDestination2 = this.createDestination2(session2, ActiveMQDestination.TOPIC_TYPE);
+      Thread.sleep(1000);
+
+      consumeSession2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      consumerDestination2 = this.createDestination2(session2, ActiveMQDestination.TOPIC_TYPE);
+      consumer2 = consumeSession2.createDurableSubscriber((Topic) consumerDestination2, getName());
+      Thread.sleep(1000);
+      consumer2.close();
+      TextMessage message = session2.createTextMessage("test");
+      message.setStringProperty("test", "test");
+      message.setJMSType("test");
+      producer2.send(producerDestination2, message);
+      System.out.println("Creating durable consumer");
+      consumer2 = consumeSession2.createDurableSubscriber((Topic) consumerDestination2, getName());
+      Message msg = consumer2.receive(1000);
+      assertNotNull(msg);
+      assertEquals(((TextMessage) msg).getText(), "test");
+      assertEquals(msg.getJMSType(), "test");
+      assertEquals(msg.getStringProperty("test"), "test");
+      connection2.stop();
+      connection2.close();
+   }
+
+
+   protected String getName()
+   {
+      return "testSendWhileClosed";
+   }
+
+}


[10/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterTestBase.java
index 5540517..97d45f6 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterTestBase.java
@@ -47,6 +47,12 @@ import org.hornetq.core.client.impl.Topology;
 import org.hornetq.core.client.impl.TopologyMemberImpl;
 import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.postoffice.Binding;
 import org.hornetq.core.postoffice.Bindings;
 import org.hornetq.core.postoffice.PostOffice;
@@ -58,8 +64,8 @@ import org.hornetq.core.server.HornetQServers;
 import org.hornetq.core.server.NodeManager;
 import org.hornetq.core.server.cluster.ClusterConnection;
 import org.hornetq.core.server.cluster.ClusterManager;
+import org.hornetq.core.server.cluster.HornetQServerSideProtocolManagerFactory;
 import org.hornetq.core.server.cluster.RemoteQueueBinding;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.cluster.impl.ClusterConnectionImpl;
 import org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum;
 import org.hornetq.core.server.group.GroupingHandler;
@@ -860,19 +866,19 @@ public abstract class ClusterTestBase extends ServiceTestBase
 
    protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node, final int timeout)
    {
-      setUpGroupHandler(type, node, timeout, -1, GroupingHandlerConfiguration.DEFAULT_REAPER_PERIOD);
+      setUpGroupHandler(type, node, timeout, -1, HornetQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod());
    }
 
    protected void setUpGroupHandler(final GroupingHandlerConfiguration.TYPE type, final int node, final int timeout, final long groupTimeout,
                                     final long reaperPeriod)
    {
-      servers[node].getConfiguration()
-         .setGroupingHandlerConfiguration(new GroupingHandlerConfiguration(new SimpleString("grouparbitrator"),
-                                                                           type,
-                                                                           new SimpleString("queues"),
-                                                                           timeout,
-                                                                           groupTimeout,
-                                                                           reaperPeriod));
+      servers[node].getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration()
+                                                                          .setName(new SimpleString("grouparbitrator"))
+                                                                          .setType(type)
+                                                                          .setAddress(new SimpleString("queues"))
+                                                                          .setTimeout(timeout)
+                                                                          .setGroupTimeout(groupTimeout)
+                                                                          .setReaperPeriod(reaperPeriod));
    }
 
    protected void setUpGroupHandler(final GroupingHandler groupingHandler, final int node)
@@ -1551,6 +1557,8 @@ public abstract class ClusterTestBase extends ServiceTestBase
          locators[node] = HornetQClient.createServerLocatorWithoutHA(serverTotc);
       }
 
+      locators[node].setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
+
       locators[node].setBlockOnNonDurableSend(true);
       locators[node].setBlockOnDurableSend(true);
       addServerLocator(locators[node]);
@@ -1632,33 +1640,44 @@ public abstract class ClusterTestBase extends ServiceTestBase
 
    protected void setupServer(final int node, final boolean fileStorage, final boolean netty) throws Exception
    {
-      setupLiveServer(node, fileStorage, false, netty);
+      setupLiveServer(node, fileStorage, false, netty, false);
+   }
+
+   protected void setupLiveServer(final int node, final boolean fileStorage, final boolean netty, boolean isLive) throws Exception
+   {
+      setupLiveServer(node, fileStorage, false, netty, isLive);
    }
 
    protected void setupLiveServer(final int node,
                                   final boolean fileStorage,
                                   final boolean sharedStorage,
-                                  final boolean netty) throws Exception
+                                  final boolean netty,
+                                  boolean liveOnly) throws Exception
    {
       if (servers[node] != null)
       {
          throw new IllegalArgumentException("Already a server at node " + node);
       }
 
-      Configuration configuration = createBasicConfig(node);
-
-      configuration.setJournalMaxIO_AIO(1000);
-
-      if (sharedStorage)
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
+      HAPolicyConfiguration haPolicyConfiguration = null;
+      if (liveOnly)
+      {
+         haPolicyConfiguration = new LiveOnlyPolicyConfiguration();
+      }
       else
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-
-      configuration.setThreadPoolMaxSize(10);
+      {
+         if (sharedStorage)
+            haPolicyConfiguration = new SharedStoreMasterPolicyConfiguration();
+         else
+            haPolicyConfiguration = new ReplicatedPolicyConfiguration();
+      }
 
-      configuration.getAcceptorConfigurations().clear();
-      configuration.getAcceptorConfigurations().add(createTransportConfiguration(netty, true,
-                                                                                 generateParams(node, netty)));
+      Configuration configuration = createBasicConfig(node)
+         .setJournalMaxIO_AIO(1000)
+         .setThreadPoolMaxSize(10)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(createTransportConfiguration(netty, true, generateParams(node, netty)))
+         .setHAPolicyConfiguration(haPolicyConfiguration);
 
       HornetQServer server;
 
@@ -1715,23 +1734,16 @@ public abstract class ClusterTestBase extends ServiceTestBase
          throw new IllegalArgumentException("Already a server at node " + node);
       }
 
-      Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node);
-
-      if (sharedStorage)
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      else
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-
-      configuration.getAcceptorConfigurations().clear();
-
-      TransportConfiguration acceptorConfig = createTransportConfiguration(netty, true, generateParams(node, netty));
-      configuration.getAcceptorConfigurations().add(acceptorConfig);
-
-      // add backup connector
       TransportConfiguration liveConfig = createTransportConfiguration(netty, false, generateParams(liveNode, netty));
-      configuration.getConnectorConfigurations().put(liveConfig.getName(), liveConfig);
       TransportConfiguration backupConfig = createTransportConfiguration(netty, false, generateParams(node, netty));
-      configuration.getConnectorConfigurations().put(backupConfig.getName(), backupConfig);
+      TransportConfiguration acceptorConfig = createTransportConfiguration(netty, true, generateParams(node, netty));
+
+      Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(acceptorConfig)
+         .addConnectorConfiguration(liveConfig.getName(), liveConfig)
+         .addConnectorConfiguration(backupConfig.getName(), backupConfig)
+         .setHAPolicyConfiguration(sharedStorage ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration());
 
       HornetQServer server;
 
@@ -1760,41 +1772,35 @@ public abstract class ClusterTestBase extends ServiceTestBase
          throw new IllegalArgumentException("Already a server at node " + node);
       }
 
-      Configuration configuration = createBasicConfig(node);
-
-      configuration.setJournalMaxIO_AIO(1000);
-
-      if (sharedStorage)
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      else
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-
-      configuration.getAcceptorConfigurations().clear();
-
       Map<String, Object> params = generateParams(node, netty);
 
-      configuration.getAcceptorConfigurations().add(createTransportConfiguration(netty, true, params));
-
       TransportConfiguration connector = createTransportConfiguration(netty, false, params);
-      configuration.getConnectorConfigurations().put(connector.getName(), connector);
 
       List<String> connectorPairs = new ArrayList<String>();
       connectorPairs.add(connector.getName());
 
-      UDPBroadcastGroupConfiguration endpoint = new UDPBroadcastGroupConfiguration(groupAddress, port, null, -1);
-
-      BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration("bg1",
-                                                                             200,
-                                                                             connectorPairs,
-                                                                             endpoint);
-
-      configuration.getBroadcastGroupConfigurations().add(bcConfig);
-
-      DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration("dg1",
-                                                                             1000,
-                                                                             1000, endpoint);
-
-      configuration.getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig);
+      UDPBroadcastGroupConfiguration endpoint = new UDPBroadcastGroupConfiguration().setGroupAddress(groupAddress).setGroupPort(port);
+
+      BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration()
+         .setName("bg1")
+         .setBroadcastPeriod(200)
+         .setConnectorInfos(connectorPairs)
+         .setEndpointFactoryConfiguration(endpoint);
+
+      DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration()
+         .setName("dg1")
+         .setRefreshTimeout(1000)
+         .setDiscoveryInitialWaitTimeout(1000)
+         .setBroadcastEndpointFactoryConfiguration(endpoint);
+
+      Configuration configuration = createBasicConfig(node)
+         .setJournalMaxIO_AIO(1000)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(createTransportConfiguration(netty, true, params))
+         .addConnectorConfiguration(connector.getName(), connector)
+         .addBroadcastGroupConfiguration(bcConfig)
+         .addDiscoveryGroupConfiguration(dcConfig.getName(), dcConfig)
+         .setHAPolicyConfiguration(sharedStorage ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration());
 
       HornetQServer server;
       if (fileStorage)
@@ -1837,40 +1843,34 @@ public abstract class ClusterTestBase extends ServiceTestBase
          throw new IllegalArgumentException("Already a server at node " + node);
       }
 
-      Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node);
-
-      if (sharedStorage)
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      else
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-
-      configuration.getAcceptorConfigurations().clear();
-
       Map<String, Object> params = generateParams(node, netty);
 
-      configuration.getAcceptorConfigurations().add(createTransportConfiguration(netty, true, params));
-
       TransportConfiguration connector = createTransportConfiguration(netty, false, params);
-      configuration.getConnectorConfigurations().put(connector.getName(), connector);
 
       List<String> connectorPairs = new ArrayList<String>();
       connectorPairs.add(connector.getName());
 
-      UDPBroadcastGroupConfiguration endpoint = new UDPBroadcastGroupConfiguration(groupAddress, port, null, -1);
-
-      BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration("bg1",
-                                                                             1000,
-                                                                             connectorPairs,
-                                                                             endpoint);
+      UDPBroadcastGroupConfiguration endpoint = new UDPBroadcastGroupConfiguration().setGroupAddress(groupAddress).setGroupPort(port);
 
-      configuration.getBroadcastGroupConfigurations().add(bcConfig);
+      BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration()
+         .setName("bg1")
+         .setBroadcastPeriod(1000)
+         .setConnectorInfos(connectorPairs)
+         .setEndpointFactoryConfiguration(endpoint);
 
-      DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration("dg1",
-                                                                             5000,
-                                                                             5000,
-                                                                             endpoint);
+      DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration()
+         .setName("dg1")
+         .setRefreshTimeout(5000)
+         .setDiscoveryInitialWaitTimeout(5000)
+         .setBroadcastEndpointFactoryConfiguration(endpoint);
 
-      configuration.getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig);
+      Configuration configuration = createBasicConfig(sharedStorage ? liveNode : node)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(createTransportConfiguration(netty, true, params))
+         .addConnectorConfiguration(connector.getName(), connector)
+         .addBroadcastGroupConfiguration(bcConfig)
+         .addDiscoveryGroupConfiguration(dcConfig.getName(), dcConfig)
+         .setHAPolicyConfiguration(sharedStorage ? new SharedStoreSlavePolicyConfiguration() : new ReplicatedPolicyConfiguration());
 
       HornetQServer server;
       if (sharedStorage)
@@ -1935,15 +1935,18 @@ public abstract class ClusterTestBase extends ServiceTestBase
          pairs.add(serverTotc.getName());
       }
       Configuration config = serverFrom.getConfiguration();
-      ClusterConnectionConfiguration clusterConf =
-         new ClusterConnectionConfiguration(name, address, name,
-                                            100,
-                                            true,
-                                            forwardWhenNoConsumers,
-                                            maxHops,
-                                            1024,
-                                            pairs,
-                                            allowDirectConnectionsOnly);
+
+      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration()
+         .setName(name)
+         .setAddress(address)
+         .setConnectorName(name)
+         .setRetryInterval(100)
+         .setForwardWhenNoConsumers(forwardWhenNoConsumers)
+         .setMaxHops(maxHops)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(pairs)
+         .setAllowDirectConnectionsOnly(allowDirectConnectionsOnly);
+
       config.getClusterConfigurations().add(clusterConf);
    }
 
@@ -1978,16 +1981,19 @@ public abstract class ClusterTestBase extends ServiceTestBase
          pairs.add(serverTotc.getName());
       }
       Configuration config = serverFrom.getConfiguration();
-      ClusterConnectionConfiguration clusterConf =
-            new ClusterConnectionConfiguration(name, address, name,
-                  retryInterval,
-                  true,
-                  forwardWhenNoConsumers,
-                  maxHops,
-                  1024,
-                  pairs,
-                  allowDirectConnectionsOnly);
-      clusterConf.setReconnectAttempts(reconnectAttempts);
+
+      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration()
+         .setName(name)
+         .setAddress(address)
+         .setConnectorName(name)
+         .setReconnectAttempts(reconnectAttempts)
+         .setRetryInterval(retryInterval)
+         .setForwardWhenNoConsumers(forwardWhenNoConsumers)
+         .setMaxHops(maxHops)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(pairs)
+         .setAllowDirectConnectionsOnly(allowDirectConnectionsOnly);
+
       config.getClusterConfigurations().add(clusterConf);
    }
 
@@ -2054,18 +2060,19 @@ public abstract class ClusterTestBase extends ServiceTestBase
          pairs.add(serverTotc.getName());
       }
       Configuration conf = serverFrom.getConfiguration();
-      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration(
-         name, address, connectorFrom.getName(),
-         HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-         HornetQDefaultConfiguration.getDefaultClusterFailureCheckPeriod(),
-         HornetQDefaultConfiguration.getDefaultClusterConnectionTtl(),
-         retryInterval,
-         HornetQDefaultConfiguration.getDefaultClusterRetryIntervalMultiplier(),
-         HornetQDefaultConfiguration.getDefaultClusterMaxRetryInterval(),
-         -1, reconnectAttempts, 1000, 1000, true, forwardWhenNoConsumers, maxHops,
-         1024, pairs, false,
-         HornetQDefaultConfiguration.getDefaultClusterNotificationInterval(),
-         HornetQDefaultConfiguration.getDefaultClusterNotificationAttempts(), null);
+
+      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration()
+         .setName(name)
+         .setAddress(address)
+         .setConnectorName(connectorFrom.getName())
+         .setRetryInterval(retryInterval)
+         .setReconnectAttempts(reconnectAttempts)
+         .setCallTimeout(100)
+         .setCallFailoverTimeout(100)
+         .setForwardWhenNoConsumers(forwardWhenNoConsumers)
+         .setMaxHops(maxHops)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(pairs);
 
       conf.getClusterConfigurations().add(clusterConf);
    }
@@ -2074,8 +2081,15 @@ public abstract class ClusterTestBase extends ServiceTestBase
                                                               final boolean forwardWhenNoConsumers, final int maxHops,
                                                               TransportConfiguration connectorFrom, List<String> pairs)
    {
-      return new ClusterConnectionConfiguration(name, address, connectorFrom.getName(), 250, true,
-                                                forwardWhenNoConsumers, maxHops, 1024, pairs, false);
+      return new ClusterConnectionConfiguration()
+         .setName(name)
+         .setAddress(address)
+         .setConnectorName(connectorFrom.getName())
+         .setRetryInterval(250)
+         .setForwardWhenNoConsumers(forwardWhenNoConsumers)
+         .setMaxHops(maxHops)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(pairs);
    }
 
    protected void setupClusterConnectionWithBackups(final String name,
@@ -2104,9 +2118,16 @@ public abstract class ClusterTestBase extends ServiceTestBase
          pairs.add(serverTotc.getName());
       }
       Configuration config = serverFrom.getConfiguration();
-      ClusterConnectionConfiguration clusterConf =
-         new ClusterConnectionConfiguration(name, address, name, 250, true, forwardWhenNoConsumers, maxHops,
-                                            1024, pairs, false);
+
+      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration()
+         .setName(name)
+         .setAddress(address)
+         .setConnectorName(name)
+         .setRetryInterval(250)
+         .setForwardWhenNoConsumers(forwardWhenNoConsumers)
+         .setMaxHops(maxHops)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(pairs);
 
       config.getClusterConfigurations().add(clusterConf);
    }
@@ -2129,13 +2150,16 @@ public abstract class ClusterTestBase extends ServiceTestBase
       TransportConfiguration connectorConfig = createTransportConfiguration(netty, false, generateParams(node, netty));
       server.getConfiguration().getConnectorConfigurations().put(name, connectorConfig);
       Configuration conf = server.getConfiguration();
-      ClusterConnectionConfiguration clusterConf =
-         new ClusterConnectionConfiguration(name, address, name, 100,
-                                            true,
-                                            forwardWhenNoConsumers,
-                                            maxHops,
-                                            1024,
-                                            discoveryGroupName);
+      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration()
+         .setName(name)
+         .setAddress(address)
+         .setConnectorName(name)
+         .setRetryInterval(100)
+         .setDuplicateDetection(true)
+         .setForwardWhenNoConsumers(forwardWhenNoConsumers)
+         .setMaxHops(maxHops)
+         .setConfirmationWindowSize(1024)
+         .setDiscoveryGroupName(discoveryGroupName);
       List<ClusterConnectionConfiguration> clusterConfs = conf.getClusterConfigurations();
 
       clusterConfs.add(clusterConf);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterWithBackupTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterWithBackupTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterWithBackupTest.java
index 73a63db..f6099c4 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterWithBackupTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusterWithBackupTest.java
@@ -117,9 +117,9 @@ public class ClusterWithBackupTest extends ClusterTestBase
       setupBackupServer(2, 5, isFileStorage(), true, isNetty());
 
       // The lives
-      setupLiveServer(3, isFileStorage(), true, isNetty());
-      setupLiveServer(4, isFileStorage(), true, isNetty());
-      setupLiveServer(5, isFileStorage(), true, isNetty());
+      setupLiveServer(3, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(4, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(5, isFileStorage(), true, isNetty(), false);
 
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusteredGroupingTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusteredGroupingTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusteredGroupingTest.java
index 64bc03b..895595e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusteredGroupingTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/ClusteredGroupingTest.java
@@ -29,7 +29,7 @@ import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientProducer;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.postoffice.impl.BindingsImpl;
 import org.hornetq.core.server.group.GroupingHandler;
 import org.hornetq.core.server.group.UnproposalListener;
@@ -98,7 +98,8 @@ public class ClusteredGroupingTest extends ClusterTestBase
          @Override
          public void onNotification(Notification notification)
          {
-            if (notification.getType() == NotificationType.UNPROPOSAL)
+            if (!(notification.getType() instanceof CoreNotificationType)) return;
+            if (notification.getType() == CoreNotificationType.UNPROPOSAL)
             {
                latch.countDown();
             }
@@ -109,7 +110,8 @@ public class ClusteredGroupingTest extends ClusterTestBase
          @Override
          public void onNotification(Notification notification)
          {
-            if (notification.getType() == NotificationType.UNPROPOSAL)
+            if (!(notification.getType() instanceof CoreNotificationType)) return;
+            if (notification.getType() == CoreNotificationType.UNPROPOSAL)
             {
                latch.countDown();
             }
@@ -205,7 +207,8 @@ public class ClusteredGroupingTest extends ClusterTestBase
          @Override
          public void onNotification(Notification notification)
          {
-            if (notification.getType() == NotificationType.UNPROPOSAL)
+            if (!(notification.getType() instanceof CoreNotificationType)) return;
+            if (notification.getType() == CoreNotificationType.UNPROPOSAL)
             {
                latch.countDown();
             }
@@ -216,7 +219,8 @@ public class ClusteredGroupingTest extends ClusterTestBase
          @Override
          public void onNotification(Notification notification)
          {
-            if (notification.getType() == NotificationType.UNPROPOSAL)
+            if (!(notification.getType() instanceof CoreNotificationType)) return;
+            if (notification.getType() == CoreNotificationType.UNPROPOSAL)
             {
                latch.countDown();
             }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/MessageRedistributionTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/MessageRedistributionTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/MessageRedistributionTest.java
index f35b5b9..bff10b5 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/MessageRedistributionTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/MessageRedistributionTest.java
@@ -76,10 +76,14 @@ public class MessageRedistributionTest extends ClusterTestBase
       MessageRedistributionTest.log.info("Doing test");
 
 
-      getServer(0).getConfiguration().setGroupingHandlerConfiguration(
-         new GroupingHandlerConfiguration(new SimpleString("handler"), GroupingHandlerConfiguration.TYPE.LOCAL, new SimpleString("queues")));
-      getServer(1).getConfiguration().setGroupingHandlerConfiguration(
-         new GroupingHandlerConfiguration(new SimpleString("handler"), GroupingHandlerConfiguration.TYPE.REMOTE, new SimpleString("queues")));
+      getServer(0).getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration()
+                                                                         .setName(new SimpleString("handler"))
+                                                                         .setType(GroupingHandlerConfiguration.TYPE.LOCAL)
+                                                                         .setAddress(new SimpleString("queues")));
+      getServer(1).getConfiguration().setGroupingHandlerConfiguration(new GroupingHandlerConfiguration()
+                                                                         .setName(new SimpleString("handler"))
+                                                                         .setType(GroupingHandlerConfiguration.TYPE.REMOTE)
+                                                                         .setAddress(new SimpleString("queues")));
 
       startServers(0, 1);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java
index 6a263b3..7578fb3 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SimpleSymmetricClusterTest.java
@@ -67,9 +67,9 @@ public class SimpleSymmetricClusterTest extends ClusterTestBase
       setupBackupServer(2, 5, isFileStorage(), true, isNetty());
 
       // The lives
-      setupLiveServer(3, isFileStorage(), true, isNetty());
-      setupLiveServer(4, isFileStorage(), true, isNetty());
-      setupLiveServer(5, isFileStorage(), true, isNetty());
+      setupLiveServer(3, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(4, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(5, isFileStorage(), true, isNetty(), false);
 
       setupClusterConnection("cluster0", "queues", false, 1, isNetty(), 3, 4, 5);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterTest.java
index e750d6c..58ed3e8 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterTest.java
@@ -25,6 +25,7 @@ import org.hornetq.tests.util.UnitTestCase;
  * Most of the cases are covered in OneWayTwoNodeClusterTest - we don't duplicate them all here
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mtaylor@redhat,com">Martyn Taylor</a>
  *
  * Created 3 Feb 2009 09:10:43
  *
@@ -1760,6 +1761,196 @@ public class SymmetricClusterTest extends ClusterTestBase
       waitForBindings(4, "queues.testaddress", 0, 0, false);
    }
 
+   @Test
+   /**
+    * This test verifies that addresses matching a simple string filter such as 'jms' result in bindings being created
+    * on appropriate nodes in the cluster.  It also verifies that addresses not matching the simple string filter do not
+    * result in bindings being created.
+    */
+   public void testClusterAddressCreatesBindingsForSimpleStringAddressFilters() throws Exception
+   {
+      setupCluster("jms", "jms", "jms", "jms", "jms");
+      startServers();
+
+      setupSessionFactory(0, isNetty());
+      setupSessionFactory(1, isNetty());
+      setupSessionFactory(2, isNetty());
+      setupSessionFactory(3, isNetty());
+      setupSessionFactory(4, isNetty());
+
+      createQueue(0, "jms.queues.test.1", "queue0", null, false);
+      createQueue(1, "jms.queues.test.1", "queue0", null, false);
+      createQueue(2, "jms.queues.test.1", "queue0", null, false);
+      createQueue(3, "jms.queues.test.1", "queue0", null, false);
+      createQueue(4, "jms.queues.test.1", "queue0", null, false);
+
+      createQueue(0, "foo.queues.test.1", "queue1", null, false);
+      createQueue(1, "foo.queues.test.1", "queue1", null, false);
+      createQueue(2, "foo.queues.test.1", "queue1", null, false);
+      createQueue(3, "foo.queues.test.1", "queue1", null, false);
+      createQueue(4, "foo.queues.test.1", "queue1", null, false);
+
+      waitForBindings(0, "jms.queues.test.1", 4, 0, false);
+      waitForBindings(1, "jms.queues.test.1", 4, 0, false);
+      waitForBindings(2, "jms.queues.test.1", 4, 0, false);
+      waitForBindings(3, "jms.queues.test.1", 4, 0, false);
+      waitForBindings(4, "jms.queues.test.1", 4, 0, false);
+
+      waitForBindings(0, "foo.queues.test.1", 0, 0, false);
+      waitForBindings(1, "foo.queues.test.1", 0, 0, false);
+      waitForBindings(2, "foo.queues.test.1", 0, 0, false);
+      waitForBindings(3, "foo.queues.test.1", 0, 0, false);
+      waitForBindings(4, "foo.queues.test.1", 0, 0, false);
+   }
+
+   @Test
+   /**
+    * This test verifies that an string exclude filter '!jms.eu.uk' results in bindings not being created for this
+    * address for nodes in a cluster.  But ensures that other addresses are matched and bindings created.
+    */
+   public void testClusterAddressDoesNotCreatesBindingsForStringExcludesAddressFilters() throws Exception
+   {
+      setupCluster("jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk", "jms.eu.de,!jms.eu.uk");
+      startServers();
+
+      setupSessionFactory(0, isNetty());
+      setupSessionFactory(1, isNetty());
+      setupSessionFactory(2, isNetty());
+      setupSessionFactory(3, isNetty());
+      setupSessionFactory(4, isNetty());
+
+      createQueue(0, "jms.eu.uk", "queue0", null, false);
+      createQueue(1, "jms.eu.uk", "queue0", null, false);
+      createQueue(2, "jms.eu.uk", "queue0", null, false);
+      createQueue(3, "jms.eu.uk", "queue0", null, false);
+      createQueue(4, "jms.eu.uk", "queue0", null, false);
+
+      createQueue(0, "jms.eu.de", "queue1", null, false);
+      createQueue(1, "jms.eu.de", "queue1", null, false);
+      createQueue(2, "jms.eu.de", "queue1", null, false);
+      createQueue(3, "jms.eu.de", "queue1", null, false);
+      createQueue(4, "jms.eu.de", "queue1", null, false);
+
+      waitForBindings(0, "jms.eu.de", 4, 0, false);
+      waitForBindings(1, "jms.eu.de", 4, 0, false);
+      waitForBindings(2, "jms.eu.de", 4, 0, false);
+      waitForBindings(3, "jms.eu.de", 4, 0, false);
+      waitForBindings(4, "jms.eu.de", 4, 0, false);
+
+      waitForBindings(0, "jms.eu.uk", 0, 0, false);
+      waitForBindings(1, "jms.eu.uk", 0, 0, false);
+      waitForBindings(2, "jms.eu.uk", 0, 0, false);
+      waitForBindings(3, "jms.eu.uk", 0, 0, false);
+      waitForBindings(4, "jms.eu.uk", 0, 0, false);
+   }
+
+   /**
+    * This test verifies that remote bindings are only created for queues that match jms.eu or jms.us excluding
+    * jms.eu.uk and jms.us.bos.  Represented by the address filter 'jms.eu,!jms.eu.uk,jms.us,!jms.us.bos'
+    * @throws Exception
+    */
+   @Test
+   public void testClusterAddressFiltersExcludesAndIncludesAddressesInList() throws Exception
+   {
+      setupCluster("jms.eu,!jms.eu.uk,jms.us,!jms.us.bos",
+                   "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos",
+                   "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos",
+                   "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos",
+                   "jms.eu,!jms.eu.uk,jms.us,!jms.us.bos");
+
+      startServers();
+
+      setupSessionFactory(0, isNetty());
+      setupSessionFactory(1, isNetty());
+      setupSessionFactory(2, isNetty());
+      setupSessionFactory(3, isNetty());
+      setupSessionFactory(4, isNetty());
+
+      createQueue(0, "jms.eu.uk", "queue0", null, false);
+      createQueue(1, "jms.eu.uk", "queue0", null, false);
+      createQueue(2, "jms.eu.uk", "queue0", null, false);
+      createQueue(3, "jms.eu.uk", "queue0", null, false);
+      createQueue(4, "jms.eu.uk", "queue0", null, false);
+
+      createQueue(0, "jms.eu.de", "queue1", null, false);
+      createQueue(1, "jms.eu.de", "queue1", null, false);
+      createQueue(2, "jms.eu.de", "queue1", null, false);
+      createQueue(3, "jms.eu.de", "queue1", null, false);
+      createQueue(4, "jms.eu.de", "queue1", null, false);
+
+      createQueue(0, "jms.eu.fr", "queue2", null, false);
+      createQueue(1, "jms.eu.fr", "queue2", null, false);
+      createQueue(2, "jms.eu.fr", "queue2", null, false);
+      createQueue(3, "jms.eu.fr", "queue2", null, false);
+      createQueue(4, "jms.eu.fr", "queue2", null, false);
+
+      createQueue(0, "jms.us.ca", "queue4", null, false);
+      createQueue(1, "jms.us.ca", "queue4", null, false);
+      createQueue(2, "jms.us.ca", "queue4", null, false);
+      createQueue(3, "jms.us.ca", "queue4", null, false);
+      createQueue(4, "jms.us.ca", "queue4", null, false);
+
+      createQueue(0, "jms.us.se", "queue5", null, false);
+      createQueue(1, "jms.us.se", "queue5", null, false);
+      createQueue(2, "jms.us.se", "queue5", null, false);
+      createQueue(3, "jms.us.se", "queue5", null, false);
+      createQueue(4, "jms.us.se", "queue5", null, false);
+
+      createQueue(0, "jms.us.ny", "queue6", null, false);
+      createQueue(1, "jms.us.ny", "queue6", null, false);
+      createQueue(2, "jms.us.ny", "queue6", null, false);
+      createQueue(3, "jms.us.ny", "queue6", null, false);
+      createQueue(4, "jms.us.ny", "queue6", null, false);
+
+      waitForBindings(0, "jms.eu.de", 4, 0, false);
+      waitForBindings(1, "jms.eu.de", 4, 0, false);
+      waitForBindings(2, "jms.eu.de", 4, 0, false);
+      waitForBindings(3, "jms.eu.de", 4, 0, false);
+      waitForBindings(4, "jms.eu.de", 4, 0, false);
+
+      waitForBindings(0, "jms.eu.fr", 4, 0, false);
+      waitForBindings(1, "jms.eu.fr", 4, 0, false);
+      waitForBindings(2, "jms.eu.fr", 4, 0, false);
+      waitForBindings(3, "jms.eu.fr", 4, 0, false);
+      waitForBindings(4, "jms.eu.fr", 4, 0, false);
+
+      waitForBindings(0, "jms.eu.uk", 0, 0, false);
+      waitForBindings(1, "jms.eu.uk", 0, 0, false);
+      waitForBindings(2, "jms.eu.uk", 0, 0, false);
+      waitForBindings(3, "jms.eu.uk", 0, 0, false);
+      waitForBindings(4, "jms.eu.uk", 0, 0, false);
+
+      waitForBindings(0, "jms.us.ca", 4, 0, false);
+      waitForBindings(1, "jms.us.ca", 4, 0, false);
+      waitForBindings(2, "jms.us.ca", 4, 0, false);
+      waitForBindings(3, "jms.us.ca", 4, 0, false);
+      waitForBindings(4, "jms.us.ca", 4, 0, false);
+
+      waitForBindings(0, "jms.us.ny", 4, 0, false);
+      waitForBindings(1, "jms.us.ny", 4, 0, false);
+      waitForBindings(2, "jms.us.ny", 4, 0, false);
+      waitForBindings(3, "jms.us.ny", 4, 0, false);
+      waitForBindings(4, "jms.us.ny", 4, 0, false);
+
+      waitForBindings(0, "jms.us.bos", 0, 0, false);
+      waitForBindings(1, "jms.us.bos", 0, 0, false);
+      waitForBindings(2, "jms.us.bos", 0, 0, false);
+      waitForBindings(3, "jms.us.bos", 0, 0, false);
+      waitForBindings(4, "jms.us.bos", 0, 0, false);
+   }
+
+   protected void setupCluster(String addr1, String addr2, String addr3, String addr4, String addr5) throws Exception
+   {
+      setupClusterConnection("cluster0", addr1, true, 1, isNetty(), 0, 1, 2, 3, 4);
+
+      setupClusterConnection("cluster1", addr2, true, 1, isNetty(), 1, 0, 2, 3, 4);
+
+      setupClusterConnection("cluster2", addr3, true, 1, isNetty(), 2, 0, 1, 3, 4);
+
+      setupClusterConnection("cluster3", addr4, true, 1, isNetty(), 3, 0, 1, 2, 4);
+      setupClusterConnection("cluster4", addr5, true, 1, isNetty(), 4, 0, 1, 2, 3);
+   }
+
    protected void setupCluster() throws Exception
    {
       setupCluster(false);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java
index b65c547..4dc5af7 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/distribution/SymmetricClusterWithBackupTest.java
@@ -12,7 +12,7 @@
  */
 package org.hornetq.tests.integration.cluster.distribution;
 
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.tests.integration.IntegrationTestLogger;
 import org.hornetq.tests.util.UnitTestCase;
 import org.junit.Test;
@@ -539,11 +539,11 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest
       setupBackupServer(9, 4, isFileStorage(), true, isNetty());
 
       // The lives
-      setupLiveServer(0, isFileStorage(), true, isNetty());
-      setupLiveServer(1, isFileStorage(), true, isNetty());
-      setupLiveServer(2, isFileStorage(), true, isNetty());
-      setupLiveServer(3, isFileStorage(), true, isNetty());
-      setupLiveServer(4, isFileStorage(), true, isNetty());
+      setupLiveServer(0, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(1, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(2, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(3, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(4, isFileStorage(), true, isNetty(), false);
    }
 
    @Override
@@ -551,11 +551,11 @@ public class SymmetricClusterWithBackupTest extends SymmetricClusterTest
    {
       // Need to set backup, since when restarting backup after it has failed over, backup will have been set to false
 
-      getServer(5).getConfiguration().getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      getServer(6).getConfiguration().getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      getServer(7).getConfiguration().getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      getServer(8).getConfiguration().getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      getServer(9).getConfiguration().getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
+      getServer(5).getConfiguration().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
+      getServer(6).getConfiguration().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
+      getServer(7).getConfiguration().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
+      getServer(8).getConfiguration().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
+      getServer(9).getConfiguration().setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
 
       startServers(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java
index 0023973..52ca1fb 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/AutomaticColocatedQuorumVoteTest.java
@@ -21,17 +21,22 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.Topology;
 import org.hornetq.core.client.impl.TopologyMemberImpl;
-import org.hornetq.core.config.BackupStrategy;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.CoreQueueConfiguration;
+import org.hornetq.core.config.ScaleDownConfiguration;
+import org.hornetq.core.config.ha.ColocatedPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.impl.HornetQServerImpl;
 import org.hornetq.tests.util.ServiceTestBase;
 import org.junit.Test;
@@ -41,27 +46,27 @@ import org.junit.runners.Parameterized;
 @RunWith(value = Parameterized.class)
 public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
 {
-   private final HAPolicy.POLICY_TYPE policyType;
+   private final boolean replicated;
 
-   @Parameterized.Parameters
+   @Parameterized.Parameters(name = "replicated={0}")
    public static Collection getParameters()
    {
       return Arrays.asList(new Object[][]
       {
-         {HAPolicy.POLICY_TYPE.COLOCATED_REPLICATED},
-         {HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE}
+         {true},
+         {false}
       });
    }
 
-   public AutomaticColocatedQuorumVoteTest(HAPolicy.POLICY_TYPE policyType)
+   public AutomaticColocatedQuorumVoteTest(boolean replicated)
    {
-      this.policyType = policyType;
+      this.replicated = replicated;
    }
    @Test
    public void testSimpleDistributionBackupStrategyFull() throws Exception
    {
-      HornetQServer server0 = createServer(0, 1, BackupStrategy.FULL);
-      HornetQServer server1 = createServer(1, 0, BackupStrategy.FULL);
+      HornetQServer server0 = createServer(0, 1, false);
+      HornetQServer server1 = createServer(1, 0, false);
       TransportConfiguration liveConnector0 = getConnectorTransportConfiguration("liveConnector" + 0, 0);
       TransportConfiguration liveConnector1 = getConnectorTransportConfiguration("liveConnector" + 1, 1);
 
@@ -103,7 +108,7 @@ public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
          assertEquals(2, connectorConfigurations1.size());
          assertEquals("5546", connectorConfigurations1.get("liveConnector1").getParams().get("port"));
          assertEquals("5445", connectorConfigurations1.get("remoteConnector1").getParams().get("port"));
-         if (policyType == HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE)
+         if (!replicated)
          {
             assertEquals(server0.getConfiguration().getJournalDirectory(), backupServer1.getConfiguration().getJournalDirectory());
             assertEquals(server0.getConfiguration().getBindingsDirectory(), backupServer1.getConfiguration().getBindingsDirectory());
@@ -128,7 +133,14 @@ public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
       }
       finally
       {
-         server0.stop();
+         try
+         {
+            server0.stop();
+         }
+         catch (Throwable e)
+         {
+            e.printStackTrace();
+         }
          server1.stop();
       }
    }
@@ -136,8 +148,8 @@ public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
    @Test
    public void testSimpleDistributionBackupStrategyScaleDown() throws Exception
    {
-      HornetQServer server0 = createServer(0, 1, BackupStrategy.SCALE_DOWN);
-      HornetQServer server1 = createServer(1, 0, BackupStrategy.SCALE_DOWN);
+      HornetQServer server0 = createServer(0, 1, true);
+      HornetQServer server1 = createServer(1, 0, true);
       TransportConfiguration liveConnector0 = getConnectorTransportConfiguration("liveConnector" + 0, 0);
       TransportConfiguration liveConnector1 = getConnectorTransportConfiguration("liveConnector" + 1, 1);
 
@@ -177,7 +189,7 @@ public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
          assertEquals(2, connectorConfigurations1.size());
          assertEquals("5446", connectorConfigurations1.get("liveConnector1").getParams().get("port"));
          assertEquals("5445", connectorConfigurations1.get("remoteConnector1").getParams().get("port"));
-         if (policyType == HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE)
+         if (!replicated)
          {
             assertEquals(server0.getConfiguration().getJournalDirectory(), backupServer1.getConfiguration().getJournalDirectory());
             assertEquals(server0.getConfiguration().getBindingsDirectory(), backupServer1.getConfiguration().getBindingsDirectory());
@@ -202,7 +214,14 @@ public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
       }
       finally
       {
-         server0.stop();
+         try
+         {
+            server0.stop();
+         }
+         catch (Throwable e)
+         {
+            e.printStackTrace();
+         }
          server1.stop();
       }
    }
@@ -210,10 +229,10 @@ public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
    @Test
    public void testSimpleDistributionOfBackupsMaxBackupsExceeded() throws Exception
    {
-      HornetQServer server0 = createServer(0, 1, BackupStrategy.FULL);
-      HornetQServer server1 = createServer(1, 0, BackupStrategy.FULL);
-      HornetQServer server2 = createServer(2, 0, BackupStrategy.FULL);
-      HornetQServer server3 = createServer(3, 0, BackupStrategy.FULL);
+      HornetQServer server0 = createServer(0, 1, false);
+      HornetQServer server1 = createServer(1, 0, false);
+      HornetQServer server2 = createServer(2, 0, false);
+      HornetQServer server3 = createServer(3, 0, false);
       TransportConfiguration liveConnector0 = getConnectorTransportConfiguration("liveConnector" + 0, 0);
       TransportConfiguration liveConnector1 = getConnectorTransportConfiguration("liveConnector" + 1, 1);
       TransportConfiguration liveConnector2 = getConnectorTransportConfiguration("liveConnector" + 2, 2);
@@ -274,45 +293,69 @@ public class AutomaticColocatedQuorumVoteTest extends ServiceTestBase
       }
    }
 
-   private HornetQServer createServer(int node, int remoteNode, BackupStrategy backupStrategy) throws Exception
+   private HornetQServer createServer(int node, int remoteNode, boolean scaleDown) throws Exception
    {
       TransportConfiguration liveConnector = getConnectorTransportConfiguration("liveConnector" + node, node);
       TransportConfiguration remoteConnector = getConnectorTransportConfiguration("remoteConnector" + node, remoteNode);
       TransportConfiguration liveAcceptor = getAcceptorTransportConfiguration(node);
-      Configuration liveConfiguration = getConfiguration("server" + node, backupStrategy, liveConnector, liveAcceptor, remoteConnector);
+      Configuration liveConfiguration = getConfiguration("server" + node, scaleDown, liveConnector, liveAcceptor, remoteConnector);
       HornetQServer server = new HornetQServerImpl(liveConfiguration);
       server.setIdentity("server" + node);
       return server;
    }
-   private Configuration getConfiguration(String identity, BackupStrategy backupStrategy, TransportConfiguration liveConnector, TransportConfiguration liveAcceptor, TransportConfiguration... otherLiveNodes) throws Exception
+
+   private Configuration getConfiguration(String identity, boolean scaleDown, TransportConfiguration liveConnector, TransportConfiguration liveAcceptor, TransportConfiguration... otherLiveNodes) throws Exception
    {
-      Configuration configuration = createDefaultConfig();
-      configuration.getAcceptorConfigurations().clear();
-      configuration.getAcceptorConfigurations().add(liveAcceptor);
-      configuration.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      configuration.setJournalDirectory(configuration.getJournalDirectory() + identity);
-      configuration.setBindingsDirectory(configuration.getBindingsDirectory() + identity);
-      configuration.setLargeMessagesDirectory(configuration.getLargeMessagesDirectory() + identity);
-      configuration.setPagingDirectory(configuration.getPagingDirectory() + identity);
+      Configuration configuration = createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(liveAcceptor)
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .setJournalDirectory(HornetQDefaultConfiguration.getDefaultJournalDir() + identity)
+         .setBindingsDirectory(HornetQDefaultConfiguration.getDefaultBindingsDirectory() + identity)
+         .setLargeMessagesDirectory(HornetQDefaultConfiguration.getDefaultLargeMessagesDir() + identity)
+         .setPagingDirectory(HornetQDefaultConfiguration.getDefaultPagingDir() + identity)
+         .addQueueConfiguration(new CoreQueueConfiguration()
+                                   .setAddress("jms.queue.testQueue")
+                                   .setName("jms.queue.testQueue"));
+
       List<String> transportConfigurationList = new ArrayList<>();
-      final HAPolicy haPolicy = new HAPolicy();
+
+      final ColocatedPolicyConfiguration haPolicy = new ColocatedPolicyConfiguration();
       for (TransportConfiguration otherLiveNode : otherLiveNodes)
       {
-         configuration.getConnectorConfigurations().put(otherLiveNode.getName(), otherLiveNode);
+         configuration.addConnectorConfiguration(otherLiveNode.getName(), otherLiveNode);
          transportConfigurationList.add(otherLiveNode.getName());
-         haPolicy.getRemoteConnectors().add(otherLiveNode.getName());
+         haPolicy.getExcludedConnectors().add(otherLiveNode.getName());
       }
-      basicClusterConnectionConfig(configuration, liveConnector.getName(), transportConfigurationList);
-      configuration.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-
-      haPolicy.setPolicyType(policyType);
-      haPolicy.setBackupStrategy(backupStrategy);
+      configuration.addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), transportConfigurationList));
       haPolicy.setBackupPortOffset(100);
       haPolicy.setBackupRequestRetries(-1);
       haPolicy.setBackupRequestRetryInterval(500);
       haPolicy.setMaxBackups(1);
       haPolicy.setRequestBackup(true);
-      configuration.setHAPolicy(haPolicy);
+      configuration.setHAPolicyConfiguration(haPolicy);
+      if (!replicated)
+      {
+         SharedStoreMasterPolicyConfiguration ssmc = new SharedStoreMasterPolicyConfiguration();
+         SharedStoreSlavePolicyConfiguration sssc = new SharedStoreSlavePolicyConfiguration();
+         haPolicy.setLiveConfig(ssmc);
+         haPolicy.setBackupConfig(sssc);
+         if (scaleDown)
+         {
+            sssc.setScaleDownConfiguration(new ScaleDownConfiguration());
+         }
+      }
+      else
+      {
+         ReplicatedPolicyConfiguration rpc = new ReplicatedPolicyConfiguration();
+         ReplicaPolicyConfiguration rpc2 = new ReplicaPolicyConfiguration();
+         haPolicy.setLiveConfig(rpc);
+         haPolicy.setBackupConfig(rpc2);
+         if (scaleDown)
+         {
+            rpc2.setScaleDownConfiguration(new ScaleDownConfiguration());
+         }
+      }
 
       return configuration;
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncJournalTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncJournalTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncJournalTest.java
index daeafeb..891be38 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncJournalTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncJournalTest.java
@@ -41,6 +41,7 @@ import org.hornetq.tests.integration.cluster.util.BackupSyncDelay;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
 import org.hornetq.tests.util.TransportConfigurationUtils;
 import org.hornetq.utils.UUID;
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -81,6 +82,27 @@ public class BackupSyncJournalTest extends FailoverTestBase
 
    }
 
+   @Override
+   @After
+   public void tearDown() throws Exception
+   {
+      try
+      {
+         File dir = new File(backupServer.getServer()
+                                .getConfiguration()
+                                .getLargeMessagesDirectory());
+         deleteDirectory(dir);
+         dir = new File(liveServer.getServer()
+                           .getConfiguration()
+                           .getLargeMessagesDirectory());
+         deleteDirectory(dir);
+      }
+      finally
+      {
+         super.tearDown();
+      }
+   }
+
    @Test
    public void testNodeID() throws Exception
    {
@@ -246,8 +268,8 @@ public class BackupSyncJournalTest extends FailoverTestBase
    }
 
    /**
-    * @throws FileNotFoundException
-    * @throws IOException
+    * @throws java.io.FileNotFoundException
+    * @throws java.io.IOException
     * @throws InterruptedException
     */
    private void assertNodeIdWasSaved() throws Exception
@@ -309,14 +331,14 @@ public class BackupSyncJournalTest extends FailoverTestBase
       assertNoMoreMessages();
 
       sendMessages(session, producer, 2 * n_msgs);
-      assertFalse("must NOT be a backup", liveServer.getServer().getConfiguration().getHAPolicy().isBackup());
-      adaptLiveConfigForReplicatedFailBack(liveServer.getServer().getConfiguration());
+      assertFalse("must NOT be a backup", liveServer.getServer().getHAPolicy().isBackup());
+      adaptLiveConfigForReplicatedFailBack(liveServer);
       liveServer.start();
       waitForServer(liveServer.getServer());
-      assertTrue("must have become a backup", liveServer.getServer().getConfiguration().getHAPolicy().isBackup());
+      assertTrue("must have become a backup", liveServer.getServer().getHAPolicy().isBackup());
 
       assertTrue("Fail-back must initialize live!", liveServer.getServer().waitForActivation(15, TimeUnit.SECONDS));
-      assertFalse("must be LIVE!", liveServer.getServer().getConfiguration().getHAPolicy().isBackup());
+      assertFalse("must be LIVE!", liveServer.getServer().getHAPolicy().isBackup());
       int i = 0;
       while (backupServer.isStarted() && i++ < 100)
       {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java
index 64469ac..ecde2ec 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/BackupSyncLargeMessageTest.java
@@ -62,6 +62,8 @@ public class BackupSyncLargeMessageTest extends BackupSyncJournalTest
    @Test
    public void testDeleteLargeMessages() throws Exception
    {
+      // 200 will increase the odds of a failure
+      setNumberOfMessages(200);
       File dir = new File(backupServer.getServer().getConfiguration().getLargeMessagesDirectory());
       assertEquals("Should not have any large messages... previous test failed to clean up?", 0,
                    getAllMessageFileIds(dir).size());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsNettyTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsNettyTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsNettyTest.java
deleted file mode 100644
index 763fa48..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsNettyTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.cluster.failover;
-
-
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.core.client.impl.TopologyMemberImpl;
-import org.hornetq.core.config.Configuration;
-import org.hornetq.core.config.CoreQueueConfiguration;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
-import org.hornetq.core.server.impl.InVMNodeManager;
-
-import java.util.HashMap;
-
-public class ColocatedFailoverCheckPairingsNettyTest extends ColocatedFailoverCheckPairingsTest
-{
-
-   protected void assertPairedCorrectly(TopologyMemberImpl m1, TopologyMemberImpl m2)
-   {
-      String backup1Port = (String) m1.getBackup().getParams().get("port");
-      String backup2Port = (String) m2.getBackup().getParams().get("port");
-      assertEquals(backup1Port, "5449");
-      assertEquals(backup2Port, "5448");
-   }
-   @Override
-   protected void createConfigs() throws Exception
-   {
-
-      TransportConfiguration liveConnector1 = getConnectorTransportConfiguration(1);
-      liveConfiguration1 = super.createDefaultConfig();
-      liveConfiguration1.getAcceptorConfigurations().clear();
-      liveConfiguration1.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(1));
-      liveConfiguration1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-      liveConfiguration1.getHAPolicy().setFailbackDelay(1000);
-      liveConfiguration1.setJournalDirectory(getTestDir() + "/live1/journal");
-      liveConfiguration1.setBindingsDirectory(getTestDir() + "/live1/bindings");
-      liveConfiguration1.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-
-      TransportConfiguration liveConnector2 = getConnectorTransportConfiguration(2);
-      basicClusterConnectionConfig(liveConfiguration1, liveConnector1.getName(), liveConnector2.getName());
-      liveConfiguration1.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfiguration1.getConnectorConfigurations().put(liveConnector2.getName(), liveConnector2);
-
-      Configuration backupConfiguration1 = liveConfiguration1.copy();
-      TransportConfiguration backupConnector1 = getConnectorTransportConfiguration(3);
-      backupConfiguration1.getConnectorConfigurations().put(backupConnector1.getName(), backupConnector1);
-      backupConfiguration1.setJournalDirectory(getTestDir() + "/backup1/journal");
-
-      backupConfiguration1.setBindingsDirectory(getTestDir() + "/backup1/bindings");
-      backupConfiguration1.getAcceptorConfigurations().clear();
-      backupConfiguration1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-      backupConfiguration1.getClusterConfigurations().clear();
-      basicClusterConnectionConfig(backupConfiguration1, backupConnector1.getName(), liveConnector1.getName());
-      liveConfiguration1.getBackupServerConfigurations().add(backupConfiguration1);
-
-
-      liveConfiguration2 = super.createDefaultConfig();
-      liveConfiguration2.getAcceptorConfigurations().clear();
-      liveConfiguration2.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(2));
-      liveConfiguration2.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-      liveConfiguration2.getHAPolicy().setFailbackDelay(1000);
-      liveConfiguration2.setJournalDirectory(getTestDir() + "/live2/journal");
-      liveConfiguration2.setBindingsDirectory(getTestDir() + "/live2/bindings");
-      liveConfiguration2.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-
-      basicClusterConnectionConfig(liveConfiguration2, liveConnector2.getName(), liveConnector1.getName());
-      liveConfiguration2.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfiguration2.getConnectorConfigurations().put(liveConnector2.getName(), liveConnector2);
-
-      Configuration backupConfiguration2 = liveConfiguration2.copy();
-      TransportConfiguration backupConnector2 = getConnectorTransportConfiguration(4);
-      backupConfiguration2.getAcceptorConfigurations().clear();
-      backupConfiguration2.getConnectorConfigurations().put(backupConnector2.getName(), backupConnector2);
-      backupConfiguration2.setJournalDirectory(getTestDir() + "/backup2/journal");
-      backupConfiguration2.setBindingsDirectory(getTestDir() + "/backup2/bindings");
-      backupConfiguration2.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-      backupConfiguration2.getClusterConfigurations().clear();
-      basicClusterConnectionConfig(backupConfiguration2, backupConnector2.getName(), liveConnector2.getName());
-      liveConfiguration2.getBackupServerConfigurations().add(backupConfiguration2);
-
-      nodeManagerLive1 = new InVMNodeManager(true, backupConfiguration2.getJournalDirectory());
-      nodeManagerLive2 = new InVMNodeManager(true, backupConfiguration1.getJournalDirectory());
-
-      liveServer1 = createTestableServer(liveConfiguration1, nodeManagerLive1, nodeManagerLive2, 1);
-      liveServer2 = createTestableServer(liveConfiguration2, nodeManagerLive2, nodeManagerLive1, 2);
-   }
-
-   @Override
-   protected TransportConfiguration getAcceptorTransportConfiguration(int node)
-   {
-      HashMap<String, Object> params = new HashMap<>();
-      params.put("port", "" + (5445 + node));
-      return new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params);
-   }
-
-   @Override
-   protected TransportConfiguration getConnectorTransportConfiguration(int node)
-   {
-      HashMap<String, Object> params = new HashMap<>();
-      params.put("port", "" + (5445 + node));
-      return new TransportConfiguration(NETTY_CONNECTOR_FACTORY, params);
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsTest.java
deleted file mode 100644
index 976dbfb..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverCheckPairingsTest.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.cluster.failover;
-
-
-import java.util.HashMap;
-
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.ClientSessionFactory;
-import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.api.core.client.ServerLocator;
-import org.hornetq.core.client.impl.Topology;
-import org.hornetq.core.client.impl.TopologyMemberImpl;
-import org.hornetq.core.config.Configuration;
-import org.hornetq.core.config.CoreQueueConfiguration;
-import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
-import org.hornetq.core.server.impl.InVMNodeManager;
-import org.hornetq.tests.integration.cluster.util.SameProcessHornetQServer;
-import org.hornetq.tests.integration.cluster.util.TestableServer;
-import org.hornetq.tests.util.ServiceTestBase;
-import org.junit.After;
-import org.junit.Test;
-
-public class ColocatedFailoverCheckPairingsTest extends ServiceTestBase
-{
-   TestableServer liveServer1;
-
-   protected TestableServer liveServer2;
-
-   protected Configuration liveConfiguration1;
-
-   protected Configuration liveConfiguration2;
-
-   protected NodeManager nodeManagerLive1;
-
-   protected NodeManager nodeManagerLive2;
-
-   @Override
-   public void setUp() throws Exception
-   {
-      super.setUp();
-   }
-
-   @Test
-   public void testPairings() throws Exception
-   {
-      createConfigs();
-
-      liveServer1.start();
-      liveServer2.start();
-      waitForServer(liveServer1.getServer());
-      waitForServer(liveServer2.getServer());
-
-      ServerLocator locator = HornetQClient.createServerLocator(true, getConnectorTransportConfiguration(1));
-
-      waitForTopology(liveServer1.getServer(), 2, 2);
-      waitForTopology(liveServer2.getServer(), 2, 2);
-
-      ClientSessionFactory sessionFactory = locator.createSessionFactory();
-
-      Topology topology = sessionFactory.getServerLocator().getTopology();
-      System.out.println(topology.describe());
-      TopologyMemberImpl m1 = topology.getMember(liveServer1.getServer().getNodeID().toString());
-      TopologyMemberImpl m2 = topology.getMember(liveServer2.getServer().getNodeID().toString());
-
-      assertPairedCorrectly(m1, m2);
-   }
-
-   protected void assertPairedCorrectly(TopologyMemberImpl m1, TopologyMemberImpl m2)
-   {
-      assertEquals(m1.getLive(), m2.getBackup());
-      assertEquals(m2.getLive(), m1.getBackup());
-   }
-
-   @Override
-   @After
-   public void tearDown() throws Exception
-   {
-      liveServer1.stop();
-      liveServer2.stop();
-      super.tearDown();
-   }
-
-   protected void createConfigs() throws Exception
-   {
-      nodeManagerLive1 = new InVMNodeManager(false);
-      nodeManagerLive2 = new InVMNodeManager(false);
-
-      TransportConfiguration liveConnector1 = getConnectorTransportConfiguration(1);
-      liveConfiguration1 = super.createDefaultConfig();
-      liveConfiguration1.getAcceptorConfigurations().clear();
-      liveConfiguration1.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(1));
-      liveConfiguration1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfiguration1.getHAPolicy().setFailbackDelay(1000);
-      liveConfiguration1.setJournalDirectory(getTestDir() + "/live1");
-      liveConfiguration1.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-
-      TransportConfiguration liveConnector2 = getConnectorTransportConfiguration(2);
-      basicClusterConnectionConfig(liveConfiguration1, liveConnector1.getName(), liveConnector2.getName());
-      liveConfiguration1.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfiguration1.getConnectorConfigurations().put(liveConnector2.getName(), liveConnector2);
-
-      Configuration backupConfiguration1 = liveConfiguration1.copy();
-      backupConfiguration1.setJournalDirectory(getTestDir() + "/live2");
-      backupConfiguration1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      liveConfiguration1.getBackupServerConfigurations().add(backupConfiguration1);
-
-      liveServer1 = createTestableServer(liveConfiguration1, nodeManagerLive1, nodeManagerLive2, 1);
-
-      liveConfiguration2 = super.createDefaultConfig();
-      liveConfiguration2.getAcceptorConfigurations().clear();
-      liveConfiguration2.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(2));
-      liveConfiguration2.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfiguration2.getHAPolicy().setFailbackDelay(1000);
-      liveConfiguration2.setJournalDirectory(getTestDir() + "/live2");
-      liveConfiguration2.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-
-      basicClusterConnectionConfig(liveConfiguration2, liveConnector2.getName(), liveConnector1.getName());
-      liveConfiguration2.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfiguration2.getConnectorConfigurations().put(liveConnector2.getName(), liveConnector2);
-
-      Configuration backupConfiguration2 = liveConfiguration2.copy();
-      backupConfiguration2.setJournalDirectory(getTestDir() + "/live1");
-      backupConfiguration2.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      liveConfiguration2.getBackupServerConfigurations().add(backupConfiguration2);
-
-      liveServer2 = createTestableServer(liveConfiguration2, nodeManagerLive2, nodeManagerLive1, 2);
-   }
-
-   protected TransportConfiguration getAcceptorTransportConfiguration(int node)
-   {
-      HashMap<String, Object> params = new HashMap<>();
-      params.put("server-id", "" + node);
-      return new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params);
-   }
-
-   protected TransportConfiguration getConnectorTransportConfiguration(int node)
-   {
-      HashMap<String, Object> params = new HashMap<>();
-      params.put("server-id", "" + node);
-      return new TransportConfiguration(INVM_CONNECTOR_FACTORY, params);
-   }
-
-   protected TestableServer createTestableServer(Configuration config, NodeManager liveNodeManager, NodeManager backupNodeManager, int id)
-   {
-      return new SameProcessHornetQServer(
-         createColocatedInVMFailoverServer(true, config, liveNodeManager, backupNodeManager, id));
-   }
-}


[19/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/HornetQServerImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/HornetQServerImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/HornetQServerImpl.java
index baca41d..ad2538e 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/HornetQServerImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/HornetQServerImpl.java
@@ -13,13 +13,12 @@
 package org.hornetq.core.server.impl;
 
 import javax.management.MBeanServer;
+
 import java.io.File;
 import java.io.FilenameFilter;
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.lang.management.ManagementFactory;
-import java.lang.reflect.Array;
-import java.nio.channels.ClosedChannelException;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
@@ -31,8 +30,6 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -41,24 +38,11 @@ import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
 
 import org.hornetq.api.config.HornetQDefaultConfiguration;
-import org.hornetq.api.core.DiscoveryGroupConfiguration;
-import org.hornetq.api.core.HornetQAlreadyReplicatingException;
-import org.hornetq.api.core.HornetQException;
-import org.hornetq.api.core.HornetQIllegalStateException;
-import org.hornetq.api.core.HornetQInternalErrorException;
 import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.ClusterTopologyListener;
-import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.api.core.client.TopologyMember;
 import org.hornetq.core.asyncio.impl.AsynchronousFileImpl;
 import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
-import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
-import org.hornetq.core.client.impl.ServerLocatorInternal;
-import org.hornetq.core.config.BackupStrategy;
 import org.hornetq.core.config.BridgeConfiguration;
-import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.ConfigurationUtils;
 import org.hornetq.core.config.CoreQueueConfiguration;
@@ -94,29 +78,19 @@ import org.hornetq.core.persistence.impl.journal.JournalStorageManager;
 import org.hornetq.core.persistence.impl.journal.OperationContextImpl;
 import org.hornetq.core.persistence.impl.nullpm.NullStorageManager;
 import org.hornetq.core.postoffice.Binding;
-import org.hornetq.core.postoffice.DuplicateIDCache;
 import org.hornetq.core.postoffice.PostOffice;
 import org.hornetq.core.postoffice.QueueBinding;
 import org.hornetq.core.postoffice.impl.DivertBinding;
 import org.hornetq.core.postoffice.impl.LocalQueueBinding;
 import org.hornetq.core.postoffice.impl.PostOfficeImpl;
-import org.hornetq.core.protocol.ServerPacketDecoder;
-import org.hornetq.core.protocol.core.Channel;
-import org.hornetq.core.protocol.core.CoreRemotingConnection;
-import org.hornetq.core.protocol.core.impl.wireformat.ReplicationLiveIsStoppingMessage;
-import org.hornetq.core.protocol.core.impl.wireformat.ReplicationLiveIsStoppingMessage.LiveStopping;
-import org.hornetq.core.remoting.CloseListener;
-import org.hornetq.core.remoting.FailureListener;
 import org.hornetq.core.remoting.server.RemotingService;
 import org.hornetq.core.remoting.server.impl.RemotingServiceImpl;
-import org.hornetq.core.replication.ReplicationEndpoint;
 import org.hornetq.core.replication.ReplicationManager;
 import org.hornetq.core.security.CheckType;
 import org.hornetq.core.security.Role;
 import org.hornetq.core.security.SecurityStore;
 import org.hornetq.core.security.impl.SecurityStoreImpl;
 import org.hornetq.core.server.ActivateCallback;
-import org.hornetq.core.server.ActivationParams;
 import org.hornetq.core.server.Bindable;
 import org.hornetq.core.server.Divert;
 import org.hornetq.core.server.HornetQComponent;
@@ -125,25 +99,20 @@ import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.JournalType;
 import org.hornetq.core.server.LargeServerMessage;
-import org.hornetq.core.server.LiveNodeLocator;
 import org.hornetq.core.server.MemoryManager;
 import org.hornetq.core.server.NodeManager;
 import org.hornetq.core.server.Queue;
 import org.hornetq.core.server.QueueFactory;
 import org.hornetq.core.server.ServerSession;
+import org.hornetq.core.server.ServerSessionFactory;
 import org.hornetq.core.server.cluster.BackupManager;
-import org.hornetq.core.server.cluster.ClusterConnection;
-import org.hornetq.core.server.cluster.ClusterControl;
-import org.hornetq.core.server.cluster.ClusterController;
 import org.hornetq.core.server.cluster.ClusterManager;
 import org.hornetq.core.server.cluster.Transformer;
 import org.hornetq.core.server.cluster.ha.HAPolicy;
-import org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum;
 import org.hornetq.core.server.group.GroupingHandler;
 import org.hornetq.core.server.group.impl.GroupingHandlerConfiguration;
 import org.hornetq.core.server.group.impl.LocalGroupingHandler;
 import org.hornetq.core.server.group.impl.RemoteGroupingHandler;
-import org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION;
 import org.hornetq.core.server.management.ManagementService;
 import org.hornetq.core.server.management.impl.ManagementServiceImpl;
 import org.hornetq.core.settings.HierarchicalRepository;
@@ -165,15 +134,12 @@ import org.hornetq.utils.ReusableLatch;
 import org.hornetq.utils.SecurityFormatter;
 import org.hornetq.utils.VersionLoader;
 
-import static org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_REPLICATING;
-import static org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAIL_OVER;
-import static org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.STOP;
-
 /**
  * The HornetQ server implementation
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  * @author <a href="mailto:ataylor@redhat.com>Andy Taylor</a>
+ * @author <a href="mailto:mtaylor@redhat.com>Martyn Taylor</a>
  */
 public class HornetQServerImpl implements HornetQServer
 {
@@ -187,6 +153,8 @@ public class HornetQServerImpl implements HornetQServer
     */
    public static final String GENERIC_IGNORED_FILTER = "__HQX=-1";
 
+   private HAPolicy haPolicy;
+
    enum SERVER_STATE
    {
       /**
@@ -276,20 +244,6 @@ public class HornetQServerImpl implements HornetQServer
     */
    private final ReusableLatch activationLatch = new ReusableLatch(0);
 
-   private final ReusableLatch backupSyncLatch = new ReusableLatch(0);
-
-   private final Object replicationLock = new Object();
-
-   /**
-    * Only applicable to 'remote backup servers'. If this flag is false the backup may not become
-    * 'live'.
-    */
-   private volatile boolean backupUpToDate = true;
-
-   private ReplicationManager replicationManager;
-
-   private ReplicationEndpoint replicationEndpoint;
-
    private final Set<ActivateCallback> activateCallbacks = new ConcurrentHashSet<ActivateCallback>();
 
    private volatile GroupingHandler groupingHandler;
@@ -307,16 +261,16 @@ public class HornetQServerImpl implements HornetQServer
 
    private final ShutdownOnCriticalErrorListener shutdownOnCriticalIO = new ShutdownOnCriticalErrorListener();
 
-   private final Object failbackCheckerGuard = new Object();
-   private boolean cancelFailBackChecker;
-
    private final HornetQServer parentServer;
 
-   private ClientSessionFactoryInternal scaleDownClientSessionFactory = null;
+   //todo think about moving this to the activation
+   private final List<SimpleString> scaledDownNodeIDs = new ArrayList<>();
+
+   private boolean threadPoolSupplied = false;
 
-   private ServerLocatorInternal scaleDownServerLocator = null;
+   private boolean scheduledPoolSupplied = false;
 
-   private final List<SimpleString> scaledDownNodeIDs = new ArrayList<>();
+   private ServiceRegistry serviceRegistry;
 
    // Constructors
    // ---------------------------------------------------------------------------------
@@ -358,11 +312,19 @@ public class HornetQServerImpl implements HornetQServer
                             final HornetQSecurityManager securityManager,
                             final HornetQServer parentServer)
    {
+      this(configuration, mbeanServer, securityManager, parentServer, null);
+   }
+
+   public HornetQServerImpl(Configuration configuration,
+                            MBeanServer mbeanServer,
+                            final HornetQSecurityManager securityManager,
+                            final HornetQServer parentServer,
+                            final ServiceRegistry serviceRegistry)
+   {
       if (configuration == null)
       {
          configuration = new ConfigurationImpl();
       }
-
       if (mbeanServer == null)
       {
          // Just use JVM mbean server
@@ -389,6 +351,7 @@ public class HornetQServerImpl implements HornetQServer
 
       this.parentServer = parentServer;
 
+      this.serviceRegistry = serviceRegistry == null ?  new ServiceRegistry() : serviceRegistry;
    }
 
    // life-cycle methods
@@ -397,7 +360,7 @@ public class HornetQServerImpl implements HornetQServer
    /*
     * Can be overridden for tests
     */
-   protected NodeManager createNodeManager(final String directory, String nodeGroupName, boolean replicatingBackup)
+   protected NodeManager createNodeManager(final String directory, boolean replicatingBackup)
    {
       NodeManager manager;
       if (!configuration.isPersistenceEnabled())
@@ -412,7 +375,6 @@ public class HornetQServerImpl implements HornetQServer
       {
          manager = new FileLockNodeManager(directory, replicatingBackup, configuration.getJournalLockAcquisitionTimeout());
       }
-      manager.setNodeGroupName(nodeGroupName);
       return manager;
    }
 
@@ -423,11 +385,13 @@ public class HornetQServerImpl implements HornetQServer
          HornetQServerLogger.LOGGER.debug("Server already started!");
          return;
       }
-      synchronized (failbackCheckerGuard)
+
+      state = SERVER_STATE.STARTING;
+
+      if (haPolicy == null)
       {
-         cancelFailBackChecker = false;
+         haPolicy = ConfigurationUtils.getHAPolicy(configuration.getHAPolicyConfiguration());
       }
-      state = SERVER_STATE.STARTING;
 
       activationLatch.setCount(1);
 
@@ -439,12 +403,11 @@ public class HornetQServerImpl implements HornetQServer
       {
          checkJournalDirectory();
 
-         nodeManager =
-            createNodeManager(configuration.getJournalDirectory(), configuration.getHAPolicy().getBackupGroupName(), false);
+         nodeManager = createNodeManager(configuration.getJournalDirectory(), false);
 
          nodeManager.start();
 
-         HornetQServerLogger.LOGGER.serverStarting((configuration.getHAPolicy().isBackup() ? "backup" : "live"), configuration);
+         HornetQServerLogger.LOGGER.serverStarting((haPolicy.isBackup() ? "backup" : "live"), configuration);
 
          if (configuration.isRunSyncSpeedTest())
          {
@@ -453,38 +416,24 @@ public class HornetQServerImpl implements HornetQServer
             test.run();
          }
 
-         final boolean wasLive = !configuration.getHAPolicy().isBackup();
-         if (!configuration.getHAPolicy().isBackup())
+         final boolean wasLive = !haPolicy.isBackup();
+         if (!haPolicy.isBackup())
          {
-            if (configuration.getHAPolicy().isSharedStore() && configuration.isPersistenceEnabled())
-            {
-               activation = new SharedStoreLiveActivation();
-            }
-            else
-            {
-               activation = new SharedNothingLiveActivation();
-            }
+            activation = haPolicy.createActivation(this, false, activationParams, shutdownOnCriticalIO);
 
             activation.run();
          }
          // The activation on fail-back may change the value of isBackup, for that reason we are
          // checking again here
-         if (configuration.getHAPolicy().isBackup())
+         if (haPolicy.isBackup())
          {
-            if (configuration.getHAPolicy().isSharedStore())
+            if (haPolicy.isSharedStore())
             {
-               activation = new SharedStoreBackupActivation();
+               activation = haPolicy.createActivation(this, false, activationParams, shutdownOnCriticalIO);
             }
             else
             {
-               assert replicationEndpoint == null;
-               nodeManager.stop();
-               nodeManager =
-                  createNodeManager(configuration.getJournalDirectory(), configuration.getHAPolicy().getBackupGroupName(), true);
-               backupUpToDate = false;
-               backupSyncLatch.setCount(1);
-               replicationEndpoint = new ReplicationEndpoint(this, shutdownOnCriticalIO, wasLive);
-               activation = new SharedNothingBackupActivation(wasLive);
+               activation = haPolicy.createActivation(this, wasLive, activationParams, shutdownOnCriticalIO);
             }
 
             backupActivationThread = new Thread(activation, HornetQMessageBundle.BUNDLE.activationForServer(this));
@@ -497,7 +446,7 @@ public class HornetQServerImpl implements HornetQServer
                                                      identity != null ? identity : "");
          }
          // start connector service
-         connectorsService = new ConnectorsService(configuration, storageManager, scheduledPool, postOffice);
+         connectorsService = new ConnectorsService(configuration, storageManager, scheduledPool, postOffice, serviceRegistry);
          connectorsService.start();
       }
       finally
@@ -520,6 +469,74 @@ public class HornetQServerImpl implements HornetQServer
       super.finalize();
    }
 
+   public void setState(SERVER_STATE state)
+   {
+      this.state = state;
+   }
+
+   public SERVER_STATE getState()
+   {
+      return state;
+   }
+
+   public void interrupBackupThread(NodeManager nodeManagerInUse) throws InterruptedException
+   {
+      long timeout = 30000;
+
+      long start = System.currentTimeMillis();
+
+      while (backupActivationThread.isAlive() && System.currentTimeMillis() - start < timeout)
+      {
+         if (nodeManagerInUse != null)
+         {
+            nodeManagerInUse.interrupt();
+         }
+
+         backupActivationThread.interrupt();
+
+         backupActivationThread.join(1000);
+
+      }
+
+      if (System.currentTimeMillis() - start >= timeout)
+      {
+         threadDump("Timed out waiting for backup activation to exit");
+      }
+   }
+
+   public void resetNodeManager() throws Exception
+   {
+      nodeManager.stop();
+      nodeManager =
+            createNodeManager(configuration.getJournalDirectory(), true);
+   }
+
+   public Activation getActivation()
+   {
+      return activation;
+   }
+
+   @Override
+   public HAPolicy getHAPolicy()
+   {
+      return haPolicy;
+   }
+
+   @Override
+   public void setHAPolicy(HAPolicy haPolicy)
+   {
+      this.haPolicy = haPolicy;
+   }
+
+   public ExecutorService getThreadPool()
+   {
+      return threadPool;
+   }
+
+   public void setActivation(SharedNothingLiveActivation activation)
+   {
+      this.activation = activation;
+   }
    /**
     * Stops the server in a different thread.
     */
@@ -533,7 +550,7 @@ public class HornetQServerImpl implements HornetQServer
          {
             try
             {
-               stop(configuration.getHAPolicy().isFailoverOnServerShutdown(), criticalIOError, false);
+               stop(false, criticalIOError, false);
             }
             catch (Exception e)
             {
@@ -545,7 +562,7 @@ public class HornetQServerImpl implements HornetQServer
 
    public final void stop() throws Exception
    {
-      stop(configuration.getHAPolicy().isFailoverOnServerShutdown());
+      stop(false);
    }
 
    public void addActivationParam(String key, Object val)
@@ -593,22 +610,10 @@ public class HornetQServerImpl implements HornetQServer
 
    /**
     * Stops the server
-    *
-    * @param failoverOnServerShutdown whether we will allow a backup server to become live when the
-    *                                 server is stopped normally
     * @param criticalIOError          whether we have encountered an IO error with the journal etc
-    * @param failingBack              if true don't set the flag to stop the failback checker
     */
-   private void stop(boolean failoverOnServerShutdown, final boolean criticalIOError, boolean failingBack) throws Exception
+   void stop(boolean failoverOnServerShutdown, final boolean criticalIOError, boolean restarting) throws Exception
    {
-      if (!failingBack)
-      {
-         synchronized (failbackCheckerGuard)
-         {
-            cancelFailBackChecker = true;
-         }
-      }
-
       synchronized (this)
       {
          if (state == SERVER_STATE.STOPPED || state == SERVER_STATE.STOPPING)
@@ -617,22 +622,8 @@ public class HornetQServerImpl implements HornetQServer
          }
          state = SERVER_STATE.STOPPING;
 
-         final ReplicationManager localReplicationManager = getReplicationManager();
+         activation.sendLiveIsStopping();
 
-         if (localReplicationManager != null)
-         {
-            replicationManager.sendLiveIsStopping(LiveStopping.STOP_CALLED);
-            // Schedule for 10 seconds
-            // this pool gets a 'hard' shutdown, no need to manage the Future of this Runnable.
-            scheduledPool.schedule(new Runnable()
-            {
-               @Override
-               public void run()
-               {
-                  localReplicationManager.clearReplicationTokens();
-               }
-            }, 30, TimeUnit.SECONDS);
-         }
          stopComponent(connectorsService);
 
          // we stop the groupingHandler before we stop the cluster manager so binding mappings
@@ -644,27 +635,10 @@ public class HornetQServerImpl implements HornetQServer
          }
          stopComponent(clusterManager);
 
-         // connect to the scale-down target first so that when we freeze/disconnect the clients we can tell them where
-         // we're sending the messages
-         if (configuration.getHAPolicy().isScaleDown())
-         {
-            connectToScaleDownTarget();
-         }
          freezeConnections();
       }
 
-      if (configuration.getHAPolicy().isScaleDown() && scaleDownClientSessionFactory != null)
-      {
-         try
-         {
-            scaleDown();
-         }
-         finally
-         {
-            scaleDownClientSessionFactory.close();
-            scaleDownServerLocator.close();
-         }
-      }
+      activation.postConnectionFreeze();
 
       closeAllServerSessions(criticalIOError);
 
@@ -693,12 +667,8 @@ public class HornetQServerImpl implements HornetQServer
          stopComponent(deploymentManager);
       }
 
-      if (managementService != null)
-         managementService.unregisterServer();
-
       stopComponent(backupManager);
-      stopComponent(managementService);
-      stopComponent(replicationEndpoint); // applies to a "backup" server
+      activation.preStorageClose();
       stopComponent(pagingManager);
 
       if (storageManager != null)
@@ -709,12 +679,17 @@ public class HornetQServerImpl implements HornetQServer
       if (remotingService != null)
          remotingService.stop(criticalIOError);
 
+      // Stop the management service after the remoting service to ensure all acceptors are deregistered with JMX
+      if (managementService != null)
+         managementService.unregisterServer();
+      stopComponent(managementService);
+
       stopComponent(securityManager);
       stopComponent(resourceManager);
 
       stopComponent(postOffice);
 
-      if (scheduledPool != null)
+      if (scheduledPool != null && !scheduledPoolSupplied)
       {
          // we just interrupt all running tasks, these are supposed to be pings and the like.
          scheduledPool.shutdownNow();
@@ -722,7 +697,7 @@ public class HornetQServerImpl implements HornetQServer
 
       stopComponent(memoryManager);
 
-      if (threadPool != null)
+      if (threadPool != null && !threadPoolSupplied)
       {
          threadPool.shutdown();
          try
@@ -742,26 +717,21 @@ public class HornetQServerImpl implements HornetQServer
          }
       }
 
-      scheduledPool = null;
-      threadPool = null;
+      if (!threadPoolSupplied) threadPool = null;
+      if (!scheduledPoolSupplied) scheduledPool = null;
 
       if (securityStore != null)
          securityStore.stop();
 
-      threadPool = null;
-
-      scheduledPool = null;
-
       pagingManager = null;
       securityStore = null;
       resourceManager = null;
-      replicationManager = null;
-      replicationEndpoint = null;
       postOffice = null;
       queueFactory = null;
       resourceManager = null;
       messagingServerControl = null;
       memoryManager = null;
+      backupManager = null;
 
       sessions.clear();
 
@@ -773,7 +743,7 @@ public class HornetQServerImpl implements HornetQServer
       SimpleString tempNodeID = getNodeID();
       if (activation != null)
       {
-         activation.close(failoverOnServerShutdown);
+         activation.close(failoverOnServerShutdown, restarting);
       }
       if (backupActivationThread != null)
       {
@@ -807,72 +777,7 @@ public class HornetQServerImpl implements HornetQServer
       }
    }
 
-   public long scaleDown() throws Exception
-   {
-      ScaleDownHandler scaleDownHandler = new ScaleDownHandler(pagingManager, postOffice, nodeManager, clusterManager.getClusterController());
-      ConcurrentMap<SimpleString, DuplicateIDCache> duplicateIDCaches = ((PostOfficeImpl) postOffice).getDuplicateIDCaches();
-      Map<SimpleString, List<Pair<byte[], Long>>> duplicateIDMap = new HashMap<>();
-      for (SimpleString address : duplicateIDCaches.keySet())
-      {
-         DuplicateIDCache duplicateIDCache = postOffice.getDuplicateIDCache(address);
-         duplicateIDMap.put(address, duplicateIDCache.getMap());
-      }
-      return scaleDownHandler.scaleDown(scaleDownClientSessionFactory, resourceManager, duplicateIDMap, configuration.getManagementAddress(), null);
-   }
 
-   public void connectToScaleDownTarget()
-   {
-      try
-      {
-         scaleDownServerLocator = clusterManager.getHAManager().getScaleDownConnector();
-         //use a Node Locator to connect to the cluster
-         scaleDownServerLocator.setPacketDecoder(ServerPacketDecoder.INSTANCE);
-         LiveNodeLocator nodeLocator = clusterManager.getHAManager().getHAPolicy().getScaleDownGroupName() == null ?
-            new AnyLiveNodeLocatorForScaleDown(HornetQServerImpl.this) :
-            new NamedLiveNodeLocatorForScaleDown(clusterManager.getHAManager().getHAPolicy().getScaleDownGroupName(), HornetQServerImpl.this);
-         scaleDownServerLocator.addClusterTopologyListener(nodeLocator);
-
-         nodeLocator.connectToCluster(scaleDownServerLocator);
-         // a timeout is necessary here in case we use a NamedLiveNodeLocatorForScaleDown and there's no matching node in the cluster
-         // should the timeout be configurable?
-         nodeLocator.locateNode(HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT);
-         ClientSessionFactoryInternal clientSessionFactory = null;
-         while (clientSessionFactory == null)
-         {
-            Pair<TransportConfiguration, TransportConfiguration> possibleLive = null;
-            try
-            {
-               possibleLive = nodeLocator.getLiveConfiguration();
-               if (possibleLive == null)  // we've tried every connector
-                  break;
-               clientSessionFactory = (ClientSessionFactoryInternal) scaleDownServerLocator.createSessionFactory(possibleLive.getA(), 0, false);
-            }
-            catch (Exception e)
-            {
-               HornetQServerLogger.LOGGER.trace("Failed to connect to " + possibleLive.getA());
-               nodeLocator.notifyRegistrationFailed(false);
-               if (clientSessionFactory != null)
-               {
-                  clientSessionFactory.close();
-               }
-               clientSessionFactory = null;
-               // should I try the backup (i.e. getB()) from possibleLive?
-            }
-         }
-         if (clientSessionFactory != null)
-         {
-            scaleDownClientSessionFactory = clientSessionFactory;
-         }
-         else
-         {
-            throw new HornetQException("Unable to connect to server for scale-down");
-         }
-      }
-      catch (Exception e)
-      {
-         HornetQServerLogger.LOGGER.failedToScaleDown(e);
-      }
-   }
 
    public boolean checkLiveIsNotColocated(String nodeId)
    {
@@ -894,17 +799,7 @@ public class HornetQServerImpl implements HornetQServer
     */
    private void freezeConnections()
    {
-      ReplicationManager localReplicationManager = getReplicationManager();
-      TransportConfiguration tc = scaleDownClientSessionFactory == null ? null : scaleDownClientSessionFactory.getConnectorConfiguration();
-      String nodeID = tc == null ? null : scaleDownClientSessionFactory.getServerLocator().getTopology().getMember(tc).getNodeId();
-      if (remotingService != null && localReplicationManager != null)
-      {
-         remotingService.freeze(nodeID, localReplicationManager.getBackupTransportConnection());
-      }
-      else if (remotingService != null)
-      {
-         remotingService.freeze(nodeID, null);
-      }
+      activation.freezeConnections(remotingService);
 
       // after disconnecting all the clients close all the server sessions so any messages in delivery will be cancelled back to the queue
       for (ServerSession serverSession : sessions.values())
@@ -962,7 +857,7 @@ public class HornetQServerImpl implements HornetQServer
 
    }
 
-   private static void stopComponent(HornetQComponent component) throws Exception
+   static void stopComponent(HornetQComponent component) throws Exception
    {
       if (component != null)
          component.stop();
@@ -1134,7 +1029,8 @@ public class HornetQServerImpl implements HornetQServer
                                       final boolean preAcknowledge,
                                       final boolean xa,
                                       final String defaultAddress,
-                                      final SessionCallback callback) throws Exception
+                                      final SessionCallback callback,
+                                      final ServerSessionFactory sessionFactory) throws Exception
    {
 
       if (securityStore != null)
@@ -1142,16 +1038,42 @@ public class HornetQServerImpl implements HornetQServer
          securityStore.authenticate(username, password);
       }
       final OperationContext context = storageManager.newContext(getExecutorFactory().getExecutor());
-      final ServerSessionImpl session = internalCreateSession(name, username, password, minLargeMessageSize, connection, autoCommitSends, autoCommitAcks, preAcknowledge, xa, defaultAddress, callback, context);
+      final ServerSessionImpl session = internalCreateSession(name, username, password, minLargeMessageSize, connection, autoCommitSends, autoCommitAcks, preAcknowledge, xa, defaultAddress, callback, context, sessionFactory);
 
       sessions.put(name, session);
 
       return session;
    }
 
-   protected ServerSessionImpl internalCreateSession(String name, String username, String password, int minLargeMessageSize, RemotingConnection connection, boolean autoCommitSends, boolean autoCommitAcks, boolean preAcknowledge, boolean xa, String defaultAddress, SessionCallback callback, OperationContext context) throws Exception
+   protected ServerSessionImpl internalCreateSession(String name, String username, String password, int minLargeMessageSize, RemotingConnection connection, boolean autoCommitSends, boolean autoCommitAcks, boolean preAcknowledge, boolean xa, String defaultAddress, SessionCallback callback, OperationContext context, ServerSessionFactory sessionFactory) throws Exception
    {
-      return new ServerSessionImpl(name,
+      if (sessionFactory == null)
+      {
+         return new ServerSessionImpl(name,
+                                   username,
+                                   password,
+                                   minLargeMessageSize,
+                                   autoCommitSends,
+                                   autoCommitAcks,
+                                   preAcknowledge,
+                                   configuration.isPersistDeliveryCountBeforeDelivery(),
+                                   xa,
+                                   connection,
+                                   storageManager,
+                                   postOffice,
+                                   resourceManager,
+                                   securityStore,
+                                   managementService,
+                                   this,
+                                   configuration.getManagementAddress(),
+                                   defaultAddress == null ? null
+                                      : new SimpleString(defaultAddress),
+                                   callback,
+                                   context);
+      }
+      else
+      {
+         return sessionFactory.createCoreSession(name,
                                    username,
                                    password,
                                    minLargeMessageSize,
@@ -1172,9 +1094,11 @@ public class HornetQServerImpl implements HornetQServer
                                       : new SimpleString(defaultAddress),
                                    callback,
                                    context);
+      }
    }
 
-   protected SecurityStore getSecurityStore()
+   @Override
+   public SecurityStore getSecurityStore()
    {
       return securityStore;
    }
@@ -1233,18 +1157,6 @@ public class HornetQServerImpl implements HornetQServer
       return activationLatch.await(timeout, unit);
    }
 
-   @Override
-   public boolean waitForBackupSync(long timeout, TimeUnit unit) throws InterruptedException
-   {
-      if (configuration.getHAPolicy().getPolicyType() == HAPolicy.POLICY_TYPE.BACKUP_REPLICATED)
-      {
-         return backupSyncLatch.await(timeout, unit);
-      }
-      else
-      {
-         return true;
-      }
-   }
 
    public HornetQServerControlImpl getHornetQServerControl()
    {
@@ -1440,17 +1352,9 @@ public class HornetQServerImpl implements HornetQServer
       return groupingHandler;
    }
 
-   public ReplicationEndpoint getReplicationEndpoint()
-   {
-      return replicationEndpoint;
-   }
-
    public ReplicationManager getReplicationManager()
    {
-      synchronized (replicationLock)
-      {
-         return replicationManager;
-      }
+      return activation.getReplicationManager();
    }
 
    public ConnectorsService getConnectorsService()
@@ -1505,7 +1409,7 @@ public class HornetQServerImpl implements HornetQServer
                                      postOffice,
                                      storageManager);
 
-      Binding binding = new DivertBinding(storageManager.generateUniqueID(), sAddress, divert);
+      Binding binding = new DivertBinding(storageManager.generateID(), sAddress, divert);
 
       postOffice.addBinding(binding);
 
@@ -1575,7 +1479,7 @@ public class HornetQServerImpl implements HornetQServer
    {
 
       return new PagingManagerImpl(new PagingStoreFactoryNIO(storageManager, configuration.getPagingDirectory(),
-                                                             configuration.getJournalBufferSize_NIO(),
+                                                             configuration.getJournalBufferTimeout_NIO(),
                                                              scheduledPool,
                                                              executorFactory,
                                                              configuration.isJournalSyncNonTransactional(),
@@ -1628,6 +1532,60 @@ public class HornetQServerImpl implements HornetQServer
       }
    }
 
+   private void callActivationCompleteCallbacks()
+   {
+      for (ActivateCallback callback : activateCallbacks)
+      {
+         callback.activationComplete();
+      }
+   }
+
+   /**
+    * Sets up HornetQ Executor Services.
+    */
+   private void initializeExecutorServices()
+   {
+      /* We check to see if a Thread Pool is supplied in the InjectedObjectRegistry.  If so we created a new Ordered
+       * Executor based on the provided Thread pool.  Otherwise we create a new ThreadPool.
+       */
+      if (serviceRegistry.getExecutorService() == null)
+      {
+         ThreadFactory tFactory = new HornetQThreadFactory("HornetQ-server-" + this.toString(), false, getThisClassLoader());
+         if (configuration.getThreadPoolMaxSize() == -1)
+         {
+            threadPool = Executors.newCachedThreadPool(tFactory);
+         }
+         else
+         {
+            threadPool = Executors.newFixedThreadPool(configuration.getThreadPoolMaxSize(), tFactory);
+         }
+      }
+      else
+      {
+         threadPool = serviceRegistry.getExecutorService();
+         this.threadPoolSupplied = true;
+      }
+      this.executorFactory = new OrderedExecutorFactory(threadPool);
+
+       /* We check to see if a Scheduled Executor Service is provided in the InjectedObjectRegistry.  If so we use this
+       * Scheduled ExecutorService otherwise we create a new one.
+       */
+      if (serviceRegistry.getScheduledExecutorService() == null)
+      {
+         ThreadFactory tFactory = new HornetQThreadFactory("HornetQ-scheduled-threads", false, getThisClassLoader());
+         scheduledPool = new ScheduledThreadPoolExecutor(configuration.getScheduledThreadPoolMaxSize(), tFactory);
+      }
+      else
+      {
+         this.scheduledPoolSupplied = true;
+         this.scheduledPool = serviceRegistry.getScheduledExecutorService();
+      }
+   }
+
+   public ServiceRegistry getServiceRegistry()
+   {
+      return serviceRegistry;
+   }
 
    /**
     * Starts everything apart from RemotingService and loading the data.
@@ -1636,16 +1594,13 @@ public class HornetQServerImpl implements HornetQServer
     * {@link #initialisePart2(boolean)}.
     * @param scalingDown
     */
-   private synchronized boolean initialisePart1(boolean scalingDown) throws Exception
+   synchronized boolean initialisePart1(boolean scalingDown) throws Exception
    {
       if (state == SERVER_STATE.STOPPED)
          return false;
-      // Create the pools - we have two pools - one for non scheduled - and another for scheduled
-
-      ThreadFactory tFactory = new HornetQThreadFactory("HornetQ-server-" + this.toString(),
-                                                        false,
-                                                        getThisClassLoader());
 
+      // Create the pools - we have two pools - one for non scheduled - and another for scheduled
+      initializeExecutorServices();
 
       if (configuration.getJournalType() == JournalType.ASYNCIO && !AIOSequentialFileFactory.isSupported())
       {
@@ -1653,21 +1608,6 @@ public class HornetQServerImpl implements HornetQServer
          configuration.setJournalType(JournalType.NIO);
       }
 
-      if (configuration.getThreadPoolMaxSize() == -1)
-      {
-         threadPool = Executors.newCachedThreadPool(tFactory);
-      }
-      else
-      {
-         threadPool = Executors.newFixedThreadPool(configuration.getThreadPoolMaxSize(), tFactory);
-      }
-
-      executorFactory = new OrderedExecutorFactory(threadPool);
-      scheduledPool = new ScheduledThreadPoolExecutor(configuration.getScheduledThreadPoolMaxSize(),
-                                                      new HornetQThreadFactory("HornetQ-scheduled-threads",
-                                                                               false,
-                                                                               getThisClassLoader()));
-
       managementService = new ManagementServiceImpl(mbeanServer, configuration);
 
       if (configuration.getMemoryMeasureInterval() != -1)
@@ -1726,13 +1666,20 @@ public class HornetQServerImpl implements HornetQServer
       // This can't be created until node id is set
       clusterManager =
          new ClusterManager(executorFactory, this, postOffice, scheduledPool, managementService, configuration,
-                            nodeManager, configuration.getHAPolicy().isBackup());
+                            nodeManager, haPolicy.isBackup());
 
       backupManager = new BackupManager(this, executorFactory, scheduledPool, nodeManager, configuration, clusterManager);
 
       clusterManager.deploy();
 
-      remotingService = new RemotingServiceImpl(clusterManager, configuration, this, managementService, scheduledPool, protocolManagerFactories);
+      remotingService = new RemotingServiceImpl(clusterManager,
+                                                configuration,
+                                                this,
+                                                managementService,
+                                                scheduledPool,
+                                                protocolManagerFactories,
+                                                executorFactory.getExecutor(),
+                                                serviceRegistry);
 
       messagingServerControl = managementService.registerServer(postOffice,
                                                                 storageManager,
@@ -1745,7 +1692,7 @@ public class HornetQServerImpl implements HornetQServer
                                                                 queueFactory,
                                                                 scheduledPool,
                                                                 pagingManager,
-                                                                configuration.getHAPolicy().isBackup());
+                                                                haPolicy.isBackup());
 
       // Address settings need to deployed initially, since they're require on paging manager.start()
 
@@ -1802,7 +1749,7 @@ public class HornetQServerImpl implements HornetQServer
    /*
     * Load the data, and start remoting service so clients can connect
     */
-   private synchronized void initialisePart2(boolean scalingDown) throws Exception
+   synchronized void initialisePart2(boolean scalingDown) throws Exception
    {
       // Load the journal and populate queues, transactions and caches in memory
 
@@ -1813,7 +1760,7 @@ public class HornetQServerImpl implements HornetQServer
 
       pagingManager.reloadStores();
 
-      JournalLoadInformation[] journalInfo = loadJournals(scalingDown);
+      JournalLoadInformation[] journalInfo = loadJournals();
 
 
       final ServerInfo dumper = new ServerInfo(this, pagingManager);
@@ -1891,6 +1838,8 @@ public class HornetQServerImpl implements HornetQServer
       {
          activationLatch.countDown();
       }
+
+      callActivationCompleteCallbacks();
    }
 
    private void deploySecurityFromConfiguration()
@@ -1921,35 +1870,18 @@ public class HornetQServerImpl implements HornetQServer
       }
    }
 
-   private JournalLoadInformation[] loadJournals(boolean scalingDown) throws Exception
+   private JournalLoadInformation[] loadJournals() throws Exception
    {
-      JournalLoader journalLoader;
+      JournalLoader journalLoader = activation.createJournalLoader(postOffice,
+            pagingManager,
+            storageManager,
+            queueFactory,
+            nodeManager,
+            managementService,
+            groupingHandler,
+            configuration,
+            parentServer);
 
-      if (scalingDown)
-      {
-         journalLoader = new BackupRecoveryJournalLoader(postOffice,
-                                                         pagingManager,
-                                                         storageManager,
-                                                         queueFactory,
-                                                         nodeManager,
-                                                         managementService,
-                                                         groupingHandler,
-                                                         configuration,
-                                                         parentServer,
-                                                         clusterManager.getHAManager().getScaleDownConnector(),
-                                                         clusterManager.getClusterController());
-      }
-      else
-      {
-         journalLoader = new PostOfficeJournalLoader(postOffice,
-               pagingManager,
-               storageManager,
-               queueFactory,
-               nodeManager,
-               managementService,
-               groupingHandler,
-               configuration);
-      }
       JournalLoadInformation[] journalInfo = new JournalLoadInformation[2];
 
       List<QueueBindingInfo> queueBindingInfos = new ArrayList();
@@ -2063,8 +1995,8 @@ public class HornetQServerImpl implements HornetQServer
 
       Filter filter = FilterImpl.createFilter(filterString);
 
-      long txID = storageManager.generateUniqueID();
-      long queueID = storageManager.generateUniqueID();
+      long txID = storageManager.generateID();
+      long queueID = storageManager.generateID();
 
       PageSubscription pageSubscription;
 
@@ -2212,7 +2144,7 @@ public class HornetQServerImpl implements HornetQServer
    /**
     * Check if journal directory exists or create it (if configured to do so)
     */
-   private void checkJournalDirectory()
+   void checkJournalDirectory()
    {
       File journalDir = new File(configuration.getJournalDirectory());
 
@@ -2229,927 +2161,46 @@ public class HornetQServerImpl implements HornetQServer
       }
    }
 
-   /**
-    * To be called by backup trying to fail back the server
-    */
-   private void startFailbackChecker()
-   {
-      scheduledPool.scheduleAtFixedRate(new FailbackChecker(), 1000L, 1000L, TimeUnit.MILLISECONDS);
-   }
 
    // Inner classes
    // --------------------------------------------------------------------------------
 
-   private class FailbackChecker implements Runnable
+
+
+   public final class ShutdownOnCriticalErrorListener implements IOCriticalErrorListener
    {
-      private boolean restarting = false;
+      boolean failedAlready = false;
 
-      public void run()
+      public synchronized void onIOException(Exception cause, String message, SequentialFile file)
       {
-         try
-         {
-            if (!restarting && nodeManager.isAwaitingFailback())
-            {
-               HornetQServerLogger.LOGGER.awaitFailBack();
-               restarting = true;
-               Thread t = new Thread(new Runnable()
-               {
-                  public void run()
-                  {
-                     try
-                     {
-                        HornetQServerLogger.LOGGER.debug(HornetQServerImpl.this + "::Stopping live node in favor of failback");
-                        stop(true, false, true);
-                        // We need to wait some time before we start the backup again
-                        // otherwise we may eventually start before the live had a chance to get it
-                        Thread.sleep(configuration.getHAPolicy().getFailbackDelay());
-                        synchronized (failbackCheckerGuard)
-                        {
-                           if (cancelFailBackChecker)
-                              return;
-                           if (configuration.getHAPolicy().isSharedStore())
-                           {
-                              configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-                           }
-                           else
-                           {
-                              configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-                           }
-                           HornetQServerLogger.LOGGER.debug(HornetQServerImpl.this +
-                                                               "::Starting backup node now after failback");
-                           start();
-                        }
-                     }
-                     catch (Exception e)
-                     {
-                        HornetQServerLogger.LOGGER.serverRestartWarning();
-                     }
-                  }
-               });
-               t.start();
-            }
-         }
-         catch (Exception e)
+         if (!failedAlready)
          {
-            HornetQServerLogger.LOGGER.serverRestartWarning(e);
+            failedAlready = true;
+
+            HornetQServerLogger.LOGGER.ioCriticalIOError(message, file.toString(), cause);
+
+            stopTheServer(true);
          }
       }
    }
 
-   private final class SharedStoreLiveActivation implements Activation
+
+   /**
+    * This seems duplicate code all over the place, but for security reasons we can't let something like this to be open in a
+    * utility class, as it would be a door to load anything you like in a safe VM.
+    * For that reason any class trying to do a privileged block should do with the AccessController directly.
+    */
+   private static Object safeInitNewInstance(final String className)
    {
-      public void run()
+      return AccessController.doPrivileged(new PrivilegedAction<Object>()
       {
-         try
-         {
-            HornetQServerLogger.LOGGER.awaitingLiveLock();
-
-            checkJournalDirectory();
-
-            if (HornetQServerLogger.LOGGER.isDebugEnabled())
-            {
-               HornetQServerLogger.LOGGER.debug("First part initialization on " + this);
-            }
-
-            if (!initialisePart1(false))
-               return;
-
-            if (nodeManager.isBackupLive())
-            {
-               /*
-                * looks like we've failed over at some point need to inform that we are the backup
-                * so when the current live goes down they failover to us
-                */
-               if (HornetQServerLogger.LOGGER.isDebugEnabled())
-               {
-                  HornetQServerLogger.LOGGER.debug("announcing backup to the former live" + this);
-               }
-               backupManager.start();
-               backupManager.announceBackup();
-               Thread.sleep(configuration.getHAPolicy().getFailbackDelay());
-            }
-
-            nodeManager.startLiveNode();
-
-            if (state == SERVER_STATE.STOPPED || state == SERVER_STATE.STOPPING)
-            {
-               return;
-            }
-
-            initialisePart2(false);
-
-            HornetQServerLogger.LOGGER.serverIsLive();
-         }
-         catch (Exception e)
-         {
-            HornetQServerLogger.LOGGER.initializationError(e);
-         }
-      }
-
-      public void close(boolean permanently) throws Exception
-      {
-         // TO avoid a NPE from stop
-         NodeManager nodeManagerInUse = nodeManager;
-
-         if (nodeManagerInUse != null)
-         {
-            if (permanently)
-            {
-               nodeManagerInUse.crashLiveServer();
-            }
-            else
-            {
-               nodeManagerInUse.pauseLiveServer();
-            }
-         }
-      }
-   }
-
-   private final class SharedStoreBackupActivation implements Activation
-   {
-      public void run()
-      {
-         try
-         {
-            nodeManager.startBackup();
-
-            boolean scalingDown = configuration.getHAPolicy().getBackupStrategy() == BackupStrategy.SCALE_DOWN;
-
-            if (!initialisePart1(scalingDown))
-               return;
-
-            backupManager.start();
-
-            state = SERVER_STATE.STARTED;
-
-            HornetQServerLogger.LOGGER.backupServerStarted(version.getFullVersion(), nodeManager.getNodeId());
-
-            nodeManager.awaitLiveNode();
-
-            configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-
-            backupManager.activated();
-            if (state != SERVER_STATE.STARTED)
-            {
-               return;
-            }
-
-            initialisePart2(scalingDown);
-
-            if (scalingDown)
-            {
-               HornetQServerLogger.LOGGER.backupServerScaledDown();
-               Thread t = new Thread(new Runnable()
-               {
-                  @Override
-                  public void run()
-                  {
-                     try
-                     {
-                        stop();
-                        //we are shared store but if we were started by a parent server then we shouldn't restart
-                        if (configuration.getHAPolicy().isRestartBackup())
-                        {
-                           start();
-                        }
-                     }
-                     catch (Exception e)
-                     {
-                        HornetQServerLogger.LOGGER.serverRestartWarning();
-                     }
-                  }
-               });
-               t.start();
-               return;
-            }
-            else
-            {
-               HornetQServerLogger.LOGGER.backupServerIsLive();
-
-               nodeManager.releaseBackup();
-            }
-            if (configuration.getHAPolicy().isAllowAutoFailBack())
-            {
-               startFailbackChecker();
-            }
-         }
-         catch (InterruptedException e)
-         {
-            // this is ok, we are being stopped
-         }
-         catch (ClosedChannelException e)
-         {
-            // this is ok too, we are being stopped
-         }
-         catch (Exception e)
-         {
-            if (!(e.getCause() instanceof InterruptedException))
-            {
-               HornetQServerLogger.LOGGER.initializationError(e);
-            }
-         }
-         catch (Throwable e)
-         {
-            HornetQServerLogger.LOGGER.initializationError(e);
-         }
-      }
-
-      public void close(boolean permanently) throws Exception
-      {
-
-         // To avoid a NPE cause by the stop
-         NodeManager nodeManagerInUse = nodeManager;
-
-         if (configuration.getHAPolicy().isBackup())
-         {
-            long timeout = 30000;
-
-            long start = System.currentTimeMillis();
-
-            while (backupActivationThread.isAlive() && System.currentTimeMillis() - start < timeout)
-            {
-               if (nodeManagerInUse != null)
-               {
-                  nodeManagerInUse.interrupt();
-               }
-
-               backupActivationThread.interrupt();
-
-               backupActivationThread.join(1000);
-
-            }
-
-            if (System.currentTimeMillis() - start >= timeout)
-            {
-               threadDump("Timed out waiting for backup activation to exit");
-            }
-
-            if (nodeManagerInUse != null)
-            {
-               nodeManagerInUse.stopBackup();
-            }
-         }
-         else
-         {
-
-            if (nodeManagerInUse != null)
-            {
-               // if we are now live, behave as live
-               // We need to delete the file too, otherwise the backup will failover when we shutdown or if the backup is
-               // started before the live
-               if (permanently)
-               {
-                  nodeManagerInUse.crashLiveServer();
-               }
-               else
-               {
-                  nodeManagerInUse.pauseLiveServer();
-               }
-            }
-         }
-      }
-   }
-
-   private final class ShutdownOnCriticalErrorListener implements IOCriticalErrorListener
-   {
-      boolean failedAlready = false;
-
-      public synchronized void onIOException(Exception cause, String message, SequentialFile file)
-      {
-         if (!failedAlready)
-         {
-            failedAlready = true;
-
-            HornetQServerLogger.LOGGER.ioCriticalIOError(message, file.toString(), cause);
-
-            stopTheServer(true);
-         }
-      }
-   }
-
-   private interface Activation extends Runnable
-   {
-      void close(boolean permanently) throws Exception;
-   }
-
-   private final class SharedNothingBackupActivation implements Activation
-   {
-      SharedNothingBackupQuorum backupQuorum;
-      private final boolean attemptFailBack;
-      private String nodeID;
-      ClusterControl clusterControl;
-      private boolean closed;
-
-      public SharedNothingBackupActivation(boolean attemptFailBack)
-      {
-         this.attemptFailBack = attemptFailBack;
-      }
-
-      public void run()
-      {
-         try
-         {
-            synchronized (HornetQServerImpl.this)
-            {
-               state = SERVER_STATE.STARTED;
-            }
-            // move all data away:
-            nodeManager.stop();
-            moveServerData();
-            nodeManager.start();
-            synchronized (this)
-            {
-               if (closed)
-                  return;
-            }
-
-            boolean scalingDown = configuration.getHAPolicy().getBackupStrategy() == BackupStrategy.SCALE_DOWN;
-
-            if (!initialisePart1(scalingDown))
-               return;
-
-            synchronized (this)
-            {
-               if (closed)
-                  return;
-               backupQuorum = new SharedNothingBackupQuorum(storageManager, nodeManager, scheduledPool);
-               clusterManager.getQuorumManager().registerQuorum(backupQuorum);
-            }
-
-            //use a Node Locator to connect to the cluster
-            LiveNodeLocator nodeLocator;
-            if (activationParams.get(ActivationParams.REPLICATION_ENDPOINT) != null)
-            {
-               TopologyMember member = (TopologyMember) activationParams.get(ActivationParams.REPLICATION_ENDPOINT);
-               nodeLocator = new NamedNodeIdNodeLocator(member.getNodeId(), new Pair<>(member.getLive(), member.getBackup()));
-            }
-            else
-            {
-               nodeLocator = configuration.getHAPolicy().getBackupGroupName() == null ?
-                     new AnyLiveNodeLocatorForReplication(backupQuorum, HornetQServerImpl.this) :
-                     new NamedLiveNodeLocatorForReplication(configuration.getHAPolicy().getBackupGroupName(), backupQuorum);
-            }
-            ClusterController clusterController = clusterManager.getClusterController();
-            clusterController.addClusterTopologyListenerForReplication(nodeLocator);
-            //todo do we actually need to wait?
-            clusterController.awaitConnectionToReplicationCluster();
-
-            clusterController.addIncomingInterceptorForReplication(new ReplicationError(HornetQServerImpl.this, nodeLocator));
-
-            // nodeManager.startBackup();
-
-            backupManager.start();
-
-            replicationEndpoint.setBackupQuorum(backupQuorum);
-            replicationEndpoint.setExecutor(executorFactory.getExecutor());
-            EndpointConnector endpointConnector = new EndpointConnector();
-
-            HornetQServerLogger.LOGGER.backupServerStarted(version.getFullVersion(), nodeManager.getNodeId());
-            state = SERVER_STATE.STARTED;
-
-            BACKUP_ACTIVATION signal;
-            do
-            {
-               //locate the first live server to try to replicate
-               nodeLocator.locateNode();
-               if (closed)
-               {
-                  return;
-               }
-               Pair<TransportConfiguration, TransportConfiguration> possibleLive = nodeLocator.getLiveConfiguration();
-               nodeID = nodeLocator.getNodeID();
-               //in a normal (non failback) scenario if we couldn't find our live server we should fail
-               if (!attemptFailBack)
-               {
-                  //this shouldn't happen
-                  if (nodeID == null)
-                     throw new RuntimeException("Could not establish the connection");
-                  nodeManager.setNodeID(nodeID);
-               }
-
-               try
-               {
-                  clusterControl =  clusterController.connectToNodeInReplicatedCluster(possibleLive.getA());
-               }
-               catch (Exception e)
-               {
-                  if (possibleLive.getB() != null)
-                  {
-                     try
-                     {
-                        clusterControl = clusterController.connectToNodeInReplicatedCluster(possibleLive.getB());
-                     }
-                     catch (Exception e1)
-                     {
-                        clusterControl = null;
-                     }
-                  }
-               }
-               if (clusterControl == null)
-               {
-                  //its ok to retry here since we haven't started replication yet
-                  //it may just be the server has gone since discovery
-                  Thread.sleep(clusterController.getRetryIntervalForReplicatedCluster());
-                  signal = BACKUP_ACTIVATION.ALREADY_REPLICATING;
-                  continue;
-               }
-
-               threadPool.execute(endpointConnector);
-               /**
-                * Wait for a signal from the the quorum manager, at this point if replication has been successful we can
-                * fail over or if there is an error trying to replicate (such as already replicating) we try the
-                * process again on the next live server.  All the action happens inside {@link BackupQuorum}
-                */
-               signal = backupQuorum.waitForStatusChange();
-               /**
-                * replicationEndpoint will be holding lots of open files. Make sure they get
-                * closed/sync'ed.
-                */
-               stopComponent(replicationEndpoint);
-               // time to give up
-               if (!isStarted() || signal == STOP)
-                  return;
-                  // time to fail over
-               else if (signal == FAIL_OVER)
-                  break;
-                  // something has gone badly run restart from scratch
-               else if (signal == BACKUP_ACTIVATION.FAILURE_REPLICATING)
-               {
-                  Thread startThread = new Thread(new Runnable()
-                  {
-                     @Override
-                     public void run()
-                     {
-                        try
-                        {
-                           stop();
-                        }
-                        catch (Exception e)
-                        {
-                           HornetQServerLogger.LOGGER.errorRestartingBackupServer(e, HornetQServerImpl.this);
-                        }
-                     }
-                  });
-                  startThread.start();
-                  return;
-               }
-               //ok, this live is no good, let's reset and try again
-               //close this session factory, we're done with it
-               clusterControl.close();
-               backupQuorum.reset();
-               if (replicationEndpoint.getChannel() != null)
-               {
-                  replicationEndpoint.getChannel().close();
-                  replicationEndpoint.setChannel(null);
-               }
-            }
-            while (signal == BACKUP_ACTIVATION.ALREADY_REPLICATING);
-
-            clusterManager.getQuorumManager().unRegisterQuorum(backupQuorum);
-
-            if (!isRemoteBackupUpToDate())
-            {
-               throw HornetQMessageBundle.BUNDLE.backupServerNotInSync();
-            }
-
-            configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-            synchronized (HornetQServerImpl.this)
-            {
-               if (!isStarted())
-                  return;
-               HornetQServerLogger.LOGGER.becomingLive(HornetQServerImpl.this);
-               nodeManager.stopBackup();
-               storageManager.start();
-               backupManager.activated();
-               initialisePart2(scalingDown);
-            }
-         }
-         catch (Exception e)
-         {
-            if ((e instanceof InterruptedException || e instanceof IllegalStateException) && !isStarted())
-               // do not log these errors if the server is being stopped.
-               return;
-            HornetQServerLogger.LOGGER.initializationError(e);
-            e.printStackTrace();
-         }
-      }
-
-      public void close(final boolean permanently) throws Exception
-      {
-         synchronized (this)
-         {
-            if (backupQuorum != null)
-               backupQuorum.causeExit(STOP);
-            closed = true;
-         }
-
-         if (configuration.getHAPolicy().isBackup())
-         {
-            long timeout = 30000;
-
-            long start = System.currentTimeMillis();
-
-            // To avoid a NPE cause by the stop
-            NodeManager nodeManagerInUse = nodeManager;
-
-            while (backupActivationThread.isAlive() && System.currentTimeMillis() - start < timeout)
-            {
-
-               if (nodeManagerInUse != null)
-               {
-                  nodeManagerInUse.interrupt();
-               }
-
-               backupActivationThread.interrupt();
-
-               Thread.sleep(1000);
-            }
-
-            if (System.currentTimeMillis() - start >= timeout)
-            {
-               HornetQServerLogger.LOGGER.backupActivationProblem();
-            }
-
-            if (nodeManagerInUse != null)
-            {
-               nodeManagerInUse.stopBackup();
-            }
-         }
-      }
-
-      /**
-       * Live has notified this server that it is going to stop.
-       */
-      public void failOver(final LiveStopping finalMessage)
-      {
-         if (finalMessage == null)
-         {
-            backupQuorum.causeExit(FAILURE_REPLICATING);
-         }
-         else
-         {
-            backupQuorum.failOver(finalMessage);
-         }
-      }
-
-      private class EndpointConnector implements Runnable
-      {
-         @Override
-         public void run()
-         {
-            try
-            {
-               //we should only try once, if its not there we should move on.
-               clusterControl.getSessionFactory().setReconnectAttempts(1);
-               backupQuorum.setSessionFactory(clusterControl.getSessionFactory());
-               //get the connection and request replication to live
-               clusterControl.authorize();
-               connectToReplicationEndpoint(clusterControl);
-               replicationEndpoint.start();
-               clusterControl.announceReplicatingBackupToLive(attemptFailBack);
-            }
-            catch (Exception e)
-            {
-               //we shouldn't stop the server just mark the connector as tried and unavailable
-               HornetQServerLogger.LOGGER.replicationStartProblem(e);
-               backupQuorum.causeExit(FAILURE_REPLICATING);
-            }
-         }
-
-         private synchronized ReplicationEndpoint connectToReplicationEndpoint(final ClusterControl control) throws Exception
-         {
-            if (!isStarted())
-               return null;
-            if (!configuration.getHAPolicy().isBackup())
-            {
-               throw HornetQMessageBundle.BUNDLE.serverNotBackupServer();
-            }
-
-            Channel replicationChannel = control.createReplicationChannel();
-
-            replicationChannel.setHandler(replicationEndpoint);
-
-            if (replicationEndpoint.getChannel() != null)
-            {
-               throw HornetQMessageBundle.BUNDLE.alreadyHaveReplicationServer();
-            }
-
-            replicationEndpoint.setChannel(replicationChannel);
-
-            return replicationEndpoint;
-         }
-      }
-   }
-
-
-   private final class SharedNothingLiveActivation implements Activation
-   {
-      public void run()
-      {
-         try
-         {
-            if (configuration.isClustered() && configuration.isCheckForLiveServer() && isNodeIdUsed())
-            {
-               configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-               return;
-            }
-
-            initialisePart1(false);
-
-            initialisePart2(false);
-
-            if (identity != null)
-            {
-               HornetQServerLogger.LOGGER.serverIsLive(identity);
-            }
-            else
-            {
-               HornetQServerLogger.LOGGER.serverIsLive();
-            }
-         }
-         catch (Exception e)
-         {
-            HornetQServerLogger.LOGGER.initializationError(e);
-         }
-      }
-
-      /**
-       * Determines whether there is another server already running with this server's nodeID.
-       * <p/>
-       * This can happen in case of a successful fail-over followed by the live's restart
-       * (attempting a fail-back).
-       *
-       * @throws Exception
-       */
-      private boolean isNodeIdUsed() throws Exception
-      {
-         if (configuration.getClusterConfigurations().isEmpty())
-            return false;
-         SimpleString nodeId0;
-         try
-         {
-            nodeId0 = nodeManager.readNodeId();
-         }
-         catch (HornetQIllegalStateException e)
-         {
-            nodeId0 = null;
-         }
-
-         ServerLocatorInternal locator;
-
-         ClusterConnectionConfiguration config = ConfigurationUtils.getReplicationClusterConfiguration(configuration);
-
-         locator = getLocator(config);
-
-         ClientSessionFactoryInternal factory = null;
-
-         NodeIdListener listener = new NodeIdListener(nodeId0);
-
-         locator.addClusterTopologyListener(listener);
-         try
-         {
-            locator.setReconnectAttempts(0);
-            try
-            {
-               locator.addClusterTopologyListener(listener);
-               factory = locator.connectNoWarnings();
-            }
-            catch (Exception notConnected)
-            {
-               return false;
-            }
-
-            listener.latch.await(5, TimeUnit.SECONDS);
-
-            return listener.isNodePresent;
-         }
-         finally
-         {
-            if (factory != null)
-               factory.close();
-            if (locator != null)
-               locator.close();
-         }
-      }
-
-      public void close(boolean permanently) throws Exception
-      {
-         // To avoid a NPE cause by the stop
-         NodeManager nodeManagerInUse = nodeManager;
-
-         if (nodeManagerInUse != null)
-         {
-            if (permanently)
-            {
-               nodeManagerInUse.crashLiveServer();
-            }
-            else
-            {
-               nodeManagerInUse.pauseLiveServer();
-            }
-         }
-      }
-   }
-
-   static final class NodeIdListener implements ClusterTopologyListener
-   {
-      volatile boolean isNodePresent = false;
-
-      private final SimpleString nodeId;
-      private final CountDownLatch latch = new CountDownLatch(1);
-
-      public NodeIdListener(SimpleString nodeId)
-      {
-         this.nodeId = nodeId;
-      }
-
-      @Override
-      public void nodeUP(TopologyMember topologyMember, boolean last)
-      {
-         boolean isOurNodeId = nodeId != null && nodeId.toString().equals(topologyMember.getNodeId());
-         if (isOurNodeId)
-         {
-            isNodePresent = true;
-         }
-         if (isOurNodeId || last)
-         {
-            latch.countDown();
-         }
-      }
-
-      @Override
-      public void nodeDown(long eventUID, String nodeID)
-      {
-         // no-op
-      }
-   }
-
-   private TransportConfiguration[] connectorNameListToArray(final List<String> connectorNames)
-   {
-      TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class,
-                                                                                        connectorNames.size());
-      int count = 0;
-      for (String connectorName : connectorNames)
-      {
-         TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorName);
-
-         if (connector == null)
-         {
-            HornetQServerLogger.LOGGER.bridgeNoConnector(connectorName);
-
-            return null;
-         }
-
-         tcConfigs[count++] = connector;
-      }
-
-      return tcConfigs;
-   }
-
-   /**
-    * This seems duplicate code all over the place, but for security reasons we can't let something like this to be open in a
-    * utility class, as it would be a door to load anything you like in a safe VM.
-    * For that reason any class trying to do a privileged block should do with the AccessController directly.
-    */
-   private static Object safeInitNewInstance(final String className)
-   {
-      return AccessController.doPrivileged(new PrivilegedAction<Object>()
-      {
-         public Object run()
+         public Object run()
          {
             return ClassloadingUtil.newInstanceFromClassLoader(className);
          }
       });
    }
 
-   @Override
-   public void startReplication(CoreRemotingConnection rc, final ClusterConnection clusterConnection,
-                                final Pair<TransportConfiguration, TransportConfiguration> pair, final boolean isFailBackRequest) throws HornetQException
-   {
-      if (replicationManager != null)
-      {
-         throw new HornetQAlreadyReplicatingException();
-      }
-
-      if (!isStarted())
-      {
-         throw new HornetQIllegalStateException();
-      }
-
-      synchronized (replicationLock)
-      {
-
-         if (replicationManager != null)
-         {
-            throw new HornetQAlreadyReplicatingException();
-         }
-         ReplicationFailureListener listener = new ReplicationFailureListener();
-         rc.addCloseListener(listener);
-         rc.addFailureListener(listener);
-         replicationManager = new ReplicationManager(rc, executorFactory);
-         replicationManager.start();
-         Thread t = new Thread(new Runnable()
-         {
-            public void run()
-            {
-               try
-               {
-                  storageManager.startReplication(replicationManager, pagingManager, getNodeID().toString(),
-                                                  isFailBackRequest && configuration.getHAPolicy().isAllowAutoFailBack());
-                  clusterConnection.nodeAnnounced(System.currentTimeMillis(), getNodeID().toString(), configuration.getHAPolicy().getBackupGroupName(), clusterManager.getHAManager().getHAPolicy().getScaleDownGroupName(), pair, true);
-
-                  backupUpToDate = false;
-
-                  if (isFailBackRequest && configuration.getHAPolicy().isAllowAutoFailBack())
-                  {
-                     BackupTopologyListener listener1 = new BackupTopologyListener(getNodeID().toString());
-                     clusterConnection.addClusterTopologyListener(listener1);
-                     if (listener1.waitForBackup())
-                     {
-                        try
-                        {
-                           Thread.sleep(configuration.getHAPolicy().getFailbackDelay());
-                        }
-                        catch (InterruptedException e)
-                        {
-                           //
-                        }
-                        //if we have to many backups kept or arent configured to restart just stop, otherwise restart as a backup
-                        if (!configuration.getHAPolicy().isRestartBackup() && countNumberOfCopiedJournals() >= configuration.getMaxSavedReplicatedJournalsSize() && configuration.getMaxSavedReplicatedJournalsSize() >= 0)
-                        {
-                           stop(true);
-                           HornetQServerLogger.LOGGER.stopReplicatedBackupAfterFailback();
-                        }
-                        else
-                        {
-                           stop(true);
-                           HornetQServerLogger.LOGGER.restartingReplicatedBackupAfterFailback();
-                           configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-                           start();
-                        }
-                     }
-                     else
-                     {
-                        HornetQServerLogger.LOGGER.failbackMissedBackupAnnouncement();
-                     }
-                  }
-               }
-               catch (Exception e)
-               {
-                  if (state == HornetQServerImpl.SERVER_STATE.STARTED)
-                  {
-                  /*
-                   * The reasoning here is that the exception was either caused by (1) the
-                   * (interaction with) the backup, or (2) by an IO Error at the storage. If (1), we
-                   * can swallow the exception and ignore the replication request. If (2) the live
-                   * will crash shortly.
-                   */
-                     HornetQServerLogger.LOGGER.errorStartingReplication(e);
-                  }
-                  try
-                  {
-                     stopComponent(replicationManager);
-                  }
-                  catch (Exception hqe)
-                  {
-                     HornetQServerLogger.LOGGER.errorStoppingReplication(hqe);
-                  }
-                  finally
-                  {
-                     synchronized (replicationLock)
-                     {
-                        replicationManager = null;
-                     }
-                  }
-               }
-            }
-         });
-
-         t.start();
-      }
-   }
-
-   /**
-    * Whether a remote backup server was in sync with its live server. If it was not in sync, it may
-    * not take over the live's functions.
-    * <p/>
-    * A local backup server or a live server should always return {@code true}
-    *
-    * @return whether the backup is up-to-date, if the server is not a backup it always returns
-    * {@code true}.
-    */
-   public boolean isRemoteBackupUpToDate()
-   {
-      return backupUpToDate;
-   }
-
-   public void setRemoteBackupUpToDate()
-   {
-      backupManager.announceBackup();
-      backupUpToDate = true;
-      backupSyncLatch.countDown();
-   }
-
    public void addProtocolManagerFactory(ProtocolManagerFactory factory)
    {
       protocolManagerFactories.add(factory);
@@ -3186,7 +2237,7 @@ public class HornetQServerImpl implements HornetQServer
    }
 
 
-   private int countNumberOfCopiedJournals()
+   int countNumberOfCopiedJournals()
    {
       //will use the main journal to check for how many backups have been kept
       File journalDir = new File(configuration.getJournalDirectory());
@@ -3209,98 +2260,13 @@ public class HornetQServerImpl implements HornetQServer
       return numberOfbackupsSaved;
    }
 
-   private final class ReplicationFailureListener implements FailureListener, CloseListener
-   {
-
-      @Override
-      public void connectionFailed(HornetQException exception, boolean failedOver)
-      {
-         connectionClosed();
-      }
-
-      @Override
-      public void connectionFailed(final HornetQException me, boolean failedOver, String scaleDownTargetNodeID)
-      {
-         connectionFailed(me, failedOver);
-      }
-
-      @Override
-      public void connectionClosed()
-      {
-         threadPool.execute(new Runnable()
-         {
-            public void run()
-            {
-               synchronized (replicationLock)
-               {
-                  if (replicationManager != null)
-                  {
-                     storageManager.stopReplication();
-                     replicationManager = null;
-                  }
-               }
-            }
-         });
-      }
-   }
-
-   /**
-    * @throws HornetQException
-    */
-   public void remoteFailOver(ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) throws HornetQException
-   {
-      HornetQServerLogger.LOGGER.trace("Remote fail-over, got message=" + finalMessage + ", backupUpToDate=" +
-                                          backupUpToDate);
-      if (!configuration.getHAPolicy().isBackup() || configuration.getHAPolicy().isSharedStore())
-      {
-         throw new HornetQInternalErrorException();
-      }
-      if (activation instanceof SharedNothingBackupActivation)
-      {
-         final SharedNothingBackupActivation replicationActivation = ((SharedNothingBackupActivation) activation);
-
-         if (!backupUpToDate)
-         {
-            replicationActivation.failOver(null);
-         }
-         else
-         {
-            replicationActivation.failOver(finalMessage);
-         }
-      }
-   }
-
-
-   private ServerLocatorInternal getLocator(ClusterConnectionConfiguration config) throws HornetQException
-   {
-      ServerLocatorInternal locator;
-      if (config.getDiscoveryGroupName() != null)
-      {
-         DiscoveryGroupConfiguration dg = configuration.getDiscoveryGroupConfigurations().get(config.getDiscoveryGroupName());
-
-         if (dg == null)
-         {
-            throw HornetQMessageBundle.BUNDLE.noDiscoveryGroupFound(dg);
-         }
-         locator = (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(dg);
-      }
-      else
-      {
-         TransportConfiguration[] tcConfigs = config.getStaticConnectors() != null ? connectorNameListToArray(config.getStaticConnectors())
-            : null;
-
-         locator = (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(tcConfigs);
-      }
-      return locator;
-   }
-
    /**
     * Move data away before starting data synchronization for fail-back.
     * <p/>
     * Use case is a server, upon restarting, finding a former backup running in its place. It will
     * move any older data away and log a warning about it.
     */
-   private void moveServerData()
+   void moveServerData()
    {
       String[] dataDirs =
          new String[]{configuration.getBindingsDirectory(),

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveActivation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveActivation.java
new file mode 100644
index 0000000..c863c66
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveActivation.java
@@ -0,0 +1,17 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+public abstract class LiveActivation extends Activation
+{
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveOnlyActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveOnlyActivation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveOnlyActivation.java
new file mode 100644
index 0000000..ceb60d1
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/LiveOnlyActivation.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.Pair;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
+import org.hornetq.core.client.impl.ServerLocatorInternal;
+import org.hornetq.core.postoffice.DuplicateIDCache;
+import org.hornetq.core.postoffice.impl.PostOfficeImpl;
+import org.hornetq.core.remoting.server.RemotingService;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.LiveNodeLocator;
+import org.hornetq.core.server.cluster.HornetQServerSideProtocolManagerFactory;
+import org.hornetq.core.server.cluster.ha.LiveOnlyPolicy;
+import org.hornetq.core.server.cluster.ha.ScaleDownPolicy;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+
+public class LiveOnlyActivation extends Activation
+{
+   //this is how we act when we initially start as live
+   private LiveOnlyPolicy liveOnlyPolicy;
+
+   private final HornetQServerImpl hornetQServer;
+
+   private ServerLocatorInternal scaleDownServerLocator;
+
+   private ClientSessionFactoryInternal scaleDownClientSessionFactory;
+
+   public LiveOnlyActivation(HornetQServerImpl server, LiveOnlyPolicy liveOnlyPolicy)
+   {
+      this.hornetQServer = server;
+      this.liveOnlyPolicy = liveOnlyPolicy;
+   }
+
+   public void run()
+   {
+      try
+      {
+         hornetQServer.initialisePart1(false);
+
+         hornetQServer.initialisePart2(false);
+
+         if (hornetQServer.getIdentity() != null)
+         {
+            HornetQServerLogger.LOGGER.serverIsLive(hornetQServer.getIdentity());
+         }
+         else
+         {
+            HornetQServerLogger.LOGGER.serverIsLive();
+         }
+      }
+      catch (Exception e)
+      {
+         HornetQServerLogger.LOGGER.initializationError(e);
+      }
+   }
+
+   @Override
+   public void close(boolean permanently, boolean restarting) throws Exception
+   {
+      if (scaleDownServerLocator != null)
+      {
+         scaleDownServerLocator.close();
+         scaleDownServerLocator = null;
+      }
+   }
+
+   public void freezeConnections(RemotingService remotingService)
+   {
+      // connect to the scale-down target first so that when we freeze/disconnect the clients we can tell them where
+      // we're sending the messages
+      if (liveOnlyPolicy.getScaleDownPolicy() != null && liveOnlyPolicy.getScaleDownPolicy().isEnabled())
+      {
+         connectToScaleDownTarget(liveOnlyPolicy.getScaleDownPolicy());
+      }
+
+      TransportConfiguration tc = scaleDownClientSessionFactory == null ? null : scaleDownClientSessionFactory.getConnectorConfiguration();
+      String nodeID = tc == null ? null : scaleDownClientSessionFactory.getServerLocator().getTopology().getMember(tc).getNodeId();
+      if (remotingService != null)
+      {
+         remotingService.freeze(nodeID, null);
+      }
+   }
+
+   @Override
+   public void postConnectionFreeze()
+   {
+      if (liveOnlyPolicy.getScaleDownPolicy() != null
+            && liveOnlyPolicy.getScaleDownPolicy().isEnabled()
+            && scaleDownClientSessionFactory != null)
+      {
+         try
+         {
+            scaleDown();
+         }
+         catch (Exception e)
+         {
+            HornetQServerLogger.LOGGER.failedToScaleDown(e);
+         }
+         finally
+         {
+            scaleDownClientSessionFactory.close();
+            scaleDownServerLocator.close();
+         }
+      }
+   }
+
+   public void connectToScaleDownTarget(ScaleDownPolicy scaleDownPolicy)
+   {
+      try
+      {
+         scaleDownServerLocator = ScaleDownPolicy.getScaleDownConnector(scaleDownPolicy, hornetQServer);
+         //use a Node Locator to connect to the cluster
+         scaleDownServerLocator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
+         LiveNodeLocator nodeLocator = scaleDownPolicy.getGroupName() == null ?
+               new AnyLiveNodeLocatorForScaleDown(hornetQServer) :
+               new NamedLiveNodeLocatorForScaleDown(scaleDownPolicy.getGroupName(), hornetQServer);
+         scaleDownServerLocator.addClusterTopologyListener(nodeLocator);
+
+         nodeLocator.connectToCluster(scaleDownServerLocator);
+         // a timeout is necessary here in case we use a NamedLiveNodeLocatorForScaleDown and there's no matching node in the cluster
+         // should the timeout be configurable?
+         nodeLocator.locateNode(HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT);
+         ClientSessionFactoryInternal clientSessionFactory = null;
+         while (clientSessionFactory == null)
+         {
+            Pair<TransportConfiguration, TransportConfiguration> possibleLive = null;
+            try
+            {
+               possibleLive = nodeLocator.getLiveConfiguration();
+               if (possibleLive == null)  // we've tried every connector
+                  break;
+               clientSessionFactory = (ClientSessionFactoryInternal) scaleDownServerLocator.createSessionFactory(possibleLive.getA(), 0, false);
+            }
+            catch (Exception e)
+            {
+               HornetQServerLogger.LOGGER.trace("Failed to connect to " + possibleLive.getA());
+               nodeLocator.notifyRegistrationFailed(false);
+               if (clientSessionFactory != null)
+               {
+                  clientSessionFactory.close();
+               }
+               clientSessionFactory = null;
+               // should I try the backup (i.e. getB()) from possibleLive?
+            }
+         }
+         if (clientSessionFactory != null)
+         {
+            scaleDownClientSessionFactory = clientSessionFactory;
+         }
+         else
+         {
+            throw new HornetQException("Unable to connect to server for scale-down");
+         }
+      }
+      catch (Exception e)
+      {
+         HornetQServerLogger.LOGGER.failedToScaleDown(e);
+      }
+   }
+
+
+   public long scaleDown() throws Exception
+   {
+      ScaleDownHandler scaleDownHandler = new ScaleDownHandler(hornetQServer.getPagingManager(),
+            hornetQServer.getPostOffice(),
+            hornetQServer.getNodeManager(),
+            hornetQServer.getClusterManager().getClusterController());
+      ConcurrentMap<SimpleString, DuplicateIDCache> duplicateIDCaches = ((PostOfficeImpl) hornetQServer.getPostOffice()).getDuplicateIDCaches();
+      Map<SimpleString, List<Pair<byte[], Long>>> duplicateIDMap = new HashMap<>();
+      for (SimpleString address : duplicateIDCaches.keySet())
+      {
+         DuplicateIDCache duplicateIDCache = hornetQServer.getPostOffice().getDuplicateIDCache(address);
+         duplicateIDMap.put(address, duplicateIDCache.getMap());
+      }
+      return scaleDownHandler.scaleDown(scaleDownClientSessionFactory, hornetQServer.getResourceManager(), duplicateIDMap,
+            hornetQServer.getManagementService().getManagementAddress(), null);
+   }
+}


[18/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/NamedLiveNodeLocatorForReplication.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/NamedLiveNodeLocatorForReplication.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/NamedLiveNodeLocatorForReplication.java
index 0980ec1..98e84e2 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/NamedLiveNodeLocatorForReplication.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/NamedLiveNodeLocatorForReplication.java
@@ -29,7 +29,7 @@ import org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum;
  * NamedLiveNodeLocatorForReplication looks for a live server in the cluster with a specific backupGroupName
  *
  * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- * @see org.hornetq.core.server.cluster.ha.HAPolicy#getBackupGroupName()
+ * @see org.hornetq.core.server.cluster.ha.HAPolicy#getGroupName()
  */
 public class NamedLiveNodeLocatorForReplication extends LiveNodeLocator
 {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/PostOfficeJournalLoader.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/PostOfficeJournalLoader.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/PostOfficeJournalLoader.java
index ced98fe..8fba846 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/PostOfficeJournalLoader.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/PostOfficeJournalLoader.java
@@ -122,7 +122,7 @@ public class PostOfficeJournalLoader implements JournalLoader
 
             if (isTopicIdentification)
             {
-               long tx = storageManager.generateUniqueID();
+               long tx = storageManager.generateID();
                storageManager.deleteQueueBinding(tx, queueBindingInfo.getId());
                storageManager.commitBindings(tx);
                continue;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/QueueImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/QueueImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/QueueImpl.java
index 030c596..f4e8fe9 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/QueueImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/QueueImpl.java
@@ -14,6 +14,7 @@ package org.hornetq.core.server.impl;
 
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import java.math.BigDecimal;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -33,10 +34,13 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
 
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
+import org.hornetq.api.core.management.ManagementHelper;
 import org.hornetq.core.filter.Filter;
 import org.hornetq.core.journal.IOAsyncTask;
 import org.hornetq.core.message.impl.MessageImpl;
@@ -47,8 +51,11 @@ import org.hornetq.core.postoffice.Binding;
 import org.hornetq.core.postoffice.Bindings;
 import org.hornetq.core.postoffice.DuplicateIDCache;
 import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.postoffice.impl.PostOfficeImpl;
+import org.hornetq.core.remoting.server.RemotingService;
 import org.hornetq.core.server.Consumer;
 import org.hornetq.core.server.HandleStatus;
+import org.hornetq.core.server.HornetQMessageBundle;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.MessageReference;
@@ -58,14 +65,17 @@ import org.hornetq.core.server.ScheduledDeliveryHandler;
 import org.hornetq.core.server.ServerMessage;
 import org.hornetq.core.server.cluster.RemoteQueueBinding;
 import org.hornetq.core.server.cluster.impl.Redistributor;
+import org.hornetq.core.server.management.ManagementService;
+import org.hornetq.core.server.management.Notification;
 import org.hornetq.core.settings.HierarchicalRepository;
 import org.hornetq.core.settings.HierarchicalRepositoryChangeListener;
 import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.core.settings.impl.SlowConsumerPolicy;
 import org.hornetq.core.transaction.Transaction;
-import org.hornetq.core.transaction.TransactionOperationAbstract;
 import org.hornetq.core.transaction.TransactionPropertyIndexes;
 import org.hornetq.core.transaction.impl.BindingsTransactionImpl;
 import org.hornetq.core.transaction.impl.TransactionImpl;
+import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.utils.ConcurrentHashSet;
 import org.hornetq.utils.FutureLatch;
 import org.hornetq.utils.LinkedListIterator;
@@ -73,6 +83,7 @@ import org.hornetq.utils.PriorityLinkedList;
 import org.hornetq.utils.PriorityLinkedListImpl;
 import org.hornetq.utils.ReferenceCounter;
 import org.hornetq.utils.ReusableLatch;
+import org.hornetq.utils.TypedProperties;
 
 /**
  * Implementation of a Queue
@@ -149,6 +160,8 @@ public class QueueImpl implements Queue
 
    private long messagesAdded;
 
+   private long messagesAcknowledged;
+
    protected final AtomicInteger deliveringCount = new AtomicInteger(0);
 
    private boolean paused;
@@ -204,6 +217,14 @@ public class QueueImpl implements Queue
 
    private final ReusableLatch deliveriesInTransit = new ReusableLatch(0);
 
+   private AtomicLong queueRateCheckTime = new AtomicLong(System.currentTimeMillis());
+
+   private AtomicLong messagesAddedSnapshot = new AtomicLong(0);
+
+   private ScheduledFuture slowConsumerReaperFuture;
+
+   private SlowConsumerReaperRunnable slowConsumerReaperRunnable;
+
    /**
     * This is to avoid multi-thread races on calculating direct delivery,
     * to guarantee ordering will be always be correct
@@ -982,21 +1003,6 @@ public class QueueImpl implements Queue
 
    public long getMessageCount()
    {
-      return getMessageCount(FLUSH_TIMEOUT);
-   }
-
-   public long getMessageCount(final long timeout)
-   {
-      if (timeout > 0)
-      {
-         internalFlushExecutor(timeout);
-      }
-      return getInstantMessageCount();
-   }
-
-
-   public long getInstantMessageCount()
-   {
       synchronized (this)
       {
          if (pageSubscription != null)
@@ -1068,6 +1074,8 @@ public class QueueImpl implements Queue
          postAcknowledge(ref);
       }
 
+      messagesAcknowledged++;
+
    }
 
    public void acknowledge(final Transaction tx, final MessageReference ref) throws Exception
@@ -1093,6 +1101,8 @@ public class QueueImpl implements Queue
 
          getRefsOperation(tx).addAck(ref);
       }
+
+      messagesAcknowledged++;
    }
 
    public void reacknowledge(final Transaction tx, final MessageReference ref) throws Exception
@@ -1108,6 +1118,8 @@ public class QueueImpl implements Queue
 
       // https://issues.jboss.org/browse/HORNETQ-609
       incDelivering();
+
+      messagesAcknowledged++;
    }
 
    private RefsOperation getRefsOperation(final Transaction tx)
@@ -1123,7 +1135,7 @@ public class QueueImpl implements Queue
 
          if (oper == null)
          {
-            oper = new RefsOperation();
+            oper = tx.createRefsOperation(this);
 
             tx.putProperty(TransactionPropertyIndexes.REFS_OPERATION, oper);
 
@@ -1209,17 +1221,6 @@ public class QueueImpl implements Queue
 
    public long getMessagesAdded()
    {
-      return getMessagesAdded(FLUSH_TIMEOUT);
-   }
-
-   public long getMessagesAdded(final long timeout)
-   {
-      if (timeout > 0) internalFlushExecutor(timeout);
-      return getInstantMessagesAdded();
-   }
-
-   public synchronized long getInstantMessagesAdded()
-   {
       if (pageSubscription != null)
       {
          return messagesAdded + pageSubscription.getCounter().getValue() - pagedReferences.get();
@@ -1230,6 +1231,10 @@ public class QueueImpl implements Queue
       }
    }
 
+   public long getMessagesAcknowledged()
+   {
+      return messagesAcknowledged;
+   }
 
    public int deleteAllReferences() throws Exception
    {
@@ -1410,6 +1415,12 @@ public class QueueImpl implements Queue
             }
          }
 
+         if (!deleted)
+         {
+            // Look in scheduled deliveries
+            deleted = scheduledDeliveryHandler.removeReferenceWithID(messageID) != null ? true : false;
+         }
+
          tx.commit();
 
          return deleted;
@@ -1456,6 +1467,11 @@ public class QueueImpl implements Queue
             tx.setContainsPersistent();
          }
 
+         if (slowConsumerReaperFuture != null)
+         {
+            slowConsumerReaperFuture.cancel(false);
+         }
+
          tx.commit();
       }
       catch (Exception e)
@@ -2545,7 +2561,7 @@ public class QueueImpl implements Queue
        and original message id
       */
 
-      long newID = storageManager.generateUniqueID();
+      long newID = storageManager.generateID();
 
       ServerMessage copy = message.makeCopyForExpiryOrDLA(newID, ref, expiry, copyOriginalHeaders);
 
@@ -2578,7 +2594,7 @@ public class QueueImpl implements Queue
    }
 
 
-   private void sendToDeadLetterAddress(final MessageReference ref) throws Exception
+   public void sendToDeadLetterAddress(final MessageReference ref) throws Exception
    {
       sendToDeadLetterAddress(ref, addressSettingsRepository.getMatch(address.toString()).getDeadLetterAddress());
    }
@@ -2804,8 +2820,7 @@ public class QueueImpl implements Queue
       return consumerListClone;
    }
 
-   // Protected as testcases may change this behaviour
-   protected void postAcknowledge(final MessageReference ref)
+   public void postAcknowledge(final MessageReference ref)
    {
       QueueImpl queue = (QueueImpl) ref.getQueue();
 
@@ -2889,6 +2904,21 @@ public class QueueImpl implements Queue
       messagesAdded = 0;
    }
 
+   public synchronized void resetMessagesAcknowledged()
+   {
+      messagesAcknowledged = 0;
+   }
+
+   public float getRate()
+   {
+      float timeSlice = ((System.currentTimeMillis() - queueRateCheckTime.getAndSet(System.currentTimeMillis())) / 1000.0f);
+      if (timeSlice == 0)
+      {
+         messagesAddedSnapshot.getAndSet(messagesAdded);
+         return 0.0f;
+      }
+      return BigDecimal.valueOf((messagesAdded - messagesAddedSnapshot.getAndSet(messagesAdded)) / timeSlice).setScale(2, BigDecimal.ROUND_UP).floatValue();
+   }
 
    // Inner classes
    // --------------------------------------------------------------------------
@@ -2906,189 +2936,6 @@ public class QueueImpl implements Queue
 
    }
 
-   public final class RefsOperation extends TransactionOperationAbstract
-   {
-      List<MessageReference> refsToAck = new ArrayList<MessageReference>();
-
-      List<ServerMessage> pagedMessagesToPostACK = null;
-
-      /**
-       * It will ignore redelivery check, which is used during consumer.close
-       * to not perform reschedule redelivery check
-       */
-      protected boolean ignoreRedeliveryCheck = false;
-
-
-      // once turned on, we shouldn't turn it off, that's why no parameters
-      public void setIgnoreRedeliveryCheck()
-      {
-         ignoreRedeliveryCheck = true;
-      }
-
-      synchronized void addAck(final MessageReference ref)
-      {
-         refsToAck.add(ref);
-         if (ref.isPaged())
-         {
-            if (pagedMessagesToPostACK == null)
-            {
-               pagedMessagesToPostACK = new ArrayList<ServerMessage>();
-            }
-            pagedMessagesToPostACK.add(ref.getMessage());
-         }
-      }
-
-      @Override
-      public void afterRollback(final Transaction tx)
-      {
-         Map<QueueImpl, LinkedList<MessageReference>> queueMap = new HashMap<QueueImpl, LinkedList<MessageReference>>();
-
-         long timeBase = System.currentTimeMillis();
-
-         //add any already acked refs, this means that they have been transferred via a producer.send() and have no
-         // previous state persisted.
-         List<MessageReference> ackedRefs = new ArrayList<>();
-
-         for (MessageReference ref : refsToAck)
-         {
-            ref.setConsumerId(null);
-
-            if (HornetQServerLogger.LOGGER.isTraceEnabled())
-            {
-               HornetQServerLogger.LOGGER.trace("rolling back " + ref);
-            }
-            try
-            {
-               if (ref.isAlreadyAcked())
-               {
-                  ackedRefs.add(ref);
-               }
-               // if ignore redelivery check, we just perform redelivery straight
-               if (ref.getQueue().checkRedelivery(ref, timeBase, ignoreRedeliveryCheck))
-               {
-                  LinkedList<MessageReference> toCancel = queueMap.get(ref.getQueue());
-
-                  if (toCancel == null)
-                  {
-                     toCancel = new LinkedList<MessageReference>();
-
-                     queueMap.put((QueueImpl) ref.getQueue(), toCancel);
-                  }
-
-                  toCancel.addFirst(ref);
-               }
-            }
-            catch (Exception e)
-            {
-               HornetQServerLogger.LOGGER.errorCheckingDLQ(e);
-            }
-         }
-
-         for (Map.Entry<QueueImpl, LinkedList<MessageReference>> entry : queueMap.entrySet())
-         {
-            LinkedList<MessageReference> refs = entry.getValue();
-
-            QueueImpl queue = entry.getKey();
-
-            synchronized (queue)
-            {
-               queue.postRollback(refs);
-            }
-         }
-
-         if (!ackedRefs.isEmpty())
-         {
-            //since pre acked refs have no previous state we need to actually create this by storing the message and the
-            //message references
-            try
-            {
-               Transaction ackedTX = new TransactionImpl(storageManager);
-               for (MessageReference ref : ackedRefs)
-               {
-                  ServerMessage message = ref.getMessage();
-                  if (message.isDurable())
-                  {
-                     int durableRefCount = message.incrementDurableRefCount();
-
-                     if (durableRefCount == 1)
-                     {
-                        storageManager.storeMessageTransactional(ackedTX.getID(), message);
-                     }
-                     Queue queue = ref.getQueue();
-
-                     storageManager.storeReferenceTransactional(ackedTX.getID(), queue.getID(), message.getMessageID());
-
-                     ackedTX.setContainsPersistent();
-                  }
-
-                  message.incrementRefCount();
-               }
-               ackedTX.commit(true);
-            }
-            catch (Exception e)
-            {
-               e.printStackTrace();
-            }
-         }
-      }
-
-      @Override
-      public void afterCommit(final Transaction tx)
-      {
-         for (MessageReference ref : refsToAck)
-         {
-            synchronized (ref.getQueue())
-            {
-               postAcknowledge(ref);
-            }
-         }
-
-         if (pagedMessagesToPostACK != null)
-         {
-            for (ServerMessage msg : pagedMessagesToPostACK)
-            {
-               try
-               {
-                  msg.decrementRefCount();
-               }
-               catch (Exception e)
-               {
-                  HornetQServerLogger.LOGGER.warn(e.getMessage(), e);
-               }
-            }
-         }
-      }
-
-      @Override
-      public synchronized List<MessageReference> getRelatedMessageReferences()
-      {
-         List<MessageReference> listRet = new LinkedList<MessageReference>();
-         listRet.addAll(listRet);
-         return listRet;
-      }
-
-      @Override
-      public synchronized List<MessageReference> getListOnConsumer(long consumerID)
-      {
-         List<MessageReference> list = new LinkedList<MessageReference>();
-         for (MessageReference ref : refsToAck)
-         {
-            if (ref.getConsumerId() != null && ref.getConsumerId().equals(consumerID))
-            {
-               list.add(ref);
-            }
-         }
-
-         return list;
-      }
-
-      public List<MessageReference> getReferencesToAcknowledge()
-      {
-         return refsToAck;
-      }
-
-   }
-
    private class DelayedAddRedistributor implements Runnable
    {
       private final Executor executor1;
@@ -3309,16 +3156,66 @@ public class QueueImpl implements Queue
       return deliveringCount.incrementAndGet();
    }
 
-   private void decDelivering()
+   public void decDelivering()
    {
       deliveringCount.decrementAndGet();
    }
 
-   private void configureExpiry(final SimpleString expiryAddressArgument)
+   private void configureExpiry(final AddressSettings settings)
    {
-      this.expiryAddress = expiryAddressArgument;
+      this.expiryAddress = settings == null ? null : settings.getExpiryAddress();
    }
 
+   private void configureSlowConsumerReaper(final AddressSettings settings)
+   {
+      if (settings == null || settings.getSlowConsumerThreshold() == AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD)
+      {
+         if (slowConsumerReaperFuture != null)
+         {
+            slowConsumerReaperFuture.cancel(false);
+            slowConsumerReaperFuture = null;
+            slowConsumerReaperRunnable = null;
+            if (HornetQServerLogger.LOGGER.isDebugEnabled())
+            {
+               HornetQServerLogger.LOGGER.debug("Cancelled slow-consumer-reaper thread for queue \"" + getName() + "\"");
+            }
+         }
+      }
+      else
+      {
+         if (slowConsumerReaperRunnable == null)
+         {
+            scheduleSlowConsumerReaper(settings);
+         }
+         else if (slowConsumerReaperRunnable.checkPeriod != settings.getSlowConsumerCheckPeriod() ||
+            slowConsumerReaperRunnable.threshold != settings.getSlowConsumerThreshold() ||
+            !slowConsumerReaperRunnable.policy.equals(settings.getSlowConsumerPolicy()))
+         {
+            slowConsumerReaperFuture.cancel(false);
+            scheduleSlowConsumerReaper(settings);
+         }
+      }
+   }
+
+   void scheduleSlowConsumerReaper(AddressSettings settings)
+   {
+      slowConsumerReaperRunnable = new SlowConsumerReaperRunnable(settings.getSlowConsumerCheckPeriod(),
+                                                                  settings.getSlowConsumerThreshold(),
+                                                                  settings.getSlowConsumerPolicy());
+
+      slowConsumerReaperFuture = scheduledExecutor.scheduleWithFixedDelay(slowConsumerReaperRunnable,
+                                                                          settings.getSlowConsumerCheckPeriod(),
+                                                                          settings.getSlowConsumerCheckPeriod(),
+                                                                          TimeUnit.SECONDS);
+
+      if (HornetQServerLogger.LOGGER.isDebugEnabled())
+      {
+         HornetQServerLogger.LOGGER.debug("Scheduled slow-consumer-reaper thread for queue \"" + getName() +
+                                             "\"; slow-consumer-check-period=" + settings.getSlowConsumerCheckPeriod() +
+                                             ", slow-consumer-threshold=" + settings.getSlowConsumerThreshold() +
+                                             ", slow-consumer-policy=" + settings.getSlowConsumerPolicy());
+      }
+   }
 
    private class AddressSettingsRepositoryListener implements HierarchicalRepositoryChangeListener
    {
@@ -3326,13 +3223,103 @@ public class QueueImpl implements Queue
       public void onChange()
       {
          AddressSettings settings = addressSettingsRepository.getMatch(address.toString());
-         if (settings == null)
+         configureExpiry(settings);
+         configureSlowConsumerReaper(settings);
+      }
+   }
+
+   private final class SlowConsumerReaperRunnable implements Runnable
+   {
+      private SlowConsumerPolicy policy;
+      private float threshold;
+      private long checkPeriod;
+
+      public SlowConsumerReaperRunnable(long checkPeriod, float threshold, SlowConsumerPolicy policy)
+      {
+         this.checkPeriod = checkPeriod;
+         this.policy = policy;
+         this.threshold = threshold;
+      }
+
+      @Override
+      public void run()
+      {
+         float queueRate = getRate();
+         if (HornetQServerLogger.LOGGER.isDebugEnabled())
          {
-            configureExpiry(null);
+            HornetQServerLogger.LOGGER.debug(getAddress() + ":" + getName() + " has " + getConsumerCount() + " consumer(s) and is receiving messages at a rate of " + queueRate + " msgs/second.");
          }
-         else
+         for (Consumer consumer : getConsumers())
          {
-            configureExpiry(settings.getExpiryAddress());
+            if (consumer instanceof ServerConsumerImpl)
+            {
+               ServerConsumerImpl serverConsumer = (ServerConsumerImpl) consumer;
+               float consumerRate = serverConsumer.getRate();
+               if (queueRate < threshold)
+               {
+                  if (HornetQServerLogger.LOGGER.isDebugEnabled())
+                  {
+                     HornetQServerLogger.LOGGER.debug("Insufficient messages received on queue \"" + getName() + "\" to satisfy slow-consumer-threshold. Skipping inspection of consumer.");
+                  }
+               }
+               else if (consumerRate < threshold)
+               {
+                  RemotingConnection connection = null;
+                  RemotingService remotingService = ((PostOfficeImpl) postOffice).getServer().getRemotingService();
+
+                  for (RemotingConnection potentialConnection : remotingService.getConnections())
+                  {
+                     if (potentialConnection.getID().toString().equals(serverConsumer.getConnectionID()))
+                     {
+                        connection = potentialConnection;
+                     }
+                  }
+
+                  if (connection != null)
+                  {
+                     HornetQServerLogger.LOGGER.slowConsumerDetected(serverConsumer.getSessionID(), serverConsumer.getID(), getName().toString(), connection.getRemoteAddress(), threshold, consumerRate);
+                     if (policy.equals(SlowConsumerPolicy.KILL))
+                     {
+                        remotingService.removeConnection(connection.getID());
+                        connection.fail(HornetQMessageBundle.BUNDLE.connectionsClosedByManagement(connection.getRemoteAddress()));
+                     }
+                     else if (policy.equals(SlowConsumerPolicy.NOTIFY))
+                     {
+                        TypedProperties props = new TypedProperties();
+
+                        props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT, getConsumerCount());
+
+                        props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, address);
+
+                        if (connection != null)
+                        {
+                           props.putSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS, SimpleString.toSimpleString(connection.getRemoteAddress()));
+
+                           if (connection.getID() != null)
+                           {
+                              props.putSimpleStringProperty(ManagementHelper.HDR_CONNECTION_NAME, SimpleString.toSimpleString(connection.getID().toString()));
+                           }
+                        }
+
+                        props.putLongProperty(ManagementHelper.HDR_CONSUMER_NAME, serverConsumer.getID());
+
+                        props.putSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME, SimpleString.toSimpleString(serverConsumer.getSessionID()));
+
+                        Notification notification = new Notification(null, CoreNotificationType.CONSUMER_SLOW, props);
+
+                        ManagementService managementService = ((PostOfficeImpl) postOffice).getServer().getManagementService();
+                        try
+                        {
+                           managementService.sendNotification(notification);
+                        }
+                        catch (Exception e)
+                        {
+                           HornetQServerLogger.LOGGER.failedToSendSlowConsumerNotification(notification, e);
+                        }
+                     }
+                  }
+               }
+            }
          }
       }
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/RefsOperation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/RefsOperation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/RefsOperation.java
new file mode 100644
index 0000000..8a7a87c
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/RefsOperation.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.MessageReference;
+import org.hornetq.core.server.Queue;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.transaction.Transaction;
+import org.hornetq.core.transaction.TransactionOperationAbstract;
+import org.hornetq.core.transaction.impl.TransactionImpl;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+public class RefsOperation extends TransactionOperationAbstract
+{
+   private final StorageManager storageManager;
+   private Queue queue;
+   List<MessageReference> refsToAck = new ArrayList<MessageReference>();
+
+   List<ServerMessage> pagedMessagesToPostACK = null;
+
+   /**
+    * It will ignore redelivery check, which is used during consumer.close
+    * to not perform reschedule redelivery check
+    */
+   protected boolean ignoreRedeliveryCheck = false;
+
+   public RefsOperation(Queue queue, StorageManager storageManager)
+   {
+      this.queue = queue;
+      this.storageManager = storageManager;
+   }
+
+   // once turned on, we shouldn't turn it off, that's why no parameters
+   public void setIgnoreRedeliveryCheck()
+   {
+      ignoreRedeliveryCheck = true;
+   }
+
+   synchronized void addAck(final MessageReference ref)
+   {
+      refsToAck.add(ref);
+      if (ref.isPaged())
+      {
+         if (pagedMessagesToPostACK == null)
+         {
+            pagedMessagesToPostACK = new ArrayList<ServerMessage>();
+         }
+         pagedMessagesToPostACK.add(ref.getMessage());
+      }
+   }
+
+   @Override
+   public void afterRollback(final Transaction tx)
+   {
+      Map<QueueImpl, LinkedList<MessageReference>> queueMap = new HashMap<QueueImpl, LinkedList<MessageReference>>();
+
+      long timeBase = System.currentTimeMillis();
+
+      //add any already acked refs, this means that they have been transferred via a producer.send() and have no
+      // previous state persisted.
+      List<MessageReference> ackedRefs = new ArrayList<>();
+
+      for (MessageReference ref : refsToAck)
+      {
+         ref.setConsumerId(null);
+
+         if (HornetQServerLogger.LOGGER.isTraceEnabled())
+         {
+            HornetQServerLogger.LOGGER.trace("rolling back " + ref);
+         }
+         try
+         {
+            if (ref.isAlreadyAcked())
+            {
+               ackedRefs.add(ref);
+            }
+            // if ignore redelivery check, we just perform redelivery straight
+            if (ref.getQueue().checkRedelivery(ref, timeBase, ignoreRedeliveryCheck))
+            {
+               LinkedList<MessageReference> toCancel = queueMap.get(ref.getQueue());
+
+               if (toCancel == null)
+               {
+                  toCancel = new LinkedList<MessageReference>();
+
+                  queueMap.put((QueueImpl) ref.getQueue(), toCancel);
+               }
+
+               toCancel.addFirst(ref);
+            }
+         }
+         catch (Exception e)
+         {
+            HornetQServerLogger.LOGGER.errorCheckingDLQ(e);
+         }
+      }
+
+      for (Map.Entry<QueueImpl, LinkedList<MessageReference>> entry : queueMap.entrySet())
+      {
+         LinkedList<MessageReference> refs = entry.getValue();
+
+         QueueImpl queue = entry.getKey();
+
+         synchronized (queue)
+         {
+            queue.postRollback(refs);
+         }
+      }
+
+      if (!ackedRefs.isEmpty())
+      {
+         //since pre acked refs have no previous state we need to actually create this by storing the message and the
+         //message references
+         try
+         {
+            Transaction ackedTX = new TransactionImpl(storageManager);
+            for (MessageReference ref : ackedRefs)
+            {
+               ServerMessage message = ref.getMessage();
+               if (message.isDurable())
+               {
+                  int durableRefCount = message.incrementDurableRefCount();
+
+                  if (durableRefCount == 1)
+                  {
+                     storageManager.storeMessageTransactional(ackedTX.getID(), message);
+                  }
+                  Queue queue = ref.getQueue();
+
+                  storageManager.storeReferenceTransactional(ackedTX.getID(), queue.getID(), message.getMessageID());
+
+                  ackedTX.setContainsPersistent();
+               }
+
+               message.incrementRefCount();
+            }
+            ackedTX.commit(true);
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+         }
+      }
+   }
+
+   @Override
+   public void afterCommit(final Transaction tx)
+   {
+      for (MessageReference ref : refsToAck)
+      {
+         synchronized (ref.getQueue())
+         {
+            queue.postAcknowledge(ref);
+         }
+      }
+
+      if (pagedMessagesToPostACK != null)
+      {
+         for (ServerMessage msg : pagedMessagesToPostACK)
+         {
+            try
+            {
+               msg.decrementRefCount();
+            }
+            catch (Exception e)
+            {
+               HornetQServerLogger.LOGGER.warn(e.getMessage(), e);
+            }
+         }
+      }
+   }
+
+   @Override
+   public synchronized List<MessageReference> getRelatedMessageReferences()
+   {
+      List<MessageReference> listRet = new LinkedList<MessageReference>();
+      listRet.addAll(listRet);
+      return listRet;
+   }
+
+   @Override
+   public synchronized List<MessageReference> getListOnConsumer(long consumerID)
+   {
+      List<MessageReference> list = new LinkedList<MessageReference>();
+      for (MessageReference ref : refsToAck)
+      {
+         if (ref.getConsumerId() != null && ref.getConsumerId().equals(consumerID))
+         {
+            list.add(ref);
+         }
+      }
+
+      return list;
+   }
+
+   public List<MessageReference> getReferencesToAcknowledge()
+   {
+      return refsToAck;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ReplicationError.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ReplicationError.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ReplicationError.java
index f7625e6..7bcb040 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ReplicationError.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ReplicationError.java
@@ -30,7 +30,7 @@ import org.hornetq.spi.core.protocol.RemotingConnection;
  * Stops the backup in case of an error at the start of Replication.
  * <p>
  * Using an interceptor for the task to avoid a server reference inside of the 'basic' channel-0
- * handler at {@link ClientSessionFactoryImpl#Channel0Handler}. As {@link ClientSessionFactoryImpl}
+ * handler at {@link org.hornetq.core.protocol.core.impl.HornetQClientProtocolManager.Channel0Handler}. As {@link org.hornetq.core.protocol.core.impl.HornetQClientProtocolManager}
  * is also shipped in the HQ-client JAR (which does not include {@link HornetQServer}).
  */
 final class ReplicationError implements Interceptor

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ScaleDownHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ScaleDownHandler.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ScaleDownHandler.java
index dd166f9..c7ce890 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ScaleDownHandler.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ScaleDownHandler.java
@@ -80,6 +80,7 @@ public class ScaleDownHandler
       ClusterControl clusterControl = clusterController.connectToNodeInCluster((ClientSessionFactoryInternal) sessionFactory);
       clusterControl.authorize();
       long num = scaleDownMessages(sessionFactory, targetNodeId);
+      HornetQServerLogger.LOGGER.info("Scaled down " + num + " messages total.");
       scaleDownTransactions(sessionFactory, resourceManager);
       scaleDownDuplicateIDs(duplicateIDMap, sessionFactory, managementAddress);
       clusterControl.announceScaleDown(new SimpleString(this.targetNodeId), nodeManager.getNodeId());
@@ -107,11 +108,8 @@ public class ScaleDownHandler
             boolean storeAndForward = false;
             if (address.toString().startsWith("sf."))
             {
-               if (address.toString().endsWith(targetNodeId))
-               {
-                  // send messages in this queue to the original address
-                  storeAndForward = true;
-               }
+               // these get special treatment later
+               storeAndForward = true;
             }
 
             // this means we haven't inspected this address before
@@ -159,10 +157,72 @@ public class ScaleDownHandler
                      // loop through every message of this queue
                      while (bigLoopMessageIterator.hasNext())
                      {
+                        MessageReference bigLoopRef = bigLoopMessageIterator.next();
+                        Message message = bigLoopRef.getMessage().copy();
+
                         if (storeAndForward)
                         {
-                           MessageReference bigLoopRef = bigLoopMessageIterator.next();
-                           Message message = bigLoopRef.getMessage();
+                           if (address.toString().endsWith(targetNodeId))
+                           {
+                              /* Here we are taking messages out of a store-and-forward queue and sending them to the corresponding
+                               * address on the scale-down target server.  However, we have to take the existing _HQ_ROUTE_TOsf.*
+                               * property and put its value into the _HQ_ROUTE_TO property so the message is routed properly.
+                               */
+
+                              byte[] oldRouteToIDs = null;
+
+                              List<SimpleString> propertiesToRemove = new ArrayList<>();
+                              message.removeProperty(MessageImpl.HDR_ROUTE_TO_IDS);
+                              for (SimpleString propName : message.getPropertyNames())
+                              {
+                                 if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS))
+                                 {
+                                    if (propName.toString().endsWith(targetNodeId))
+                                    {
+                                       oldRouteToIDs = message.getBytesProperty(propName);
+                                    }
+                                    propertiesToRemove.add(propName);
+                                 }
+                              }
+
+                              for (SimpleString propertyToRemove : propertiesToRemove)
+                              {
+                                 message.removeProperty(propertyToRemove);
+                              }
+
+                              message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_IDS, oldRouteToIDs);
+                           }
+                           else
+                           {
+                              /* Here we are taking messages out of a store-and-forward queue and sending them to the corresponding
+                               * store-and-forward address on the scale-down target server.  In this case we use a special property
+                               * for the queue ID so that the scale-down target server can route it appropriately.
+                               */
+                              byte[] oldRouteToIDs = null;
+
+                              List<SimpleString> propertiesToRemove = new ArrayList<>();
+                              message.removeProperty(MessageImpl.HDR_ROUTE_TO_IDS);
+                              for (SimpleString propName : message.getPropertyNames())
+                              {
+                                 if (propName.startsWith(MessageImpl.HDR_ROUTE_TO_IDS))
+                                 {
+                                    if (propName.toString().endsWith(address.toString().substring(address.toString().lastIndexOf("."))))
+                                    {
+                                       oldRouteToIDs = message.getBytesProperty(propName);
+                                    }
+                                    propertiesToRemove.add(propName);
+                                 }
+                              }
+
+                              for (SimpleString propertyToRemove : propertiesToRemove)
+                              {
+                                 message.removeProperty(propertyToRemove);
+                              }
+
+                              message.putBytesProperty(MessageImpl.HDR_SCALEDOWN_TO_IDS, oldRouteToIDs);
+                           }
+
+                           HornetQServerLogger.LOGGER.debug("Scaling down message " + message + " from " + address + " to " + message.getAddress() + " on node " + targetNodeId);
                            producer.send(message.getAddress(), message);
                            messageCount++;
                            bigLoopQueue.deleteReference(message.getMessageID());
@@ -171,8 +231,7 @@ public class ScaleDownHandler
                         {
                            List<Queue> queuesWithMessage = new ArrayList<>();
                            queuesWithMessage.add(bigLoopQueue);
-                           MessageReference bigLoopRef = bigLoopMessageIterator.next();
-                           long messageId = bigLoopRef.getMessage().getMessageID();
+                           long messageId = message.getMessageID();
 
                            getQueuesWithMessage(store, queues, queueIterators, checkedQueues, bigLoopQueue, queuesWithMessage, bigLoopRef, messageId);
 
@@ -200,9 +259,8 @@ public class ScaleDownHandler
                            }
 
                            logMessage.delete(logMessage.length() - 2, logMessage.length());  // trim off the trailing comma and space
-                           HornetQServerLogger.LOGGER.info(logMessage.append(" on address ").append(address));
+                           HornetQServerLogger.LOGGER.debug(logMessage.append(" on address ").append(address));
 
-                           Message message = bigLoopRef.getMessage();
                            message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_IDS, buffer.array());
                            //we need this incase we are sending back to the source server of the message, this basically
                            //acts like the bridge and ignores dup detection
@@ -258,6 +316,7 @@ public class ScaleDownHandler
       Map<String, Long> queueIDs = new HashMap<>();
       for (Xid xid : preparedTransactions)
       {
+         HornetQServerLogger.LOGGER.debug("Scaling down transaction: " + xid);
          Transaction transaction = resourceManager.getTransaction(xid);
          session.start(xid, XAResource.TMNOFLAGS);
          List<TransactionOperation> allOperations = transaction.getAllOperations();
@@ -293,9 +352,9 @@ public class ScaleDownHandler
                   queueIds.getA().add(queueID);
                }
             }
-            else if (operation instanceof QueueImpl.RefsOperation)
+            else if (operation instanceof RefsOperation)
             {
-               QueueImpl.RefsOperation refsOperation = (QueueImpl.RefsOperation) operation;
+               RefsOperation refsOperation = (RefsOperation) operation;
                List<MessageReference> refs = refsOperation.getReferencesToAcknowledge();
                for (MessageReference ref : refs)
                {
@@ -456,6 +515,7 @@ public class ScaleDownHandler
       if (queueID == -1)
       {
          session.createQueue(addressName, queue.getName(), queue.getFilter() == null ? null : queue.getFilter().getFilterString(), queue.isDurable());
+         HornetQServerLogger.LOGGER.debug("Failed to get queue ID, creating queue [addressName=" + addressName + ", queueName=" + queue.getName() + ", filter=" + (queue.getFilter() == null ? "" : queue.getFilter().getFilterString()) + ", durable=" + queue.isDurable() + "]");
          queueID = getQueueID(session, queue.getName());
       }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerConsumerImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerConsumerImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerConsumerImpl.java
index 2bc2e26..2d1f8a3 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerConsumerImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerConsumerImpl.java
@@ -12,12 +12,14 @@
  */
 package org.hornetq.core.server.impl;
 
+import java.math.BigDecimal;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.concurrent.ConcurrentLinkedQueue;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
@@ -26,8 +28,8 @@ import org.hornetq.api.core.HornetQBuffers;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.HornetQIllegalStateException;
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.client.impl.ClientConsumerImpl;
 import org.hornetq.core.filter.Filter;
 import org.hornetq.core.message.BodyEncoder;
@@ -73,7 +75,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
 
    private final long id;
 
-   private final Queue messageQueue;
+   protected final Queue messageQueue;
 
    private final Filter filter;
 
@@ -85,6 +87,8 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
 
    private final boolean supportLargeMessage;
 
+   private Object protocolContext;
+
    /**
     * We get a readLock when a message is handled, and return the readLock when the message is finally delivered
     * When stopping the consumer we need to get a writeLock to make sure we had all delivery finished
@@ -109,13 +113,13 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
     */
    private final boolean browseOnly;
 
-   private BrowserDeliverer browserDeliverer;
+   protected BrowserDeliverer browserDeliverer;
 
    private final boolean strictUpdateDeliveryCount;
 
    private final StorageManager storageManager;
 
-   private final java.util.Queue<MessageReference> deliveringRefs = new ConcurrentLinkedQueue<MessageReference>();
+   protected final java.util.Queue<MessageReference> deliveringRefs = new ConcurrentLinkedQueue<MessageReference>();
 
    private final SessionCallback callback;
 
@@ -135,6 +139,12 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
 
    private final long creationTime;
 
+   private AtomicLong consumerRateCheckTime = new AtomicLong(System.currentTimeMillis());
+
+   private AtomicLong messageConsumedSnapshot = new AtomicLong(0);
+
+   private long acks;
+
    // Constructors ---------------------------------------------------------------------------------
 
    public ServerConsumerImpl(final long id,
@@ -223,6 +233,16 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
    // ServerConsumer implementation
    // ----------------------------------------------------------------------
 
+   public Object getProtocolContext()
+   {
+      return protocolContext;
+   }
+
+   public void setProtocolContext(Object protocolContext)
+   {
+      this.protocolContext = protocolContext;
+   }
+
    public long getID()
    {
       return id;
@@ -266,7 +286,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
 
    public HandleStatus handle(final MessageReference ref) throws Exception
    {
-      if (availableCredits != null && availableCredits.get() <= 0)
+      if (callback != null && !callback.hasCredits(this) || availableCredits != null && availableCredits.get() <= 0)
       {
          if (HornetQServerLogger.LOGGER.isDebugEnabled())
          {
@@ -408,6 +428,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
       return filter;
    }
 
+   @Override
    public void close(final boolean failed) throws Exception
    {
       callback.removeReadyListener(this);
@@ -421,16 +442,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
          del.finish();
       }
 
-      if (browseOnly)
-      {
-         browserDeliverer.close();
-      }
-      else
-      {
-         messageQueue.removeConsumer(this);
-      }
-
-      session.removeConsumer(id);
+      removeItself();
 
       LinkedList<MessageReference> refs = cancelRefs(failed, false, null);
 
@@ -472,12 +484,27 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
 
          props.putSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME, SimpleString.toSimpleString(session.getName()));
 
-         Notification notification = new Notification(null, NotificationType.CONSUMER_CLOSED, props);
+         Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CLOSED, props);
 
          managementService.sendNotification(notification);
       }
    }
 
+   @Override
+   public void removeItself() throws Exception
+   {
+      if (browseOnly)
+      {
+         browserDeliverer.close();
+      }
+      else
+      {
+         messageQueue.removeConsumer(this);
+      }
+
+      session.removeConsumer(id);
+   }
+
    /**
     * Prompt delivery and send a "forced delivery" message to the consumer.
     * <p/>
@@ -513,12 +540,12 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
                   }
                   else
                   {
-                     ServerMessage forcedDeliveryMessage = new ServerMessageImpl(storageManager.generateUniqueID(), 50);
+                     ServerMessage forcedDeliveryMessage = new ServerMessageImpl(storageManager.generateID(), 50);
 
                      forcedDeliveryMessage.putLongProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE, sequence);
                      forcedDeliveryMessage.setAddress(messageQueue.getName());
 
-                     callback.sendMessage(forcedDeliveryMessage, id, 0);
+                     callback.sendMessage(forcedDeliveryMessage, ServerConsumerImpl.this, 0);
                   }
                }
             }
@@ -565,7 +592,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
             }
             if (performACK)
             {
-               acknowledge(false, tx, ref.getMessage().getMessageID());
+               acknowledge(tx, ref.getMessage().getMessageID());
 
                performACK = false;
             }
@@ -655,7 +682,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
       }
    }
 
-   public void receiveCredits(final int credits) throws Exception
+   public void receiveCredits(final int credits)
    {
       if (credits == -1)
       {
@@ -705,7 +732,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
       return messageQueue;
    }
 
-   public void acknowledge(final boolean autoCommitAcks, Transaction tx, final long messageID) throws Exception
+   public void acknowledge(Transaction tx, final long messageID) throws Exception
    {
       if (browseOnly)
       {
@@ -720,7 +747,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
 
       boolean startedTransaction = false;
 
-      if (tx == null || autoCommitAcks)
+      if (tx == null)
       {
          startedTransaction = true;
          tx = new TransactionImpl(storageManager);
@@ -745,6 +772,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
             }
 
             ref.getQueue().acknowledge(tx, ref);
+            acks++;
          }
          while (ref.getMessage().getMessageID() != messageID);
 
@@ -781,7 +809,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
       }
    }
 
-   public void individualAcknowledge(final boolean autoCommitAcks, final Transaction tx, final long messageID) throws Exception
+   public void individualAcknowledge(final Transaction tx, final long messageID) throws Exception
    {
       if (browseOnly)
       {
@@ -795,7 +823,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
          throw new IllegalStateException("Cannot find ref to ack " + messageID);
       }
 
-      if (autoCommitAcks)
+      if (tx == null)
       {
          ref.getQueue().acknowledge(ref);
       }
@@ -803,6 +831,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
       {
          ref.getQueue().acknowledge(tx, ref);
       }
+      acks++;
    }
 
    public void individualCancel(final long messageID, boolean failed) throws Exception
@@ -896,12 +925,23 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
    @Override
    public void disconnect()
    {
-      callback.disconnect(id, getQueue().getName().toString());
+      callback.disconnect(this, getQueue().getName().toString());
+   }
+
+   public float getRate()
+   {
+      float timeSlice = ((System.currentTimeMillis() - consumerRateCheckTime.getAndSet(System.currentTimeMillis())) / 1000.0f);
+      if (timeSlice == 0)
+      {
+         messageConsumedSnapshot.getAndSet(acks);
+         return 0.0f;
+      }
+      return BigDecimal.valueOf((acks - messageConsumedSnapshot.getAndSet(acks)) / timeSlice).setScale(2, BigDecimal.ROUND_UP).floatValue();
    }
 
    // Private --------------------------------------------------------------------------------------
 
-   private void promptDelivery()
+   public void promptDelivery()
    {
       // largeMessageDeliverer is always set inside a lock
       // if we don't acquire a lock, we will have NPE eventually
@@ -938,7 +978,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
     */
    private void deliverStandardMessage(final MessageReference ref, final ServerMessage message)
    {
-      int packetSize = callback.sendMessage(message, id, ref.getDeliveryCount());
+      int packetSize = callback.sendMessage(message, ServerConsumerImpl.this, ref.getDeliveryCount());
 
       if (availableCredits != null)
       {
@@ -1040,7 +1080,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
                sentInitialPacket = true;
 
                int packetSize = callback.sendLargeMessage(largeMessage,
-                                                          id,
+                                                          ServerConsumerImpl.this,
                                                           context.getLargeBodySize(),
                                                           ref.getDeliveryCount());
 
@@ -1088,7 +1128,7 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
 
                byte[] body = bodyBuffer.toByteBuffer().array();
 
-               int packetSize = callback.sendLargeMessageContinuation(id,
+               int packetSize = callback.sendLargeMessageContinuation(ServerConsumerImpl.this,
                                                                       body,
                                                                       positionPendingLargeMessage + localChunkLen < sizePendingLargeMessage,
                                                                       false);
@@ -1166,16 +1206,16 @@ public class ServerConsumerImpl implements ServerConsumer, ReadyListener
       }
    }
 
-   private class BrowserDeliverer implements Runnable
+   protected class BrowserDeliverer implements Runnable
    {
-      private MessageReference current = null;
+      protected MessageReference current = null;
 
       public BrowserDeliverer(final LinkedListIterator<MessageReference> iterator)
       {
          this.iterator = iterator;
       }
 
-      private final LinkedListIterator<MessageReference> iterator;
+      public final LinkedListIterator<MessageReference> iterator;
 
       public synchronized void close()
       {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerMessageImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerMessageImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerMessageImpl.java
index 54899ad..e780957 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerMessageImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerMessageImpl.java
@@ -102,9 +102,10 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage
       return true;
    }
 
-   public void setMessageID(final long id)
+   public ServerMessageImpl setMessageID(final long id)
    {
       messageID = id;
+      return this;
    }
 
    public MessageReference createReference(final Queue queue)
@@ -247,30 +248,27 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage
    @Override
    public void setOriginalHeaders(final ServerMessage other, final MessageReference originalReference, final boolean expiry)
    {
+      SimpleString originalQueue = other.getSimpleStringProperty(Message.HDR_ORIGINAL_QUEUE);
+
+      if (originalQueue != null)
+      {
+         putStringProperty(Message.HDR_ORIGINAL_QUEUE, originalQueue);
+      }
+      else if (originalReference != null)
+      {
+         putStringProperty(Message.HDR_ORIGINAL_QUEUE, originalReference.getQueue().getName());
+      }
+
       if (other.containsProperty(Message.HDR_ORIG_MESSAGE_ID))
       {
          putStringProperty(Message.HDR_ORIGINAL_ADDRESS, other.getSimpleStringProperty(Message.HDR_ORIGINAL_ADDRESS));
 
-         SimpleString originalQueue = other.getSimpleStringProperty(Message.HDR_ORIGINAL_QUEUE);
-
-         if (originalQueue != null)
-         {
-            putStringProperty(Message.HDR_ORIGINAL_QUEUE, originalQueue);
-         }
-
          putLongProperty(Message.HDR_ORIG_MESSAGE_ID, other.getLongProperty(Message.HDR_ORIG_MESSAGE_ID));
       }
       else
       {
          putStringProperty(Message.HDR_ORIGINAL_ADDRESS, other.getAddress());
 
-         /**
-          * This could be null in some DLA cases since the message wasn't routed yet
-          */
-         if (originalReference != null)
-         {
-            putStringProperty(Message.HDR_ORIGINAL_QUEUE, originalReference.getQueue().getName());
-         }
 
          putLongProperty(Message.HDR_ORIG_MESSAGE_ID, other.getMessageID());
       }
@@ -328,9 +326,6 @@ public class ServerMessageImpl extends MessageImpl implements ServerMessage
          ", durable=" + durable + ", address=" + getAddress() + ",properties=" + properties.toString() + "]@" + System.identityHashCode(this);
    }
 
-   // FIXME - this is stuff that is only used in large messages
-
-   // This is only valid on the client side - why is it here?
    public InputStream getBodyInputStream()
    {
       return null;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerSessionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerSessionImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerSessionImpl.java
index fb9a637..1083dfb 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerSessionImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServerSessionImpl.java
@@ -26,6 +26,7 @@ package org.hornetq.core.server.impl;
 
 import javax.transaction.xa.XAException;
 import javax.transaction.xa.Xid;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -42,6 +43,7 @@ import org.hornetq.api.core.HornetQNonExistentQueueException;
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
 import org.hornetq.core.client.impl.ClientMessageImpl;
 import org.hornetq.core.exception.HornetQXAException;
@@ -78,6 +80,7 @@ import org.hornetq.core.server.management.Notification;
 import org.hornetq.core.transaction.ResourceManager;
 import org.hornetq.core.transaction.Transaction;
 import org.hornetq.core.transaction.Transaction.State;
+import org.hornetq.core.transaction.TransactionFactory;
 import org.hornetq.core.transaction.TransactionOperationAbstract;
 import org.hornetq.core.transaction.TransactionPropertyIndexes;
 import org.hornetq.core.transaction.impl.TransactionImpl;
@@ -88,8 +91,6 @@ import org.hornetq.utils.UUID;
 import org.hornetq.utils.json.JSONArray;
 import org.hornetq.utils.json.JSONObject;
 
-import static org.hornetq.api.core.management.NotificationType.CONSUMER_CREATED;
-
 /**
  * Server side Session implementation
  *
@@ -108,29 +109,29 @@ public class ServerSessionImpl implements ServerSession, FailureListener
 
    // Attributes ----------------------------------------------------------------------------
 
-   private final String username;
+   protected final String username;
 
-   private final String password;
+   protected final String password;
 
    private final int minLargeMessageSize;
 
-   private final boolean autoCommitSends;
+   protected boolean autoCommitSends;
 
-   private final boolean autoCommitAcks;
+   protected boolean autoCommitAcks;
 
-   private final boolean preAcknowledge;
+   protected final boolean preAcknowledge;
 
-   private final boolean strictUpdateDeliveryCount;
+   protected final boolean strictUpdateDeliveryCount;
 
-   private final RemotingConnection remotingConnection;
+   protected final RemotingConnection remotingConnection;
 
-   private final Map<Long, ServerConsumer> consumers = new ConcurrentHashMap<Long, ServerConsumer>();
+   protected final Map<Long, ServerConsumer> consumers = new ConcurrentHashMap<Long, ServerConsumer>();
 
-   private Transaction tx;
+   protected Transaction tx;
 
-   private final boolean xa;
+   protected boolean xa;
 
-   private final StorageManager storageManager;
+   protected final StorageManager storageManager;
 
    private final ResourceManager resourceManager;
 
@@ -138,24 +139,24 @@ public class ServerSessionImpl implements ServerSession, FailureListener
 
    private final SecurityStore securityStore;
 
-   private final ManagementService managementService;
+   protected final ManagementService managementService;
 
-   private volatile boolean started = false;
+   protected volatile boolean started = false;
 
-   private final Map<SimpleString, TempQueueCleanerUpper> tempQueueCleannerUppers = new HashMap<SimpleString, TempQueueCleanerUpper>();
+   protected final Map<SimpleString, TempQueueCleanerUpper> tempQueueCleannerUppers = new HashMap<SimpleString, TempQueueCleanerUpper>();
 
-   private final String name;
+   protected final String name;
 
-   private final HornetQServer server;
+   protected final HornetQServer server;
 
    private final SimpleString managementAddress;
 
    // The current currentLargeMessage being processed
    private volatile LargeServerMessage currentLargeMessage;
 
-   private final RoutingContext routingContext = new RoutingContextImpl(null);
+   protected final RoutingContext routingContext = new RoutingContextImpl(null);
 
-   private final SessionCallback callback;
+   protected final SessionCallback callback;
 
    private volatile SimpleString defaultAddress;
 
@@ -166,7 +167,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
    private final OperationContext context;
 
    // Session's usage should be by definition single threaded, hence it's not needed to use a concurrentHashMap here
-   private final Map<SimpleString, Pair<UUID, AtomicLong>> targetAddressInfos = new HashMap<SimpleString, Pair<UUID, AtomicLong>>();
+   protected final Map<SimpleString, Pair<UUID, AtomicLong>> targetAddressInfos = new HashMap<SimpleString, Pair<UUID, AtomicLong>>();
 
    private final long creationTime = System.currentTimeMillis();
 
@@ -178,8 +179,34 @@ public class ServerSessionImpl implements ServerSession, FailureListener
    // concurrently.
    private volatile boolean closed = false;
 
+   private final TransactionFactory transactionFactory;
+
    // Constructors ---------------------------------------------------------------------------------
 
+   //create an 'empty' session. Only used by AMQServerSession
+   //in order to check username and password
+   protected ServerSessionImpl(String username, String password)
+   {
+      this.username = username;
+      this.password = password;
+
+      this.transactionFactory = null;
+      this.strictUpdateDeliveryCount = false;
+      this.storageManager = null;
+      this.server = null;
+      this.securityStore = null;
+      this.resourceManager = null;
+      this.remotingConnection = null;
+      this.preAcknowledge = false;
+      this.postOffice = null;
+      this.name = null;
+      this.minLargeMessageSize = 0;
+      this.managementService = null;
+      this.managementAddress = null;
+      this.context = null;
+      this.callback = null;
+   }
+
    public ServerSessionImpl(final String name,
                             final String username,
                             final String password,
@@ -201,6 +228,36 @@ public class ServerSessionImpl implements ServerSession, FailureListener
                             final SessionCallback callback,
                             final OperationContext context) throws Exception
    {
+      this(name, username, password, minLargeMessageSize,
+         autoCommitSends, autoCommitAcks, preAcknowledge,
+         strictUpdateDeliveryCount, xa, remotingConnection,
+         storageManager, postOffice, resourceManager, securityStore,
+         managementService, server, managementAddress, defaultAddress,
+         callback, context, null);
+   }
+
+   public ServerSessionImpl(final String name,
+                            final String username,
+                            final String password,
+                            final int minLargeMessageSize,
+                            final boolean autoCommitSends,
+                            final boolean autoCommitAcks,
+                            final boolean preAcknowledge,
+                            final boolean strictUpdateDeliveryCount,
+                            final boolean xa,
+                            final RemotingConnection remotingConnection,
+                            final StorageManager storageManager,
+                            final PostOffice postOffice,
+                            final ResourceManager resourceManager,
+                            final SecurityStore securityStore,
+                            final ManagementService managementService,
+                            final HornetQServer server,
+                            final SimpleString managementAddress,
+                            final SimpleString defaultAddress,
+                            final SessionCallback callback,
+                            final OperationContext context,
+                            TransactionFactory transactionFactory) throws Exception
+   {
       this.username = username;
 
       this.password = password;
@@ -242,6 +299,16 @@ public class ServerSessionImpl implements ServerSession, FailureListener
 
       remotingConnection.addFailureListener(this);
       this.context = context;
+
+      if (transactionFactory == null)
+      {
+         this.transactionFactory = new DefaultTransactionFactory();
+      }
+      else
+      {
+         this.transactionFactory = transactionFactory;
+      }
+
       if (!xa)
       {
          tx = newTransaction();
@@ -289,15 +356,12 @@ public class ServerSessionImpl implements ServerSession, FailureListener
       return Collections.unmodifiableSet(consumersClone);
    }
 
-   public void removeConsumer(final long consumerID) throws Exception
+   public boolean removeConsumer(final long consumerID) throws Exception
    {
-      if (consumers.remove(consumerID) == null)
-      {
-         throw new IllegalStateException("Cannot find consumer with id " + consumerID + " to remove");
-      }
+      return consumers.remove(consumerID) != null;
    }
 
-   private void doClose(final boolean failed) throws Exception
+   protected void doClose(final boolean failed) throws Exception
    {
       synchronized (this)
       {
@@ -316,14 +380,6 @@ public class ServerSessionImpl implements ServerSession, FailureListener
                HornetQServerLogger.LOGGER.warn(e.getMessage(), e);
             }
          }
-
-         server.removeSession(name);
-
-         remotingConnection.removeFailureListener(this);
-
-         callback.closed();
-
-         closed = true;
       }
 
       //putting closing of consumers outside the sync block
@@ -332,7 +388,22 @@ public class ServerSessionImpl implements ServerSession, FailureListener
 
       for (ServerConsumer consumer : consumersClone)
       {
-         consumer.close(failed);
+         try
+         {
+            consumer.close(failed);
+         }
+         catch (Throwable e)
+         {
+            HornetQServerLogger.LOGGER.warn(e.getMessage(), e);
+            try
+            {
+               consumer.removeItself();
+            }
+            catch (Throwable e2)
+            {
+               HornetQServerLogger.LOGGER.warn(e2.getMessage(), e2);
+            }
+         }
       }
 
       consumers.clear();
@@ -348,22 +419,34 @@ public class ServerSessionImpl implements ServerSession, FailureListener
             HornetQServerLogger.LOGGER.errorDeletingLargeMessageFile(error);
          }
       }
+
+
+      synchronized (this)
+      {
+         server.removeSession(name);
+
+         remotingConnection.removeFailureListener(this);
+
+         callback.closed();
+
+         closed = true;
+      }
    }
 
-   public void createConsumer(final long consumerID,
-                              final SimpleString queueName,
-                              final SimpleString filterString,
-                              final boolean browseOnly) throws Exception
+   public ServerConsumer createConsumer(final long consumerID,
+                                        final SimpleString queueName,
+                                        final SimpleString filterString,
+                                        final boolean browseOnly) throws Exception
    {
-      this.createConsumer(consumerID, queueName, filterString, browseOnly, true, null);
+      return this.createConsumer(consumerID, queueName, filterString, browseOnly, true, null);
    }
 
-   public void createConsumer(final long consumerID,
-                              final SimpleString queueName,
-                              final SimpleString filterString,
-                              final boolean browseOnly,
-                              final boolean supportLargeMessage,
-                              final Integer credits) throws Exception
+   public ServerConsumer createConsumer(final long consumerID,
+                                        final SimpleString queueName,
+                                        final SimpleString filterString,
+                                        final boolean browseOnly,
+                                        final boolean supportLargeMessage,
+                                        final Integer credits) throws Exception
    {
       Binding binding = postOffice.getBinding(queueName);
 
@@ -376,7 +459,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
 
       Filter filter = FilterImpl.createFilter(filterString);
 
-      ServerConsumer consumer = new ServerConsumerImpl(consumerID,
+      ServerConsumer consumer = newConsumer(consumerID,
                                                        this,
                                                        (QueueBinding) binding,
                                                        filter,
@@ -419,7 +502,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
             props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filterString);
          }
 
-         Notification notification = new Notification(null, CONSUMER_CREATED, props);
+         Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CREATED, props);
 
          if (HornetQServerLogger.LOGGER.isDebugEnabled())
          {
@@ -431,6 +514,31 @@ public class ServerSessionImpl implements ServerSession, FailureListener
 
          managementService.sendNotification(notification);
       }
+
+      return consumer;
+   }
+
+   protected ServerConsumer newConsumer(long consumerID,
+         ServerSessionImpl serverSessionImpl, QueueBinding binding,
+         Filter filter, boolean started2, boolean browseOnly,
+         StorageManager storageManager2, SessionCallback callback2,
+         boolean preAcknowledge2, boolean strictUpdateDeliveryCount2,
+         ManagementService managementService2, boolean supportLargeMessage,
+         Integer credits) throws Exception
+   {
+      return new ServerConsumerImpl(consumerID,
+            this,
+            (QueueBinding) binding,
+            filter,
+            started,
+            browseOnly,
+            storageManager,
+            callback,
+            preAcknowledge,
+            strictUpdateDeliveryCount,
+            managementService,
+            supportLargeMessage,
+            credits);
    }
 
    public void createQueue(final SimpleString address,
@@ -492,13 +600,13 @@ public class ServerSessionImpl implements ServerSession, FailureListener
       return remotingConnection;
    }
 
-   private static class TempQueueCleanerUpper implements CloseListener, FailureListener
+   public static class TempQueueCleanerUpper implements CloseListener, FailureListener
    {
       private final SimpleString bindingName;
 
       private final HornetQServer server;
 
-      TempQueueCleanerUpper(final HornetQServer server, final SimpleString bindingName)
+      public TempQueueCleanerUpper(final HornetQServer server, final SimpleString bindingName)
       {
          this.server = server;
 
@@ -599,7 +707,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
                                          queue.isTemporary(),
                                          filterString,
                                          queue.getConsumerCount(),
-                                         queue.getMessageCount(QueueImpl.DELIVERY_TIMEOUT));
+                                         queue.getMessageCount());
       }
       // make an exception for the management address (see HORNETQ-29)
       else if (name.equals(managementAddress))
@@ -668,12 +776,12 @@ public class ServerSessionImpl implements ServerSession, FailureListener
          // have these messages to be stuck on the limbo until the server is restarted
          // The tx has already timed out, so we need to ack and rollback immediately
          Transaction newTX = newTransaction();
-         consumer.acknowledge(autoCommitAcks, newTX, messageID);
+         consumer.acknowledge(newTX, messageID);
          newTX.rollback();
       }
       else
       {
-         consumer.acknowledge(autoCommitAcks, tx, messageID);
+         consumer.acknowledge(autoCommitAcks ? null : tx, messageID);
       }
    }
 
@@ -681,23 +789,18 @@ public class ServerSessionImpl implements ServerSession, FailureListener
    {
       ServerConsumer consumer = consumers.get(consumerID);
 
-      if (this.xa && tx == null)
-      {
-         throw new HornetQXAException(XAException.XAER_PROTO, "Invalid transaction state");
-      }
-
       if (tx != null && tx.getState() == State.ROLLEDBACK)
       {
          // JBPAPP-8845 - if we let stuff to be acked on a rolled back TX, we will just
          // have these messages to be stuck on the limbo until the server is restarted
          // The tx has already timed out, so we need to ack and rollback immediately
          Transaction newTX = newTransaction();
-         consumer.individualAcknowledge(autoCommitAcks, tx, messageID);
+         consumer.individualAcknowledge(tx, messageID);
          newTX.rollback();
       }
       else
       {
-         consumer.individualAcknowledge(autoCommitAcks, tx, messageID);
+         consumer.individualAcknowledge(autoCommitAcks ? null : tx, messageID);
       }
 
    }
@@ -732,11 +835,21 @@ public class ServerSessionImpl implements ServerSession, FailureListener
       }
       try
       {
-         tx.commit();
+         if (tx != null)
+         {
+            tx.commit();
+         }
       }
       finally
       {
-         tx = newTransaction();
+         if (xa)
+         {
+            tx = null;
+         }
+         else
+         {
+            tx = newTransaction();
+         }
       }
    }
 
@@ -774,18 +887,18 @@ public class ServerSessionImpl implements ServerSession, FailureListener
    /**
     * @return
     */
-   private TransactionImpl newTransaction()
+   protected Transaction newTransaction()
    {
-      return new TransactionImpl(storageManager, timeoutSeconds);
+      return transactionFactory.newTransaction(null, storageManager, timeoutSeconds);
    }
 
    /**
     * @param xid
     * @return
     */
-   private TransactionImpl newTransaction(final Xid xid)
+   private Transaction newTransaction(final Xid xid)
    {
-      return new TransactionImpl(xid, storageManager, timeoutSeconds);
+      return transactionFactory.newTransaction(xid, storageManager, timeoutSeconds);
    }
 
    public synchronized void xaCommit(final Xid xid, final boolean onePhase) throws Exception
@@ -1306,13 +1419,17 @@ public class ServerSessionImpl implements ServerSession, FailureListener
    @Override
    public Transaction getCurrentTransaction()
    {
+      if (tx == null)
+      {
+         tx = newTransaction();
+      }
       return tx;
    }
 
    public void sendLarge(final MessageInternal message) throws Exception
    {
       // need to create the LargeMessage before continue
-      long id = storageManager.generateUniqueID();
+      long id = storageManager.generateID();
 
       LargeServerMessage largeMsg = storageManager.createLargeMessage(id, message);
 
@@ -1335,7 +1452,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
       //case the id header already generated.
       if (!message.isLargeMessage())
       {
-         long id = storageManager.generateUniqueID();
+         long id = storageManager.generateID();
 
          message.setMessageID(id);
          message.encodeMessageIDToBuffer();
@@ -1658,6 +1775,21 @@ public class ServerSessionImpl implements ServerSession, FailureListener
          toCancel.addAll(consumer.cancelRefs(clientFailed, lastMessageAsDelived, theTx));
       }
 
+      //we need to check this before we cancel the refs and add them to the tx, any delivering refs will have been delivered
+      //after the last tx was rolled back so we should handle them separately. if not they
+      //will end up added to the tx but never ever handled even tho they were removed from the consumers delivering refs.
+      //we add them to a new tx and roll them back as the calling client will assume that this has happened.
+      if (theTx.getState() == State.ROLLEDBACK)
+      {
+         Transaction newTX = newTransaction();
+         cancelAndRollback(clientFailed, newTX, wasStarted, toCancel);
+         throw new IllegalStateException("Transaction has already been rolled back");
+      }
+      cancelAndRollback(clientFailed, theTx, wasStarted, toCancel);
+   }
+
+   private void cancelAndRollback(boolean clientFailed, Transaction theTx, boolean wasStarted, List<MessageReference> toCancel) throws Exception
+   {
       for (MessageReference ref : toCancel)
       {
          ref.getQueue().cancel(theTx, ref);
@@ -1683,7 +1815,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
       theTx.rollback();
    }
 
-   private void doSend(final ServerMessage msg, final boolean direct) throws Exception
+   protected void doSend(final ServerMessage msg, final boolean direct) throws Exception
    {
       // check the user has write access to this address.
       try
@@ -1692,7 +1824,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
       }
       catch (HornetQException e)
       {
-         if (!autoCommitSends)
+         if (!autoCommitSends && tx != null)
          {
             tx.markAsRollbackOnly(e);
          }
@@ -1735,7 +1867,7 @@ public class ServerSessionImpl implements ServerSession, FailureListener
    {
       if (this.tx != null)
       {
-         QueueImpl.RefsOperation oper = (QueueImpl.RefsOperation) tx.getProperty(TransactionPropertyIndexes.REFS_OPERATION);
+         RefsOperation oper = (RefsOperation) tx.getProperty(TransactionPropertyIndexes.REFS_OPERATION);
 
          if (oper == null)
          {
@@ -1752,4 +1884,12 @@ public class ServerSessionImpl implements ServerSession, FailureListener
       }
    }
 
+   private static class DefaultTransactionFactory implements TransactionFactory
+   {
+      @Override
+      public Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds)
+      {
+         return new TransactionImpl(xid, storageManager, timeoutSeconds);
+      }
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServiceRegistry.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServiceRegistry.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServiceRegistry.java
new file mode 100644
index 0000000..0e0e809
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ServiceRegistry.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.server.impl;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
+
+import org.hornetq.api.core.Interceptor;
+import org.hornetq.api.core.Pair;
+import org.hornetq.core.config.ConnectorServiceConfiguration;
+import org.hornetq.core.server.ConnectorServiceFactory;
+
+/**
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
+ */
+
+public class ServiceRegistry
+{
+   private ExecutorService executorService;
+
+   private ScheduledExecutorService scheduledExecutorService;
+
+   /* We are using a List rather than HashMap here as HornetQ allows multiple instances of the same class to be added
+   * to the interceptor list
+   */
+   private Map<String, Interceptor> incomingInterceptors;
+
+   private Map<String, Interceptor> outgoingInterceptors;
+
+   private Map<String, Pair<ConnectorServiceFactory, ConnectorServiceConfiguration>> connectorServices;
+
+   public ServiceRegistry()
+   {
+      this.incomingInterceptors = new ConcurrentHashMap<String, Interceptor>();
+      this.outgoingInterceptors = new ConcurrentHashMap<String, Interceptor>();
+      this.connectorServices = new ConcurrentHashMap<String, Pair<ConnectorServiceFactory, ConnectorServiceConfiguration>>();
+   }
+
+   public ExecutorService getExecutorService()
+   {
+      return executorService;
+   }
+
+   public void setExecutorService(ExecutorService executorService)
+   {
+      this.executorService = executorService;
+   }
+
+   public ScheduledExecutorService getScheduledExecutorService()
+   {
+      return scheduledExecutorService;
+   }
+
+   public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService)
+   {
+      this.scheduledExecutorService = scheduledExecutorService;
+   }
+
+   public void addConnectorService(ConnectorServiceFactory connectorServiceFactory, ConnectorServiceConfiguration configuration)
+   {
+      connectorServices.put(configuration.getConnectorName(), new Pair<>(connectorServiceFactory, configuration));
+   }
+
+   public void removeConnectorService(ConnectorServiceConfiguration configuration)
+   {
+      connectorServices.remove(configuration.getConnectorName());
+   }
+
+   public Collection<Pair<ConnectorServiceFactory, ConnectorServiceConfiguration>> getConnectorServices()
+   {
+      return connectorServices.values();
+   }
+
+   public void addIncomingInterceptor(String name, Interceptor interceptor)
+   {
+      incomingInterceptors.put(name, interceptor);
+   }
+
+   public void removeIncomingInterceptor(String name)
+   {
+      incomingInterceptors.remove(name);
+   }
+
+   public Collection<Interceptor> getIncomingInterceptors()
+   {
+      return Collections.unmodifiableCollection(incomingInterceptors.values());
+   }
+
+   public Interceptor getIncomingInterceptor(String name)
+   {
+      return incomingInterceptors.get(name);
+   }
+
+   public void addOutgoingInterceptor(String name, Interceptor interceptor)
+   {
+      outgoingInterceptors.put(name, interceptor);
+   }
+
+   public Interceptor getOutgoingInterceptor(String name)
+   {
+      return outgoingInterceptors.get(name);
+   }
+
+   public void removeOutgoingInterceptor(String name)
+   {
+      outgoingInterceptors.remove(name);
+   }
+
+   public Collection<Interceptor> getOutgoingInterceptors()
+   {
+      return Collections.unmodifiableCollection(outgoingInterceptors.values());
+   }
+}


[26/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ConfigurationUtils.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ConfigurationUtils.java b/hornetq-server/src/main/java/org/hornetq/core/config/ConfigurationUtils.java
index 72a132b..fe0c284 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/ConfigurationUtils.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ConfigurationUtils.java
@@ -13,6 +13,23 @@
 package org.hornetq.core.config;
 
 import org.hornetq.api.core.HornetQIllegalStateException;
+import org.hornetq.core.config.ha.ColocatedPolicyConfiguration;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
+import org.hornetq.core.server.HornetQMessageBundle;
+import org.hornetq.core.server.cluster.ha.BackupPolicy;
+import org.hornetq.core.server.cluster.ha.ColocatedPolicy;
+import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.server.cluster.ha.LiveOnlyPolicy;
+import org.hornetq.core.server.cluster.ha.ReplicaPolicy;
+import org.hornetq.core.server.cluster.ha.ReplicatedPolicy;
+import org.hornetq.core.server.cluster.ha.ScaleDownPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreMasterPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreSlavePolicy;
+
 public final class ConfigurationUtils
 {
 
@@ -21,9 +38,8 @@ public final class ConfigurationUtils
       // Utility class
    }
 
-   public static ClusterConnectionConfiguration getReplicationClusterConfiguration(Configuration conf) throws HornetQIllegalStateException
+   public static ClusterConnectionConfiguration getReplicationClusterConfiguration(Configuration conf, String replicationCluster) throws HornetQIllegalStateException
    {
-      final String replicationCluster = conf.getHAPolicy().getReplicationClustername();
       if (replicationCluster == null || replicationCluster.isEmpty())
          return conf.getClusterConfigurations().get(0);
       for (ClusterConnectionConfiguration clusterConf : conf.getClusterConfigurations())
@@ -33,4 +49,94 @@ public final class ConfigurationUtils
       }
       throw new HornetQIllegalStateException("Missing cluster-configuration for replication-clustername '" + replicationCluster + "'.");
    }
+
+   public static HAPolicy getHAPolicy(HAPolicyConfiguration conf) throws HornetQIllegalStateException
+   {
+      if (conf == null)
+      {
+         return new LiveOnlyPolicy();
+      }
+
+      switch (conf.getType())
+      {
+         case LIVE_ONLY:
+         {
+            LiveOnlyPolicyConfiguration pc = (LiveOnlyPolicyConfiguration) conf;
+            return new LiveOnlyPolicy(getScaleDownPolicy(pc.getScaleDownConfiguration()));
+         }
+         case REPLICATED:
+         {
+            ReplicatedPolicyConfiguration pc = (ReplicatedPolicyConfiguration) conf;
+            return new ReplicatedPolicy(pc.isCheckForLiveServer(), pc.getGroupName(), pc.getClusterName());
+         }
+         case REPLICA:
+         {
+            ReplicaPolicyConfiguration pc = (ReplicaPolicyConfiguration) conf;
+            return new ReplicaPolicy(pc.getClusterName(), pc.getMaxSavedReplicatedJournalsSize(), pc.getGroupName(), pc.isRestartBackup(), pc.isAllowFailBack(), pc.getFailbackDelay(), getScaleDownPolicy(pc.getScaleDownConfiguration()));
+         }
+         case SHARED_STORE_MASTER:
+         {
+            SharedStoreMasterPolicyConfiguration pc = (SharedStoreMasterPolicyConfiguration) conf;
+            return new SharedStoreMasterPolicy(pc.getFailbackDelay(), pc.isFailoverOnServerShutdown());
+         }
+         case SHARED_STORE_SLAVE:
+         {
+            SharedStoreSlavePolicyConfiguration pc = (SharedStoreSlavePolicyConfiguration) conf;
+            return new SharedStoreSlavePolicy(pc.getFailbackDelay(), pc.isFailoverOnServerShutdown(), pc.isRestartBackup(), pc.isAllowFailBack(), getScaleDownPolicy(pc.getScaleDownConfiguration()));
+         }
+         case COLOCATED:
+         {
+            ColocatedPolicyConfiguration pc = (ColocatedPolicyConfiguration) conf;
+
+            HAPolicyConfiguration backupConf = pc.getBackupConfig();
+            BackupPolicy backupPolicy;
+            if (backupConf == null)
+            {
+               backupPolicy = new ReplicaPolicy();
+            }
+            else
+            {
+               backupPolicy = (BackupPolicy) getHAPolicy(backupConf);
+            }
+            HAPolicyConfiguration liveConf = pc.getLiveConfig();
+            HAPolicy livePolicy;
+            if (liveConf == null)
+            {
+               livePolicy = new ReplicatedPolicy();
+            }
+            else
+            {
+               livePolicy = getHAPolicy(liveConf);
+            }
+            return new ColocatedPolicy(pc.isRequestBackup(),
+                  pc.getBackupRequestRetries(),
+                  pc.getBackupRequestRetryInterval(),
+                  pc.getMaxBackups(),
+                  pc.getBackupPortOffset(),
+                  pc.getExcludedConnectors(),
+                  livePolicy,
+                  backupPolicy);
+         }
+
+      }
+      throw HornetQMessageBundle.BUNDLE.unsupportedHAPolicyConfiguration(conf);
+   }
+
+   public static ScaleDownPolicy getScaleDownPolicy(ScaleDownConfiguration scaleDownConfiguration)
+   {
+      if (scaleDownConfiguration != null)
+      {
+         if (scaleDownConfiguration.getDiscoveryGroup() != null)
+         {
+            return new ScaleDownPolicy(scaleDownConfiguration.getDiscoveryGroup(), scaleDownConfiguration.getGroupName(),
+                  scaleDownConfiguration.getClusterName(), scaleDownConfiguration.isEnabled());
+         }
+         else
+         {
+            return new ScaleDownPolicy(scaleDownConfiguration.getConnectors(), scaleDownConfiguration.getGroupName(),
+                  scaleDownConfiguration.getClusterName(), scaleDownConfiguration.isEnabled());
+         }
+      }
+      return null;
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ConnectorServiceConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ConnectorServiceConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ConnectorServiceConfiguration.java
index 26ec18c..3121c1f 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/ConnectorServiceConfiguration.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ConnectorServiceConfiguration.java
@@ -23,17 +23,14 @@ public class ConnectorServiceConfiguration implements Serializable
 {
    private static final long serialVersionUID = -641207073030767325L;
 
-   private final String name;
+   private String name;
 
-   private final  String factoryClassName;
+   private String factoryClassName;
 
-   private final  Map<String, Object> params;
+   private Map<String, Object> params;
 
-   public ConnectorServiceConfiguration(final String clazz, final Map<String, Object> params, final String name)
+   public ConnectorServiceConfiguration()
    {
-      this.name = name;
-      factoryClassName = clazz;
-      this.params = params;
    }
 
    public String getConnectorName()
@@ -51,6 +48,29 @@ public class ConnectorServiceConfiguration implements Serializable
       return params;
    }
 
+   public String getName()
+   {
+      return name;
+   }
+
+   public ConnectorServiceConfiguration setName(String name)
+   {
+      this.name = name;
+      return this;
+   }
+
+   public ConnectorServiceConfiguration setFactoryClassName(String factoryClassName)
+   {
+      this.factoryClassName = factoryClassName;
+      return this;
+   }
+
+   public ConnectorServiceConfiguration setParams(Map<String, Object> params)
+   {
+      this.params = params;
+      return this;
+   }
+
    @Override
    public boolean equals(Object o)
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/CoreQueueConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/CoreQueueConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/CoreQueueConfiguration.java
index 51422a3..7ba64ef 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/CoreQueueConfiguration.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/CoreQueueConfiguration.java
@@ -22,20 +22,16 @@ public class CoreQueueConfiguration implements Serializable
 {
    private static final long serialVersionUID = 650404974977490254L;
 
-   private String address;
+   private String address = null;
 
-   private String name;
+   private String name = null;
 
-   private String filterString;
+   private String filterString = null;
 
-   private boolean durable;
+   private boolean durable = true;
 
-   public CoreQueueConfiguration(final String address, final String name, final String filterString, final boolean durable)
+   public CoreQueueConfiguration()
    {
-      this.address = address;
-      this.name = name;
-      this.filterString = filterString;
-      this.durable = durable;
    }
 
    public String getAddress()
@@ -61,33 +57,37 @@ public class CoreQueueConfiguration implements Serializable
    /**
     * @param address the address to set
     */
-   public void setAddress(final String address)
+   public CoreQueueConfiguration setAddress(final String address)
    {
       this.address = address;
+      return this;
    }
 
    /**
     * @param name the name to set
     */
-   public void setName(final String name)
+   public CoreQueueConfiguration setName(final String name)
    {
       this.name = name;
+      return this;
    }
 
    /**
     * @param filterString the filterString to set
     */
-   public void setFilterString(final String filterString)
+   public CoreQueueConfiguration setFilterString(final String filterString)
    {
       this.filterString = filterString;
+      return this;
    }
 
    /**
-    * @param durable the durable to set
+    * @param durable the durable to set; default value is true
     */
-   public void setDurable(final boolean durable)
+   public CoreQueueConfiguration setDurable(final boolean durable)
    {
       this.durable = durable;
+      return this;
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/DivertConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/DivertConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/DivertConfiguration.java
index 1dab186..45b1179 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/DivertConfiguration.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/DivertConfiguration.java
@@ -14,6 +14,7 @@ package org.hornetq.core.config;
 
 import java.io.Serializable;
 
+import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.utils.UUIDGenerator;
 
 /**
@@ -25,42 +26,22 @@ public class DivertConfiguration implements Serializable
 {
    private static final long serialVersionUID = 6910543740464269629L;
 
-   private String name;
+   private String name = null;
 
-   private String routingName;
+   private String routingName = UUIDGenerator.getInstance().generateStringUUID();
 
-   private String address;
+   private String address = null;
 
-   private String forwardingAddress;
+   private String forwardingAddress = null;
 
-   private boolean exclusive;
+   private boolean exclusive = HornetQDefaultConfiguration.isDefaultDivertExclusive();
 
-   private String filterString;
+   private String filterString = null;
 
-   private String transformerClassName;
+   private String transformerClassName = null;
 
-   public DivertConfiguration(final String name,
-                              final String routingName,
-                              final String address,
-                              final String forwardingAddress,
-                              final boolean exclusive,
-                              final String filterString,
-                              final String transformerClassName)
+   public DivertConfiguration()
    {
-      this.name = name;
-      if (routingName == null)
-      {
-         this.routingName = UUIDGenerator.getInstance().generateStringUUID();
-      }
-      else
-      {
-         this.routingName = routingName;
-      }
-      this.address = address;
-      this.forwardingAddress = forwardingAddress;
-      this.exclusive = exclusive;
-      this.filterString = filterString;
-      this.transformerClassName = transformerClassName;
    }
 
    public String getName()
@@ -101,57 +82,64 @@ public class DivertConfiguration implements Serializable
    /**
     * @param name the name to set
     */
-   public void setName(final String name)
+   public DivertConfiguration setName(final String name)
    {
       this.name = name;
+      return this;
    }
 
    /**
     * @param routingName the routingName to set
     */
-   public void setRoutingName(final String routingName)
+   public DivertConfiguration setRoutingName(final String routingName)
    {
       this.routingName = routingName;
+      return this;
    }
 
    /**
     * @param address the address to set
     */
-   public void setAddress(final String address)
+   public DivertConfiguration setAddress(final String address)
    {
       this.address = address;
+      return this;
    }
 
    /**
     * @param forwardingAddress the forwardingAddress to set
     */
-   public void setForwardingAddress(final String forwardingAddress)
+   public DivertConfiguration setForwardingAddress(final String forwardingAddress)
    {
       this.forwardingAddress = forwardingAddress;
+      return this;
    }
 
    /**
     * @param exclusive the exclusive to set
     */
-   public void setExclusive(final boolean exclusive)
+   public DivertConfiguration setExclusive(final boolean exclusive)
    {
       this.exclusive = exclusive;
+      return this;
    }
 
    /**
     * @param filterString the filterString to set
     */
-   public void setFilterString(final String filterString)
+   public DivertConfiguration setFilterString(final String filterString)
    {
       this.filterString = filterString;
+      return this;
    }
 
    /**
     * @param transformerClassName the transformerClassName to set
     */
-   public void setTransformerClassName(final String transformerClassName)
+   public DivertConfiguration setTransformerClassName(final String transformerClassName)
    {
       this.transformerClassName = transformerClassName;
+      return this;
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/HAPolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/HAPolicyConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/HAPolicyConfiguration.java
new file mode 100644
index 0000000..c1d68ca
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/HAPolicyConfiguration.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config;
+
+import java.io.Serializable;
+
+public interface HAPolicyConfiguration extends Serializable
+{
+   public enum TYPE
+   {
+      LIVE_ONLY,
+      REPLICATED,
+      REPLICA,
+      SHARED_STORE_MASTER,
+      SHARED_STORE_SLAVE,
+      COLOCATED
+   }
+
+   TYPE getType();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ScaleDownConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ScaleDownConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ScaleDownConfiguration.java
new file mode 100644
index 0000000..9a685aa
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ScaleDownConfiguration.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ScaleDownConfiguration implements Serializable
+{
+   private List<String> connectors = new ArrayList<>();
+
+   private String discoveryGroup = null;
+
+   private String groupName = null;
+
+   private String clusterName = null;
+
+   private boolean enabled = HornetQDefaultConfiguration.isDefaultScaleDownEnabled();
+
+   public List<String> getConnectors()
+   {
+      return connectors;
+   }
+
+   public ScaleDownConfiguration setConnectors(List<String> connectors)
+   {
+      this.connectors = connectors;
+      return this;
+   }
+
+   public ScaleDownConfiguration addConnector(String connector)
+   {
+      connectors.add(connector);
+      return this;
+   }
+
+   public String getDiscoveryGroup()
+   {
+      return discoveryGroup;
+   }
+
+   public ScaleDownConfiguration setDiscoveryGroup(String discoveryGroup)
+   {
+      this.discoveryGroup = discoveryGroup;
+      return this;
+   }
+
+   public String getGroupName()
+   {
+      return groupName;
+   }
+
+   public ScaleDownConfiguration setGroupName(String groupName)
+   {
+      this.groupName = groupName;
+      return this;
+   }
+
+   public String getClusterName()
+   {
+      return clusterName;
+   }
+
+   public ScaleDownConfiguration setClusterName(String clusterName)
+   {
+      this.clusterName = clusterName;
+      return this;
+   }
+
+   public boolean isEnabled()
+   {
+      return enabled;
+   }
+
+   public ScaleDownConfiguration setEnabled(boolean enabled)
+   {
+      this.enabled = enabled;
+      return this;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ha/ColocatedPolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ha/ColocatedPolicyConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ha/ColocatedPolicyConfiguration.java
new file mode 100644
index 0000000..f5c930b
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ha/ColocatedPolicyConfiguration.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ColocatedPolicyConfiguration implements HAPolicyConfiguration
+{
+   private boolean requestBackup = HornetQDefaultConfiguration.isDefaultHapolicyRequestBackup();
+
+   private int backupRequestRetries = HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetries();
+
+   private long backupRequestRetryInterval = HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetryInterval();
+
+   private int maxBackups = HornetQDefaultConfiguration.getDefaultHapolicyMaxBackups();
+
+   private int backupPortOffset = HornetQDefaultConfiguration.getDefaultHapolicyBackupPortOffset();
+
+   private List<String> excludedConnectors = new ArrayList<>();
+
+   private int portOffset = HornetQDefaultConfiguration.getDefaultHapolicyBackupPortOffset();
+
+   private HAPolicyConfiguration liveConfig;
+
+   private HAPolicyConfiguration backupConfig;
+
+   public ColocatedPolicyConfiguration()
+   {
+   }
+
+   @Override
+   public TYPE getType()
+   {
+      return TYPE.COLOCATED;
+   }
+
+   public boolean isRequestBackup()
+   {
+      return requestBackup;
+   }
+
+   public ColocatedPolicyConfiguration setRequestBackup(boolean requestBackup)
+   {
+      this.requestBackup = requestBackup;
+      return this;
+   }
+
+   public int getBackupRequestRetries()
+   {
+      return backupRequestRetries;
+   }
+
+   public ColocatedPolicyConfiguration setBackupRequestRetries(int backupRequestRetries)
+   {
+      this.backupRequestRetries = backupRequestRetries;
+      return this;
+   }
+
+   public long getBackupRequestRetryInterval()
+   {
+      return backupRequestRetryInterval;
+   }
+
+   public ColocatedPolicyConfiguration setBackupRequestRetryInterval(long backupRequestRetryInterval)
+   {
+      this.backupRequestRetryInterval = backupRequestRetryInterval;
+      return this;
+   }
+
+   public int getMaxBackups()
+   {
+      return maxBackups;
+   }
+
+   public ColocatedPolicyConfiguration setMaxBackups(int maxBackups)
+   {
+      this.maxBackups = maxBackups;
+      return this;
+   }
+
+   public int getBackupPortOffset()
+   {
+      return backupPortOffset;
+   }
+
+   public ColocatedPolicyConfiguration setBackupPortOffset(int backupPortOffset)
+   {
+      this.backupPortOffset = backupPortOffset;
+      return this;
+   }
+
+   public List<String> getExcludedConnectors()
+   {
+      return excludedConnectors;
+   }
+
+   public ColocatedPolicyConfiguration setExcludedConnectors(List<String> excludedConnectors)
+   {
+      this.excludedConnectors = excludedConnectors;
+      return this;
+   }
+
+   public int getPortOffset()
+   {
+      return portOffset;
+   }
+
+   public ColocatedPolicyConfiguration setPortOffset(int portOffset)
+   {
+      this.portOffset = portOffset;
+      return this;
+   }
+
+   public HAPolicyConfiguration getLiveConfig()
+   {
+      return liveConfig;
+   }
+
+   public ColocatedPolicyConfiguration setLiveConfig(HAPolicyConfiguration liveConfig)
+   {
+      this.liveConfig = liveConfig;
+      return this;
+   }
+
+   public HAPolicyConfiguration getBackupConfig()
+   {
+      return backupConfig;
+   }
+
+   public ColocatedPolicyConfiguration setBackupConfig(HAPolicyConfiguration backupConfig)
+   {
+      this.backupConfig = backupConfig;
+      return this;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ha/LiveOnlyPolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ha/LiveOnlyPolicyConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ha/LiveOnlyPolicyConfiguration.java
new file mode 100644
index 0000000..622af31
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ha/LiveOnlyPolicyConfiguration.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config.ha;
+
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ScaleDownConfiguration;
+
+public class LiveOnlyPolicyConfiguration implements HAPolicyConfiguration
+{
+   public LiveOnlyPolicyConfiguration()
+   {
+   }
+
+   public LiveOnlyPolicyConfiguration(ScaleDownConfiguration scaleDownConfiguration)
+   {
+      this.scaleDownConfiguration = scaleDownConfiguration;
+   }
+
+   @Override
+   public TYPE getType()
+   {
+      return TYPE.LIVE_ONLY;
+   }
+
+   public ScaleDownConfiguration getScaleDownConfiguration()
+   {
+      return scaleDownConfiguration;
+   }
+
+   public void setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration)
+   {
+      this.scaleDownConfiguration = scaleDownConfiguration;
+   }
+
+   ScaleDownConfiguration scaleDownConfiguration;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicaPolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicaPolicyConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicaPolicyConfiguration.java
new file mode 100644
index 0000000..fa3eaf9
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicaPolicyConfiguration.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ScaleDownConfiguration;
+
+public class ReplicaPolicyConfiguration implements HAPolicyConfiguration
+{
+   private String clusterName = null;
+
+   private int maxSavedReplicatedJournalsSize = HornetQDefaultConfiguration.getDefaultMaxSavedReplicatedJournalsSize();
+
+   private String groupName = null;
+
+   private boolean restartBackup = HornetQDefaultConfiguration.isDefaultRestartBackup();
+
+   private ScaleDownConfiguration scaleDownConfiguration;
+
+   /*
+   * used in the replicated policy after failover
+   * */
+   private boolean allowFailBack = false;
+
+   private long failbackDelay = HornetQDefaultConfiguration.getDefaultFailbackDelay();
+
+   public ReplicaPolicyConfiguration()
+   {
+   }
+
+   @Override
+   public TYPE getType()
+   {
+      return TYPE.REPLICA;
+   }
+
+   public ScaleDownConfiguration getScaleDownConfiguration()
+   {
+      return scaleDownConfiguration;
+   }
+
+   public ReplicaPolicyConfiguration setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration)
+   {
+      this.scaleDownConfiguration = scaleDownConfiguration;
+      return this;
+   }
+
+   public String getClusterName()
+   {
+      return clusterName;
+   }
+
+   public ReplicaPolicyConfiguration setClusterName(String clusterName)
+   {
+      this.clusterName = clusterName;
+      return this;
+   }
+
+   public int getMaxSavedReplicatedJournalsSize()
+   {
+      return maxSavedReplicatedJournalsSize;
+   }
+
+   public ReplicaPolicyConfiguration setMaxSavedReplicatedJournalsSize(int maxSavedReplicatedJournalsSize)
+   {
+      this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize;
+      return this;
+   }
+
+   public String getGroupName()
+   {
+      return groupName;
+   }
+
+   public ReplicaPolicyConfiguration setGroupName(String groupName)
+   {
+      this.groupName = groupName;
+      return this;
+   }
+
+   public boolean isRestartBackup()
+   {
+      return restartBackup;
+   }
+
+   public ReplicaPolicyConfiguration setRestartBackup(boolean restartBackup)
+   {
+      this.restartBackup = restartBackup;
+      return this;
+   }
+
+   public boolean isAllowFailBack()
+   {
+      return allowFailBack;
+   }
+
+   public ReplicaPolicyConfiguration setAllowFailBack(boolean allowFailBack)
+   {
+      this.allowFailBack = allowFailBack;
+      return this;
+   }
+
+   public ReplicaPolicyConfiguration setFailbackDelay(long failbackDelay)
+   {
+      this.failbackDelay = failbackDelay;
+      return this;
+   }
+
+   public long getFailbackDelay()
+   {
+      return failbackDelay;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicatedPolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicatedPolicyConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicatedPolicyConfiguration.java
new file mode 100644
index 0000000..5a1e2ec
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ha/ReplicatedPolicyConfiguration.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+
+public class ReplicatedPolicyConfiguration implements HAPolicyConfiguration
+{
+   private boolean checkForLiveServer = HornetQDefaultConfiguration.isDefaultCheckForLiveServer();
+
+   private String groupName = null;
+
+   private String clusterName = null;
+
+   public ReplicatedPolicyConfiguration()
+   {
+   }
+
+   @Override
+   public TYPE getType()
+   {
+      return TYPE.REPLICATED;
+   }
+
+   public boolean isCheckForLiveServer()
+   {
+      return checkForLiveServer;
+   }
+
+   public ReplicatedPolicyConfiguration setCheckForLiveServer(boolean checkForLiveServer)
+   {
+      this.checkForLiveServer = checkForLiveServer;
+      return this;
+   }
+
+   public String getGroupName()
+   {
+      return groupName;
+   }
+
+   public ReplicatedPolicyConfiguration setGroupName(String groupName)
+   {
+      this.groupName = groupName;
+      return this;
+   }
+
+   public String getClusterName()
+   {
+      return clusterName;
+   }
+
+   public ReplicatedPolicyConfiguration setClusterName(String clusterName)
+   {
+      this.clusterName = clusterName;
+      return this;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreMasterPolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreMasterPolicyConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreMasterPolicyConfiguration.java
new file mode 100644
index 0000000..60de542
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreMasterPolicyConfiguration.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+
+public class SharedStoreMasterPolicyConfiguration implements HAPolicyConfiguration
+{
+   private long failbackDelay = HornetQDefaultConfiguration.getDefaultFailbackDelay();
+
+   private boolean failoverOnServerShutdown = HornetQDefaultConfiguration.isDefaultFailoverOnServerShutdown();
+
+   public SharedStoreMasterPolicyConfiguration()
+   {
+   }
+
+   @Override
+   public TYPE getType()
+   {
+      return TYPE.SHARED_STORE_MASTER;
+   }
+
+   public long getFailbackDelay()
+   {
+      return failbackDelay;
+   }
+
+   public SharedStoreMasterPolicyConfiguration setFailbackDelay(long failbackDelay)
+   {
+      this.failbackDelay = failbackDelay;
+      return this;
+   }
+
+   public boolean isFailoverOnServerShutdown()
+   {
+      return failoverOnServerShutdown;
+   }
+
+   public SharedStoreMasterPolicyConfiguration setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
+   {
+      this.failoverOnServerShutdown = failoverOnServerShutdown;
+      return this;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreSlavePolicyConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreSlavePolicyConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreSlavePolicyConfiguration.java
new file mode 100644
index 0000000..a0c8da1
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ha/SharedStoreSlavePolicyConfiguration.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ScaleDownConfiguration;
+
+public class SharedStoreSlavePolicyConfiguration implements HAPolicyConfiguration
+{
+   private long failbackDelay = HornetQDefaultConfiguration.getDefaultFailbackDelay();
+
+   private boolean failoverOnServerShutdown = HornetQDefaultConfiguration.isDefaultFailoverOnServerShutdown();
+
+   private boolean restartBackup = HornetQDefaultConfiguration.isDefaultRestartBackup();
+
+   private boolean allowFailBack = HornetQDefaultConfiguration.isDefaultAllowAutoFailback();
+
+   private ScaleDownConfiguration scaleDownConfiguration;
+
+   public SharedStoreSlavePolicyConfiguration()
+   {
+   }
+
+   @Override
+   public TYPE getType()
+   {
+      return TYPE.SHARED_STORE_SLAVE;
+   }
+
+   public boolean isRestartBackup()
+   {
+      return restartBackup;
+   }
+
+   public SharedStoreSlavePolicyConfiguration setRestartBackup(boolean restartBackup)
+   {
+      this.restartBackup = restartBackup;
+      return this;
+   }
+
+   public ScaleDownConfiguration getScaleDownConfiguration()
+   {
+      return scaleDownConfiguration;
+   }
+
+   public SharedStoreSlavePolicyConfiguration setScaleDownConfiguration(ScaleDownConfiguration scaleDownConfiguration)
+   {
+      this.scaleDownConfiguration = scaleDownConfiguration;
+      return this;
+   }
+
+   public boolean isAllowFailBack()
+   {
+      return allowFailBack;
+   }
+
+   public SharedStoreSlavePolicyConfiguration setAllowFailBack(boolean allowFailBack)
+   {
+      this.allowFailBack = allowFailBack;
+      return this;
+   }
+
+   public boolean isFailoverOnServerShutdown()
+   {
+      return failoverOnServerShutdown;
+   }
+
+   public SharedStoreSlavePolicyConfiguration setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
+   {
+      this.failoverOnServerShutdown = failoverOnServerShutdown;
+      return this;
+   }
+
+   public long getFailbackDelay()
+   {
+      return failbackDelay;
+   }
+
+   public SharedStoreSlavePolicyConfiguration setFailbackDelay(long failbackDelay)
+   {
+      this.failbackDelay = failbackDelay;
+      return this;
+   }
+
+}


[28/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java
new file mode 100644
index 0000000..0c20c0f
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalServer.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.proton.plug.test.minimalserver;
+
+
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.List;
+
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.ChannelPipeline;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.ServerChannel;
+import io.netty.channel.group.ChannelGroup;
+import io.netty.channel.group.ChannelGroupFuture;
+import io.netty.channel.group.DefaultChannelGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.ByteToMessageDecoder;
+import io.netty.util.ResourceLeakDetector;
+import io.netty.util.concurrent.GlobalEventExecutor;
+
+import org.proton.plug.AMQPServerConnectionContext;
+import org.proton.plug.context.server.ProtonServerConnectionContextFactory;
+import org.proton.plug.test.Constants;
+
+/**
+ * A Netty TCP Acceptor that supports SSL
+ *
+ * @author <a href="ataylor@redhat.com">Andy Taylor</a>
+ * @author <a href="tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="tlee@redhat.com">Trustin Lee</a>
+ * @author <a href="jmesnil@redhat.com">Jeff Mesnil</a>
+ * @author <a href="nmaurer@redhat.com">Norman Maurer</a>
+ * @version $Rev$, $Date$
+ */
+public class MinimalServer
+{
+
+   static
+   {
+      // Disable resource leak detection for performance reasons by default
+      ResourceLeakDetector.setEnabled(false);
+   }
+
+   private Class<? extends ServerChannel> channelClazz;
+
+   private EventLoopGroup eventLoopGroup;
+
+   private volatile ChannelGroup serverChannelGroup;
+
+   private volatile ChannelGroup channelGroup;
+
+   private ServerBootstrap bootstrap;
+
+   private String host;
+
+   private boolean sasl;
+
+   // Constants.PORT is the default here
+   private int port;
+
+   public synchronized void start(String host, int port, final boolean sasl) throws Exception
+   {
+      this.host = host;
+      this.port = port;
+      this.sasl = sasl;
+
+      if (channelClazz != null)
+      {
+         // Already started
+         return;
+      }
+
+      int threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
+      channelClazz = NioServerSocketChannel.class;
+      eventLoopGroup = new NioEventLoopGroup(threadsToUse, new SimpleServerThreadFactory("simple-server", true, Thread.currentThread().getContextClassLoader()));
+
+      bootstrap = new ServerBootstrap();
+      bootstrap.group(eventLoopGroup);
+      bootstrap.channel(channelClazz);
+
+
+      ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>()
+      {
+         @Override
+         public void initChannel(Channel channel) throws Exception
+         {
+            ChannelPipeline pipeline = channel.pipeline();
+            pipeline.addLast("amqp-handler", new ProtocolDecoder());
+         }
+      };
+      bootstrap.childHandler(factory);
+
+      bootstrap.option(ChannelOption.SO_REUSEADDR, true).
+         childOption(ChannelOption.SO_REUSEADDR, true).
+         childOption(ChannelOption.SO_KEEPALIVE, true).
+//       childOption(ChannelOption.AUTO_READ, false).
+         childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
+
+      channelGroup = new DefaultChannelGroup("hornetq-accepted-channels", GlobalEventExecutor.INSTANCE);
+
+      serverChannelGroup = new DefaultChannelGroup("hornetq-acceptor-channels", GlobalEventExecutor.INSTANCE);
+
+
+      SocketAddress address;
+      address = new InetSocketAddress(host, port);
+      Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel();
+      serverChannelGroup.add(serverChannel);
+
+   }
+
+   class ProtocolDecoder extends ByteToMessageDecoder
+   {
+
+      AMQPServerConnectionContext connection;
+
+
+      public ProtocolDecoder()
+      {
+      }
+
+      @Override
+      public void channelActive(ChannelHandlerContext ctx) throws Exception
+      {
+         super.channelActive(ctx);
+         connection = ProtonServerConnectionContextFactory.getFactory().createConnection(new MinimalConnectionSPI(ctx.channel()));
+         //ctx.read();
+      }
+
+      @Override
+      protected void decode(final ChannelHandlerContext ctx, ByteBuf byteIn, List<Object> out) throws Exception
+      {
+         connection.inputBuffer(byteIn);
+         ctx.flush();
+//         if (connection.capacity() > 0)
+//         {
+//            ctx.read();
+//         }
+      }
+   }
+
+   public synchronized void stop()
+   {
+      serverChannelGroup.close().awaitUninterruptibly();
+      ChannelGroupFuture future = channelGroup.close().awaitUninterruptibly();
+   }
+
+
+   public static void main(String[] arg)
+   {
+      MinimalServer server = new MinimalServer();
+      try
+      {
+         server.start("127.0.0.1", Constants.PORT, true);
+
+
+         while (true)
+         {
+            Thread.sleep(360000000);
+         }
+      }
+      catch (Throwable e)
+      {
+         e.printStackTrace();
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java
new file mode 100644
index 0000000..30a58bc
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalSessionSPI.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.minimalserver;
+
+import java.util.concurrent.BlockingDeque;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.qpid.proton.amqp.Binary;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.AMQPSessionContext;
+import org.proton.plug.context.ProtonPlugSender;
+import org.proton.plug.context.server.ProtonServerSessionContext;
+import org.proton.plug.SASLResult;
+import org.proton.plug.util.ProtonServerMessage;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class MinimalSessionSPI implements AMQPSessionCallback
+{
+
+   private SASLResult result;
+   ProtonServerSessionContext session;
+
+   @Override
+   public void init(AMQPSessionContext session, SASLResult result)
+   {
+      this.session = (ProtonServerSessionContext) session;
+      this.result = result;
+   }
+
+   @Override
+   public void start()
+   {
+   }
+
+   static AtomicInteger tempQueueGenerator = new AtomicInteger(0);
+
+   public String tempQueueName()
+   {
+      return "TempQueueName" + tempQueueGenerator.incrementAndGet();
+   }
+
+   @Override
+   public Object createSender(ProtonPlugSender plugSender, String queue, String filer, boolean browserOnly)
+   {
+      Consumer consumer = new Consumer(DumbServer.getQueue(queue));
+      return consumer;
+   }
+
+   @Override
+   public void startSender(Object brokerConsumer)
+   {
+      ((Consumer) brokerConsumer).start();
+   }
+
+   @Override
+   public void createTemporaryQueue(String queueName)
+   {
+
+   }
+
+   @Override
+   public void onFlowConsumer(Object consumer, int credits)
+   {
+   }
+
+   @Override
+   public boolean queueQuery(String queueName)
+   {
+      return true;
+   }
+
+   @Override
+   public void closeSender(Object brokerConsumer)
+   {
+      ((Consumer) brokerConsumer).close();
+   }
+
+   @Override
+   public ProtonJMessage encodeMessage(Object message, int deliveryCount)
+   {
+      // We are storing internally as EncodedMessage on this minimalserver server
+      return (ProtonServerMessage) message;
+   }
+
+   @Override
+   public Binary getCurrentTXID()
+   {
+      return new Binary(new byte[]{1});
+   }
+
+   @Override
+   public void commitCurrentTX()
+   {
+   }
+
+   @Override
+   public void rollbackCurrentTX()
+   {
+   }
+
+   @Override
+   public void close()
+   {
+
+   }
+
+   @Override
+   public void ack(Object brokerConsumer, Object message)
+   {
+
+   }
+
+   @Override
+   public void cancel(Object brokerConsumer, Object message, boolean updateCounts)
+   {
+
+   }
+
+   @Override
+   public void resumeDelivery(Object consumer)
+   {
+      System.out.println("Resume delivery!!!");
+      ((Consumer) consumer).start();
+   }
+
+   @Override
+   public void serverSend(Receiver receiver, Delivery delivery, String address, int messageFormat, ByteBuf buffer)
+   {
+      ProtonServerMessage serverMessage = new ProtonServerMessage();
+      serverMessage.decode(buffer.nioBuffer());
+
+      BlockingDeque<Object> queue = DumbServer.getQueue(address);
+      queue.add(serverMessage);
+   }
+
+
+   class Consumer
+   {
+      final BlockingDeque<Object> queue;
+
+      Consumer(BlockingDeque<Object> queue)
+      {
+         this.queue = queue;
+      }
+
+      boolean running = false;
+      volatile Thread thread;
+
+      public void close()
+      {
+         System.out.println("Closing!!!");
+         running = false;
+         if (thread != null)
+         {
+            try
+            {
+               thread.join();
+            }
+            catch (Throwable ignored)
+            {
+            }
+         }
+
+         thread = null;
+      }
+
+      public synchronized void start()
+      {
+         running = true;
+         if (thread == null)
+         {
+            System.out.println("Start!!!");
+            thread = new Thread()
+            {
+               public void run()
+               {
+                  try
+                  {
+                     while (running)
+                     {
+                        Object msg = queue.poll(1, TimeUnit.SECONDS);
+
+                        if (msg != null)
+                        {
+                           session.serverDelivery(msg, Consumer.this, 1);
+                        }
+                     }
+                  }
+                  catch (Exception e)
+                  {
+                     e.printStackTrace();
+                  }
+               }
+            };
+            thread.start();
+         }
+      }
+
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java
new file mode 100644
index 0000000..d33c235
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/SimpleServerThreadFactory.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.proton.plug.test.minimalserver;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * A HornetQThreadFactory
+ *
+ * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ */
+public final class SimpleServerThreadFactory implements ThreadFactory
+{
+   private final ThreadGroup group;
+
+   private final AtomicInteger threadCount = new AtomicInteger(0);
+
+   private final int threadPriority;
+
+   private final boolean daemon;
+
+   private final ClassLoader tccl;
+
+   public SimpleServerThreadFactory(final String groupName, final boolean daemon, final ClassLoader tccl)
+   {
+      group = new ThreadGroup(groupName + "-" + System.identityHashCode(this));
+
+      this.threadPriority = Thread.NORM_PRIORITY;
+
+      this.tccl = tccl;
+
+      this.daemon = daemon;
+   }
+
+   public Thread newThread(final Runnable command)
+   {
+      final Thread t;
+      // attach the thread to a group only if there is no security manager:
+      // when sandboxed, the code does not have the RuntimePermission modifyThreadGroup
+      if (System.getSecurityManager() == null)
+      {
+         t = new Thread(group, command, "Thread-" + threadCount.getAndIncrement() + " (" + group.getName() + ")");
+      }
+      else
+      {
+         t = new Thread(command, "Thread-" + threadCount.getAndIncrement());
+      }
+
+      AccessController.doPrivileged(new PrivilegedAction<Object>()
+      {
+         public Object run()
+         {
+            t.setDaemon(daemon);
+            t.setPriority(threadPriority);
+            return null;
+         }
+      });
+
+      try
+      {
+         AccessController.doPrivileged(new PrivilegedAction<Object>()
+         {
+            public Object run()
+            {
+               t.setContextClassLoader(tccl);
+               return null;
+            }
+         });
+      }
+      catch (java.security.AccessControlException e)
+      {
+         e.printStackTrace();
+      }
+
+      return t;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java
new file mode 100644
index 0000000..be615c4
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/sasl/PlainSASLTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.sasl;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.proton.plug.sasl.ClientSASLPlain;
+import org.proton.plug.sasl.PlainSASLResult;
+import org.proton.plug.sasl.ServerSASLPlain;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class PlainSASLTest
+{
+   @Test
+   public void testPlain()
+   {
+      ClientSASLPlain plainSASL = new ClientSASLPlain("user-me", "password-secret");
+      byte[] bytesResult = plainSASL.getBytes();
+
+      ServerSASLPlain serverSASLPlain = new ServerSASLPlain();
+      PlainSASLResult result = (PlainSASLResult) serverSASLPlain.processSASL(bytesResult);
+      Assert.assertEquals("user-me", result.getUser());
+      Assert.assertEquals("password-secret", result.getPassword());
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java
new file mode 100644
index 0000000..e1f0744
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/CreditsSemaphoreTest.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.util;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.proton.plug.util.CreditsSemaphore;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class CreditsSemaphoreTest
+{
+   final CreditsSemaphore semaphore = new CreditsSemaphore(10);
+
+   final AtomicInteger errors = new AtomicInteger(0);
+
+   final AtomicInteger acquired = new AtomicInteger(0);
+
+   final CountDownLatch waiting = new CountDownLatch(1);
+
+   Thread thread = new Thread()
+   {
+      public void run()
+      {
+         try
+         {
+            for (int i = 0; i < 12; i++)
+            {
+               if (!semaphore.tryAcquire())
+               {
+                  waiting.countDown();
+                  semaphore.acquire();
+               }
+               acquired.incrementAndGet();
+            }
+         }
+         catch (Throwable e)
+         {
+            e.printStackTrace();
+            errors.incrementAndGet();
+         }
+      }
+   };
+
+
+   @Test
+   public void testSetAndRelease() throws Exception
+   {
+      thread.start();
+
+      // 5 seconds would be an eternity here
+      Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS));
+
+      Assert.assertEquals(0, semaphore.getCredits());
+
+      long timeout = System.currentTimeMillis() + 1000;
+      while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout)
+      {
+         Thread.sleep(10);
+      }
+
+      Assert.assertTrue(semaphore.hasQueuedThreads());
+
+      semaphore.setCredits(2);
+
+      thread.join();
+
+      Assert.assertEquals(12, acquired.get());
+
+      Assert.assertFalse(semaphore.hasQueuedThreads());
+   }
+
+   @Test
+   public void testDownAndUp() throws Exception
+   {
+      thread.start();
+
+      // 5 seconds would be an eternity here
+      Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS));
+
+      Assert.assertEquals(0, semaphore.getCredits());
+
+      long timeout = System.currentTimeMillis() + 1000;
+      while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout)
+      {
+         Thread.sleep(10);
+      }
+
+      Assert.assertTrue(semaphore.hasQueuedThreads());
+
+      semaphore.release(2);
+
+      thread.join();
+
+      Assert.assertEquals(12, acquired.get());
+
+      Assert.assertFalse(semaphore.hasQueuedThreads());
+   }
+
+
+   @Test
+   public void testStartedZeroedSetLater() throws Exception
+   {
+      semaphore.setCredits(0);
+
+      thread.start();
+
+      // 5 seconds would be an eternity here
+      Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS));
+
+      Assert.assertEquals(0, semaphore.getCredits());
+
+      long timeout = System.currentTimeMillis() + 1000;
+      while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout)
+      {
+         Thread.sleep(10);
+      }
+
+      Assert.assertTrue(semaphore.hasQueuedThreads());
+
+      Assert.assertEquals(0, acquired.get());
+
+      semaphore.setCredits(12);
+
+      thread.join();
+
+      Assert.assertEquals(12, acquired.get());
+
+      Assert.assertFalse(semaphore.hasQueuedThreads());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java
new file mode 100644
index 0000000..5d44c88
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/ReusableLatchTest.java
@@ -0,0 +1,335 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.util;
+
+import java.util.concurrent.CountDownLatch;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.proton.plug.util.ReusableLatch;
+
+/**
+ * @author <a href="mailto:clebert.suconic@jboss.com">Clebert Suconic</a>
+ */
+public class ReusableLatchTest
+{
+   @Test
+   public void testLatchWithParameterizedDown() throws Exception
+   {
+      ReusableLatch latch = new ReusableLatch(1000);
+
+      latch.countDown(5000);
+
+      Assert.assertTrue(latch.await(1000));
+
+
+      Assert.assertEquals(0, latch.getCount());
+   }
+
+   @Test
+   public void testLatchOnSingleThread() throws Exception
+   {
+      ReusableLatch latch = new ReusableLatch();
+
+      for (int i = 1; i <= 100; i++)
+      {
+         latch.countUp();
+         Assert.assertEquals(i, latch.getCount());
+      }
+
+      for (int i = 100; i > 0; i--)
+      {
+         Assert.assertEquals(i, latch.getCount());
+         latch.countDown();
+         Assert.assertEquals(i - 1, latch.getCount());
+      }
+
+      latch.await();
+   }
+
+   /**
+    * This test will open numberOfThreads threads, and add numberOfAdds on the
+    * VariableLatch After those addthreads are finished, the latch count should
+    * be numberOfThreads * numberOfAdds Then it will open numberOfThreads
+    * threads again releasing numberOfAdds on the VariableLatch After those
+    * releaseThreads are finished, the latch count should be 0 And all the
+    * waiting threads should be finished also
+    *
+    * @throws Exception
+    */
+   @Test
+   public void testLatchOnMultiThread() throws Exception
+   {
+      final ReusableLatch latch = new ReusableLatch();
+
+      latch.countUp(); // We hold at least one, so ThreadWaits won't go away
+
+      final int numberOfThreads = 100;
+      final int numberOfAdds = 100;
+
+      class ThreadWait extends Thread
+      {
+         private volatile boolean waiting = true;
+
+         @Override
+         public void run()
+         {
+            try
+            {
+               if (!latch.await(5000))
+               {
+                  System.err.println("Latch timed out");
+               }
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+            }
+            waiting = false;
+         }
+      }
+
+      class ThreadAdd extends Thread
+      {
+         private final CountDownLatch latchReady;
+
+         private final CountDownLatch latchStart;
+
+         ThreadAdd(final CountDownLatch latchReady, final CountDownLatch latchStart)
+         {
+            this.latchReady = latchReady;
+            this.latchStart = latchStart;
+         }
+
+         @Override
+         public void run()
+         {
+            try
+            {
+               latchReady.countDown();
+               // Everybody should start at the same time, to worse concurrency
+               // effects
+               latchStart.await();
+               for (int i = 0; i < numberOfAdds; i++)
+               {
+                  latch.countUp();
+               }
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+            }
+         }
+      }
+
+      CountDownLatch latchReady = new CountDownLatch(numberOfThreads);
+      CountDownLatch latchStart = new CountDownLatch(1);
+
+      ThreadAdd[] threadAdds = new ThreadAdd[numberOfThreads];
+      ThreadWait[] waits = new ThreadWait[numberOfThreads];
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         threadAdds[i] = new ThreadAdd(latchReady, latchStart);
+         threadAdds[i].start();
+         waits[i] = new ThreadWait();
+         waits[i].start();
+      }
+
+      latchReady.await();
+      latchStart.countDown();
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         threadAdds[i].join();
+      }
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         Assert.assertTrue(waits[i].waiting);
+      }
+
+      Assert.assertEquals(numberOfThreads * numberOfAdds + 1, latch.getCount());
+
+      class ThreadDown extends Thread
+      {
+         private final CountDownLatch latchReady;
+
+         private final CountDownLatch latchStart;
+
+         ThreadDown(final CountDownLatch latchReady, final CountDownLatch latchStart)
+         {
+            this.latchReady = latchReady;
+            this.latchStart = latchStart;
+         }
+
+         @Override
+         public void run()
+         {
+            try
+            {
+               latchReady.countDown();
+               // Everybody should start at the same time, to worse concurrency
+               // effects
+               latchStart.await();
+               for (int i = 0; i < numberOfAdds; i++)
+               {
+                  latch.countDown();
+               }
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+            }
+         }
+      }
+
+      latchReady = new CountDownLatch(numberOfThreads);
+      latchStart = new CountDownLatch(1);
+
+      ThreadDown[] down = new ThreadDown[numberOfThreads];
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         down[i] = new ThreadDown(latchReady, latchStart);
+         down[i].start();
+      }
+
+      latchReady.await();
+      latchStart.countDown();
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         down[i].join();
+      }
+
+      Assert.assertEquals(1, latch.getCount());
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         Assert.assertTrue(waits[i].waiting);
+      }
+
+      latch.countDown();
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         waits[i].join();
+      }
+
+      Assert.assertEquals(0, latch.getCount());
+
+      for (int i = 0; i < numberOfThreads; i++)
+      {
+         Assert.assertFalse(waits[i].waiting);
+      }
+   }
+
+   @Test
+   public void testReuseLatch() throws Exception
+   {
+      final ReusableLatch latch = new ReusableLatch(5);
+      for (int i = 0; i < 5; i++)
+      {
+         latch.countDown();
+      }
+
+      latch.countUp();
+
+      class ThreadWait extends Thread
+      {
+         private volatile boolean waiting = false;
+
+         private volatile Exception e;
+
+         private final CountDownLatch readyLatch = new CountDownLatch(1);
+
+         @Override
+         public void run()
+         {
+            waiting = true;
+            readyLatch.countDown();
+            try
+            {
+               if (!latch.await(1000))
+               {
+                  System.err.println("Latch timed out!");
+               }
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+               this.e = e;
+            }
+            waiting = false;
+         }
+      }
+
+      ThreadWait t = new ThreadWait();
+      t.start();
+
+      t.readyLatch.await();
+
+      Assert.assertEquals(true, t.waiting);
+
+      latch.countDown();
+
+      t.join();
+
+      Assert.assertEquals(false, t.waiting);
+
+      Assert.assertNull(t.e);
+
+      latch.countUp();
+
+      t = new ThreadWait();
+      t.start();
+
+      t.readyLatch.await();
+
+      Assert.assertEquals(true, t.waiting);
+
+      latch.countDown();
+
+      t.join();
+
+      Assert.assertEquals(false, t.waiting);
+
+      Assert.assertNull(t.e);
+
+      Assert.assertTrue(latch.await(1000));
+
+      Assert.assertEquals(0, latch.getCount());
+
+      latch.countDown();
+
+      Assert.assertEquals(0, latch.getCount());
+
+   }
+
+   @Test
+   public void testTimeout() throws Exception
+   {
+      ReusableLatch latch = new ReusableLatch();
+
+      latch.countUp();
+
+      long start = System.currentTimeMillis();
+      Assert.assertFalse(latch.await(1000));
+      long end = System.currentTimeMillis();
+
+      Assert.assertTrue("Timeout didn't work correctly", end - start >= 1000 && end - start < 2000);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java
new file mode 100644
index 0000000..5832b1e
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/util/SimpleServerAbstractTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.util;
+
+import org.proton.plug.test.AbstractJMSTest;
+import org.proton.plug.test.Constants;
+import org.proton.plug.test.invm.InVMTestConnector;
+import org.proton.plug.test.minimalclient.Connector;
+import org.proton.plug.test.minimalclient.SimpleAMQPConnector;
+import org.proton.plug.test.minimalserver.DumbServer;
+import org.proton.plug.test.minimalserver.MinimalServer;
+import org.junit.After;
+import org.junit.Before;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class SimpleServerAbstractTest
+{
+
+   protected final boolean useSASL;
+   protected final boolean useInVM;
+   protected MinimalServer server = new MinimalServer();
+
+   public SimpleServerAbstractTest(boolean useSASL, boolean useInVM)
+   {
+      this.useSASL = useSASL;
+      this.useInVM = useInVM;
+   }
+
+   @Before
+   public void setUp() throws Exception
+   {
+      DumbServer.clear();
+      AbstractJMSTest.forceGC();
+      if (!useInVM)
+      {
+         server.start("127.0.0.1", Constants.PORT, useSASL);
+      }
+
+
+   }
+
+   @After
+   public void tearDown() throws Exception
+   {
+      if (!useInVM)
+      {
+         server.stop();
+      }
+      DumbServer.clear();
+   }
+
+   protected Connector newConnector()
+   {
+      if (useInVM)
+      {
+         return new InVMTestConnector();
+      }
+      else
+      {
+         return new SimpleAMQPConnector();
+      }
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompDecoder.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompDecoder.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompDecoder.java
index 8321533..d515fa3 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompDecoder.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompDecoder.java
@@ -100,6 +100,8 @@ public class StompDecoder
 
    public static final byte C = (byte) 'C';
 
+   public static final byte c = (byte) 'c';
+
    public static final byte D = (byte) 'D';
 
    public static final byte E = (byte) 'E';

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompFrame.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompFrame.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompFrame.java
index e4d2637..a0d26c1 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompFrame.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompFrame.java
@@ -172,18 +172,18 @@ public class StompFrame
          this.val = val;
       }
 
-      public String getEscapedKey()
+      public String getEncodedKey()
       {
-         return escape(key);
+         return encode(key);
       }
 
-      public String getEscapedValue()
+      public String getEncodedValue()
       {
-         return escape(val);
+         return encode(val);
       }
    }
 
-   public String escape(String str)
+   public String encode(String str)
    {
       int len = str.length();
 
@@ -192,21 +192,35 @@ public class StompFrame
       for (int i = 0; i < len; i++)
       {
          char c = str.charAt(i);
-         if (c == '\n')
+
+         // \n
+         if (c == (byte) 10)
          {
-            buffer[iBuffer++] = '\\';
-            buffer[iBuffer] = 'n';
+            buffer[iBuffer] = (byte) 92;
+            buffer[++iBuffer] = (byte) 110;
          }
-         else if (c == '\\')
+
+         // \r
+         else if (c == (byte) 13)
          {
-            buffer[iBuffer++] = '\\';
-            buffer[iBuffer] = '\\';
+            buffer[iBuffer] = (byte) 92;
+            buffer[++iBuffer] = (byte) 114;
          }
-         else if (c == ':')
+
+         // \
+         else if (c == (byte) 92)
          {
-            buffer[iBuffer++] = '\\';
-            buffer[iBuffer] = ':';
+            buffer[iBuffer] = (byte) 92;
+            buffer[++iBuffer] = (byte) 92;
          }
+
+         // :
+         else if (c == (byte) 58)
+         {
+            buffer[iBuffer] = (byte) 92;
+            buffer[++iBuffer] = (byte) 99;
+         }
+
          else
          {
             buffer[iBuffer] = c;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompProtocolManager.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompProtocolManager.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompProtocolManager.java
index a5e62fe..a8e6f3e 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompProtocolManager.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompProtocolManager.java
@@ -28,8 +28,8 @@ import org.hornetq.api.core.HornetQExceptionType;
 import org.hornetq.api.core.Interceptor;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.journal.IOAsyncTask;
 import org.hornetq.core.postoffice.BindingType;
 import org.hornetq.core.remoting.impl.netty.NettyServerConnection;
@@ -42,6 +42,7 @@ import org.hornetq.core.server.management.ManagementService;
 import org.hornetq.core.server.management.Notification;
 import org.hornetq.core.server.management.NotificationListener;
 import org.hornetq.spi.core.protocol.ConnectionEntry;
+import org.hornetq.spi.core.protocol.MessageConverter;
 import org.hornetq.spi.core.protocol.ProtocolManager;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.spi.core.remoting.Acceptor;
@@ -92,6 +93,12 @@ class StompProtocolManager implements ProtocolManager, NotificationListener
       }
    }
 
+   @Override
+   public MessageConverter getConverter()
+   {
+      return null;
+   }
+
    // ProtocolManager implementation --------------------------------
 
    public ConnectionEntry createConnectionEntry(final Acceptor acceptorUsed, final Connection connection)
@@ -236,7 +243,7 @@ class StompProtocolManager implements ProtocolManager, NotificationListener
                                                       false,
                                                       false,
                                                       null,
-                                                      stompSession);
+                                                      stompSession, null);
          stompSession.setServerSession(session);
          sessions.put(connection.getID(), stompSession);
       }
@@ -261,7 +268,7 @@ class StompProtocolManager implements ProtocolManager, NotificationListener
                                                       false,
                                                       false,
                                                       null,
-                                                      stompSession);
+                                                      stompSession, null);
          stompSession.setServerSession(session);
          transactedSessions.put(txID, stompSession);
       }
@@ -365,7 +372,7 @@ class StompProtocolManager implements ProtocolManager, NotificationListener
 
    public ServerMessageImpl createServerMessage()
    {
-      return new ServerMessageImpl(server.getStorageManager().generateUniqueID(), 512);
+      return new ServerMessageImpl(server.getStorageManager().generateID(), 512);
    }
 
    public void commitTransaction(StompConnection connection, String txID) throws Exception
@@ -402,7 +409,7 @@ class StompProtocolManager implements ProtocolManager, NotificationListener
          throw new HornetQStompException("There already is a subscription for: " + subscriptionID +
                                             ". Either use unique subscription IDs or do not create multiple subscriptions for the same destination");
       }
-      long consumerID = server.getStorageManager().generateUniqueID();
+      long consumerID = server.getStorageManager().generateID();
       String clientID = (connection.getClientID() != null) ? connection.getClientID() : null;
       stompSession.addSubscription(consumerID,
                                    subscriptionID,
@@ -450,7 +457,10 @@ class StompProtocolManager implements ProtocolManager, NotificationListener
    @Override
    public void onNotification(Notification notification)
    {
-      NotificationType type = notification.getType();
+      if (!(notification.getType() instanceof CoreNotificationType)) return;
+
+      CoreNotificationType type = (CoreNotificationType) notification.getType();
+
       TypedProperties props = notification.getProperties();
 
       switch (type)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompSession.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompSession.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompSession.java
index 9109541..afc8b28 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompSession.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/StompSession.java
@@ -30,6 +30,7 @@ import org.hornetq.core.persistence.impl.journal.LargeServerMessageImpl;
 import org.hornetq.core.remoting.impl.netty.TransportConstants;
 import org.hornetq.core.server.LargeServerMessage;
 import org.hornetq.core.server.QueueQueryResult;
+import org.hornetq.core.server.ServerConsumer;
 import org.hornetq.core.server.ServerMessage;
 import org.hornetq.core.server.ServerSession;
 import org.hornetq.core.server.impl.ServerMessageImpl;
@@ -86,6 +87,12 @@ public class StompSession implements SessionCallback
       return session;
    }
 
+   @Override
+   public boolean hasCredits(ServerConsumer consumerID)
+   {
+      return true;
+   }
+
    public void sendProducerCreditsMessage(int credits, SimpleString address)
    {
    }
@@ -94,13 +101,13 @@ public class StompSession implements SessionCallback
    {
    }
 
-   public int sendMessage(ServerMessage serverMessage, long consumerID, int deliveryCount)
+   public int sendMessage(ServerMessage serverMessage, ServerConsumer consumer, int deliveryCount)
    {
       LargeServerMessageImpl largeMessage = null;
       ServerMessage newServerMessage = serverMessage;
       try
       {
-         StompSubscription subscription = subscriptions.get(consumerID);
+         StompSubscription subscription = subscriptions.get(consumer.getID());
          StompFrame frame = null;
          if (serverMessage.isLargeMessage())
          {
@@ -146,13 +153,13 @@ public class StompSession implements SessionCallback
             if (manager.send(connection, frame))
             {
                //we ack and commit only if the send is successful
-               session.acknowledge(consumerID, newServerMessage.getMessageID());
+               session.acknowledge(consumer.getID(), newServerMessage.getMessageID());
                session.commit();
             }
          }
          else
          {
-            messagesToAck.put(newServerMessage.getMessageID(), new Pair<Long, Integer>(consumerID, length));
+            messagesToAck.put(newServerMessage.getMessageID(), new Pair<Long, Integer>(consumer.getID(), length));
             // Must send AFTER adding to messagesToAck - or could get acked from client BEFORE it's been added!
             manager.send(connection, frame);
          }
@@ -174,12 +181,12 @@ public class StompSession implements SessionCallback
 
    }
 
-   public int sendLargeMessageContinuation(long consumerID, byte[] body, boolean continues, boolean requiresResponse)
+   public int sendLargeMessageContinuation(ServerConsumer consumer, byte[] body, boolean continues, boolean requiresResponse)
    {
       return 0;
    }
 
-   public int sendLargeMessage(ServerMessage msg, long consumerID, long bodySize, int deliveryCount)
+   public int sendLargeMessage(ServerMessage msg, ServerConsumer consumer, long bodySize, int deliveryCount)
    {
       return 0;
    }
@@ -199,9 +206,9 @@ public class StompSession implements SessionCallback
    }
 
    @Override
-   public void disconnect(long consumerId, String queueName)
+   public void disconnect(ServerConsumer consumerId, String queueName)
    {
-      StompSubscription stompSubscription = subscriptions.remove(consumerId);
+      StompSubscription stompSubscription = subscriptions.remove(consumerId.getID());
       if (stompSubscription != null)
       {
          StompFrame frame = connection.getFrameHandler().createStompFrame(StompCommands.ERROR.toString());
@@ -380,7 +387,7 @@ public class StompSession implements SessionCallback
       }
 
       StorageManager storageManager = ((ServerSessionImpl) session).getStorageManager();
-      long id = storageManager.generateUniqueID();
+      long id = storageManager.generateID();
       LargeServerMessage largeMessage = storageManager.createLargeMessage(id, message);
 
       byte[] bytes = new byte[message.getBodyBuffer().writerIndex() - MessageImpl.BODY_OFFSET];

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameHandlerV11.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameHandlerV11.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameHandlerV11.java
index 483924d..07b9107 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameHandlerV11.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameHandlerV11.java
@@ -730,24 +730,15 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements
                }
                case HEADER_SEPARATOR:
                {
-                  if (isEscaping)
+                  if (inHeaderName)
                   {
-                     //a colon
-                     holder.append(b);
-                     isEscaping = false;
-                  }
-                  else
-                  {
-                     if (inHeaderName)
-                     {
-                        headerName = holder.getString();
+                     headerName = holder.getString();
 
-                        holder.reset();
+                     holder.reset();
 
-                        inHeaderName = false;
+                     inHeaderName = false;
 
-                        headerValueWhitespace = true;
-                     }
+                     headerValueWhitespace = true;
                   }
 
                   whiteSpaceOnly = false;
@@ -767,6 +758,19 @@ public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements
                   }
                   break;
                }
+               case StompDecoder.c:
+               {
+                  if (isEscaping)
+                  {
+                     holder.append(StompDecoder.HEADER_SEPARATOR);
+                     isEscaping = false;
+                  }
+                  else
+                  {
+                     holder.append(b);
+                  }
+                  break;
+               }
                case StompDecoder.NEW_LINE:
                {
                   if (whiteSpaceOnly)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameV11.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameV11.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameV11.java
index 9bc5b10..2cfc426 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameV11.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v11/StompFrameV11.java
@@ -62,9 +62,9 @@ public class StompFrameV11 extends StompFrame
          // Output the headers.
          for (Header h : allHeaders)
          {
-            head.append(h.getEscapedKey());
+            head.append(h.getEncodedKey());
             head.append(Stomp.Headers.SEPARATOR);
-            head.append(h.getEscapedValue());
+            head.append(h.getEncodedValue());
             head.append(Stomp.NEWLINE);
          }
          // Add a newline to separate the headers from the content.

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameHandlerV12.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameHandlerV12.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameHandlerV12.java
index 36a5dbe..3ca1701 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameHandlerV12.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameHandlerV12.java
@@ -166,24 +166,15 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE
                }
                case HEADER_SEPARATOR:
                {
-                  if (isEscaping)
+                  if (inHeaderName)
                   {
-                     //a colon
-                     holder.append(b);
-                     isEscaping = false;
-                  }
-                  else
-                  {
-                     if (inHeaderName)
-                     {
-                        headerName = holder.getString();
+                     headerName = holder.getString();
 
-                        holder.reset();
+                     holder.reset();
 
-                        inHeaderName = false;
+                     inHeaderName = false;
 
-                        headerValueWhitespace = true;
-                     }
+                     headerValueWhitespace = true;
                   }
 
                   whiteSpaceOnly = false;
@@ -225,6 +216,19 @@ public class StompFrameHandlerV12 extends StompFrameHandlerV11 implements FrameE
                   nextEOLChar = true;
                   break;
                }
+               case StompDecoder.c:
+               {
+                  if (isEscaping)
+                  {
+                     holder.append(StompDecoder.HEADER_SEPARATOR);
+                     isEscaping = false;
+                  }
+                  else
+                  {
+                     holder.append(b);
+                  }
+                  break;
+               }
                case NEW_LINE:
                {
                   nextEOLChar = false;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameV12.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameV12.java b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameV12.java
index 4dafa0c..2be74f1 100644
--- a/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameV12.java
+++ b/hornetq-protocols/hornetq-stomp-protocol/src/main/java/org/hornetq/core/protocol/stomp/v12/StompFrameV12.java
@@ -62,9 +62,9 @@ public class StompFrameV12 extends StompFrame
          // Output the headers.
          for (Header h : allHeaders)
          {
-            head.append(h.getEscapedKey());
+            head.append(h.getEncodedKey());
             head.append(Stomp.Headers.SEPARATOR);
-            head.append(h.getEscapedValue());
+            head.append(h.getEncodedValue());
             head.append(Stomp.NEWLINE);
          }
 
@@ -104,49 +104,4 @@ public class StompFrameV12 extends StompFrame
          allHeaders.add(new Header(key, val));
       }
    }
-
-   @Override
-   public String escape(String str)
-   {
-      int len = str.length();
-
-      char[] buffer = new char[2 * len];
-      int iBuffer = 0;
-      for (int i = 0; i < len; i++)
-      {
-         char c = str.charAt(i);
-         if (c == '\r')
-         {
-            buffer[iBuffer++] = '\\';
-            buffer[iBuffer] = 'r';
-         }
-         else if (c == '\n')
-         {
-            buffer[iBuffer++] = '\\';
-            buffer[iBuffer] = 'n';
-         }
-         else if (c == '\\')
-         {
-            buffer[iBuffer++] = '\\';
-            buffer[iBuffer] = '\\';
-         }
-         else if (c == ':')
-         {
-            buffer[iBuffer++] = '\\';
-            buffer[iBuffer] = ':';
-         }
-         else
-         {
-            buffer[iBuffer] = c;
-         }
-         iBuffer++;
-      }
-
-      char[] total = new char[iBuffer];
-      System.arraycopy(buffer, 0, total, 0, iBuffer);
-
-      return new String(total);
-   }
-
-
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-protocols/pom.xml b/hornetq-protocols/pom.xml
index 54e7012..1ecde53 100644
--- a/hornetq-protocols/pom.xml
+++ b/hornetq-protocols/pom.xml
@@ -19,6 +19,8 @@
    <modules>
       <module>hornetq-amqp-protocol</module>
       <module>hornetq-stomp-protocol</module>
+      <module>hornetq-openwire-protocol</module>
+      <module>hornetq-proton-plug</module>
    </modules>
 
-</project>
\ No newline at end of file
+</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-ra/pom.xml b/hornetq-ra/pom.xml
index fc9ad51..561af3e 100644
--- a/hornetq-ra/pom.xml
+++ b/hornetq-ra/pom.xml
@@ -52,6 +52,21 @@
          <artifactId>jboss-jca-api</artifactId>
          <scope>provided</scope>
       </dependency>
+      <dependency>
+         <groupId>org.jboss.ironjacamar</groupId>
+         <artifactId>ironjacamar-core-api</artifactId>
+         <scope>provided</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.spec.javax.transaction</groupId>
+         <artifactId>jboss-transaction-api_1.2_spec</artifactId>
+         <scope>provided</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss</groupId>
+         <artifactId>jboss-transaction-spi</artifactId>
+         <scope>provided</scope>
+      </dependency>
    </dependencies>
 
 </project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAManagedConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAManagedConnection.java b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAManagedConnection.java
index b51c388..055b3e1 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAManagedConnection.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAManagedConnection.java
@@ -42,6 +42,7 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.locks.ReentrantLock;
 
+import org.hornetq.core.client.impl.ClientSessionInternal;
 import org.hornetq.jms.client.HornetQConnection;
 import org.hornetq.jms.client.HornetQConnectionFactory;
 import org.hornetq.jms.client.HornetQXAConnection;
@@ -51,6 +52,7 @@ import org.hornetq.jms.client.HornetQXAConnection;
  *
  * @author <a href="mailto:adrian@jboss.com">Adrian Brock</a>
  * @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public final class HornetQRAManagedConnection implements ManagedConnection, ExceptionListener
 {
@@ -292,7 +294,7 @@ public final class HornetQRAManagedConnection implements ManagedConnection, Exce
       try
       {
          /**
-          * (xa|nonXA)Session.close() may NOT be called BEFORE connection.close().
+          * (xa|nonXA)Session.close() may NOT be called BEFORE connection.close()
           * <p>
           * If the ClientSessionFactory is trying to fail-over or reconnect with -1 attempts, and
           * one calls session.close() it may effectively dead-lock.
@@ -522,12 +524,14 @@ public final class HornetQRAManagedConnection implements ManagedConnection, Exce
       }
 
       //
-      // Spec says a mc must allways return the same XA resource,
+      // Spec says a mc must always return the same XA resource,
       // so we cache it.
       //
       if (xaResource == null)
       {
-         xaResource = new HornetQRAXAResource(this, xaSession.getXAResource());
+         ClientSessionInternal csi = (ClientSessionInternal) xaSession.getXAResource();
+         HornetQRAXAResource hqXAResource = new HornetQRAXAResource(this, xaSession.getXAResource());
+         xaResource = new HornetQXAResourceWrapper(hqXAResource, ra.getJndiName(), csi.getNodeId());
       }
 
       if (HornetQRAManagedConnection.trace)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASession.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASession.java b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASession.java
index d03f602..e4ace2b 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASession.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASession.java
@@ -49,12 +49,16 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Set;
 
+import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
+import org.hornetq.jms.client.HornetQSession;
+
 
 /**
  * A joint interface for JMS sessions
  *
  * @author <a href="mailto:adrian@jboss.com">Adrian Brock</a>
  * @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public final class HornetQRASession implements QueueSession, TopicSession, XAQueueSession, XATopicSession
 {
@@ -1273,6 +1277,18 @@ public final class HornetQRASession implements QueueSession, TopicSession, XAQue
    }
 
    /**
+    * Returns the ID of the Node that this session is associated with.
+    *
+    * @return Node ID
+    */
+   public String getNodeId() throws JMSException
+   {
+      HornetQSession session = (HornetQSession) getSessionInternal();
+      ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal) session.getCoreSession().getSessionFactory();
+      return factory.getLiveNodeId();
+   }
+
+   /**
     * Get the session
     *
     * @return The session

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASessionFactoryImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASessionFactoryImpl.java b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASessionFactoryImpl.java
index 80493bc..58a88a4 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASessionFactoryImpl.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRASessionFactoryImpl.java
@@ -923,10 +923,10 @@ public final class HornetQRASessionFactoryImpl extends HornetQConnectionForConte
                      break;
                   //The value {@code Session.CLIENT_ACKNOWLEDGE} may not be used.
                   case Session.CLIENT_ACKNOWLEDGE:
-                     throw HornetQRABundle.BUNDLE.invalidSessionTransactedModeRuntime();
+                     throw HornetQRABundle.BUNDLE.invalidClientAcknowledgeModeRuntime();
                      //same with this although the spec doesn't explicitly say
                   case Session.SESSION_TRANSACTED:
-                     throw HornetQRABundle.BUNDLE.invalidClientAcknowledgeModeRuntime();
+                     throw HornetQRABundle.BUNDLE.invalidSessionTransactedModeRuntime();
                   default:
                      throw HornetQRABundle.BUNDLE.invalidAcknowledgeMode(acknowledgeMode);
                }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAXAResource.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAXAResource.java b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAXAResource.java
index 31cbe75..053b4f2 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAXAResource.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQRAXAResource.java
@@ -18,6 +18,7 @@ import javax.transaction.xa.Xid;
 
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.core.client.impl.ClientSessionInternal;
+import org.hornetq.core.client.impl.HornetQXAResource;
 
 /**
  * HornetQXAResource.
@@ -25,7 +26,7 @@ import org.hornetq.core.client.impl.ClientSessionInternal;
  * @author <a href="adrian@jboss.com">Adrian Brock</a>
  * @author <a href="jesper.pedersen@jboss.org">Jesper Pedersen</a>
  */
-public class HornetQRAXAResource implements XAResource
+public class HornetQRAXAResource implements HornetQXAResource
 {
    /** Trace enabled */
    private static boolean trace = HornetQRALogger.LOGGER.isTraceEnabled();
@@ -247,4 +248,10 @@ public class HornetQRAXAResource implements XAResource
 
       return xaResource.setTransactionTimeout(seconds);
    }
+
+   @Override
+   public XAResource getResource()
+   {
+      return xaResource;
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/HornetQResourceAdapter.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQResourceAdapter.java b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQResourceAdapter.java
index c6399ac..d72ee44 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQResourceAdapter.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQResourceAdapter.java
@@ -31,6 +31,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import org.hornetq.api.core.BroadcastEndpointFactoryConfiguration;
 import org.hornetq.api.core.DiscoveryGroupConfiguration;
@@ -56,12 +58,18 @@ import org.jgroups.JChannel;
  * @author <a href="adrian@jboss.com">Adrian Brock</a>
  * @author <a href="jesper.pedersen@jboss.org">Jesper Pedersen</a>
  * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class HornetQResourceAdapter implements ResourceAdapter, Serializable
 {
    private static final long serialVersionUID = 4756893709825838770L;
 
    /**
+    * The Name of the product that this resource adapter represents.
+    */
+   public static final String PRODUCT_NAME = "HornetQ";
+
+   /**
     * Trace enabled
     */
    private static boolean trace = HornetQRALogger.LOGGER.isTraceEnabled();
@@ -111,6 +119,8 @@ public class HornetQResourceAdapter implements ResourceAdapter, Serializable
 
    private final List<HornetQRAManagedConnectionFactory> managedConnectionFactories = new ArrayList<HornetQRAManagedConnectionFactory>();
 
+   private String entries;
+
    /**
     * Constructor
     */
@@ -371,6 +381,29 @@ public class HornetQResourceAdapter implements ResourceAdapter, Serializable
       this.raProperties.setHA(ha);
    }
 
+   public String getEntries()
+   {
+      return entries;
+   }
+
+   public String getJndiName()
+   {
+      if (!(entries == null || entries.isEmpty()))
+      {
+         Matcher m = Pattern.compile("\"(.*?)\"").matcher(entries);
+         if (m.find())
+         {
+            return m.group(1);
+         }
+      }
+      return null;
+   }
+
+   public void setEntries(String entries)
+   {
+      this.entries = entries;
+   }
+
    /**
     * Get the discovery group name
     *
@@ -1890,7 +1923,11 @@ public class HornetQResourceAdapter implements ResourceAdapter, Serializable
 
             String localBindAddress = overrideProperties.getDiscoveryLocalBindAddress() != null ? overrideProperties.getDiscoveryLocalBindAddress()
                : raProperties.getDiscoveryLocalBindAddress();
-            endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration(discoveryAddress, discoveryPort, localBindAddress, -1);
+            endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration()
+               .setGroupAddress(discoveryAddress)
+               .setGroupPort(discoveryPort)
+               .setLocalBindAddress(localBindAddress)
+               .setLocalBindPort(-1);
          }
          else if (jgroupsFileName != null)
          {
@@ -1911,7 +1948,10 @@ public class HornetQResourceAdapter implements ResourceAdapter, Serializable
             initialTimeout = HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT;
          }
 
-         DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration(refreshTimeout, initialTimeout, endpointFactoryConfiguration);
+         DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration()
+            .setRefreshTimeout(refreshTimeout)
+            .setDiscoveryInitialWaitTimeout(initialTimeout)
+            .setBroadcastEndpointFactoryConfiguration(endpointFactoryConfiguration);
 
          if (HornetQRALogger.LOGGER.isDebugEnabled())
          {
@@ -2011,7 +2051,11 @@ public class HornetQResourceAdapter implements ResourceAdapter, Serializable
 
             String localBindAddress = overrideProperties.getDiscoveryLocalBindAddress() != null ? overrideProperties.getDiscoveryLocalBindAddress()
                : raProperties.getDiscoveryLocalBindAddress();
-            endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration(discoveryAddress, discoveryPort, localBindAddress, -1);
+            endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration()
+               .setGroupAddress(discoveryAddress)
+               .setGroupPort(discoveryPort)
+               .setLocalBindAddress(localBindAddress)
+               .setLocalBindPort(-1);
          }
          else if (jgroupsFileName != null)
          {
@@ -2045,7 +2089,10 @@ public class HornetQResourceAdapter implements ResourceAdapter, Serializable
          {
             initialTimeout = HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT;
          }
-         DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration(refreshTimeout, initialTimeout, endpointFactoryConfiguration);
+         DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration()
+            .setRefreshTimeout(refreshTimeout)
+            .setDiscoveryInitialWaitTimeout(initialTimeout)
+            .setBroadcastEndpointFactoryConfiguration(endpointFactoryConfiguration);
 
          groupConfiguration.setRefreshTimeout(refreshTimeout);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/HornetQXAResourceWrapper.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/HornetQXAResourceWrapper.java b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQXAResourceWrapper.java
new file mode 100644
index 0000000..043f35b
--- /dev/null
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/HornetQXAResourceWrapper.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.ra;
+
+import javax.transaction.xa.XAException;
+import javax.transaction.xa.XAResource;
+import javax.transaction.xa.Xid;
+
+import org.hornetq.core.client.impl.HornetQXAResource;
+import org.hornetq.utils.VersionLoader;
+
+/**
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
+ *
+ * Wraps XAResource with org.jboss.tm.XAResourceWrapper.  This adds extra meta-data to to the XAResource used by
+ * Transaction Manager for recovery scenarios.
+ */
+
+public class HornetQXAResourceWrapper implements org.jboss.tm.XAResourceWrapper, org.jboss.jca.core.spi.transaction.xa.XAResourceWrapper, HornetQXAResource
+{
+   private final XAResource xaResource;
+
+   // The EIS Name
+   private final String productName;
+
+   // The EIS Version
+   private final String productVersion;
+
+   // A composite of NodeID + JNDIName that allows adminstrator looking at an XAResource to determine it's origin.
+   private final String jndiNameNodeId;
+
+   /**
+    * Creates a new XAResourceWrapper.  PRODUCT_NAME, productVersion and jndiName are useful for log output in the
+    * Transaction Manager.  For HornetQ only the resourceManagerID is required to allow Transaction Manager to recover
+    * from relevant recovery scenarios.
+    *
+    * @param xaResource
+    * @param jndiName
+    */
+   public HornetQXAResourceWrapper(XAResource xaResource, String jndiName, String nodeId)
+   {
+      this.xaResource = xaResource;
+      this.productName = HornetQResourceAdapter.PRODUCT_NAME;
+      this.productVersion = VersionLoader.getVersion().getFullVersion();
+      this.jndiNameNodeId = jndiName + " NodeId:" + nodeId;
+   }
+
+   @Override
+   public XAResource getResource()
+   {
+      return xaResource;
+   }
+
+   @Override
+   public String getProductName()
+   {
+      return productName;
+   }
+
+   @Override
+   public String getProductVersion()
+   {
+      return productVersion;
+   }
+
+   @Override
+   public String getJndiName()
+   {
+      return jndiNameNodeId;
+   }
+
+   @Override
+   public void commit(Xid xid, boolean b) throws XAException
+   {
+      getResource().commit(xid, b);
+   }
+
+   @Override
+   public void end(Xid xid, int i) throws XAException
+   {
+      getResource().end(xid, i);
+   }
+
+   @Override
+   public void forget(Xid xid) throws XAException
+   {
+      getResource().forget(xid);
+   }
+
+   @Override
+   public int getTransactionTimeout() throws XAException
+   {
+      return getResource().getTransactionTimeout();
+   }
+
+   @Override
+   public boolean isSameRM(XAResource xaResource) throws XAException
+   {
+      return getResource().isSameRM(xaResource);
+   }
+
+   @Override
+   public int prepare(Xid xid) throws XAException
+   {
+      return getResource().prepare(xid);
+   }
+
+   @Override
+   public Xid[] recover(int i) throws XAException
+   {
+      return getResource().recover(i);
+   }
+
+   @Override
+   public void rollback(Xid xid) throws XAException
+   {
+      getResource().rollback(xid);
+   }
+
+   @Override
+   public boolean setTransactionTimeout(int i) throws XAException
+   {
+      return getResource().setTransactionTimeout(i);
+   }
+
+   @Override
+   public void start(Xid xid, int i) throws XAException
+   {
+      getResource().start(xid, i);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivation.java b/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivation.java
index d0a17a4..d75be85 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivation.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivation.java
@@ -46,6 +46,7 @@ import org.hornetq.ra.HornetQRAConnectionFactory;
 import org.hornetq.ra.HornetQRALogger;
 import org.hornetq.ra.HornetQRaUtils;
 import org.hornetq.ra.HornetQResourceAdapter;
+import org.hornetq.utils.FutureLatch;
 import org.hornetq.utils.SensitiveDataCodec;
 
 /**
@@ -401,9 +402,33 @@ public class HornetQActivation
 
       handlers.clear();
 
+      FutureLatch future = new FutureLatch(handlersCopy.length);
+      List<Thread> interruptThreads = new ArrayList<>();
       for (HornetQMessageHandler handler : handlersCopy)
       {
-         handler.interruptConsumer();
+         Thread thread = handler.interruptConsumer(future);
+         if (thread != null)
+         {
+            interruptThreads.add(thread);
+         }
+      }
+
+      //wait for all the consumers to complete any onmessage calls
+      boolean stuckThreads = !future.await(factory.getCallTimeout());
+      //if any are stuck then we need to interrupt them
+      if (stuckThreads)
+      {
+         for (Thread interruptThread : interruptThreads)
+         {
+            try
+            {
+               interruptThread.interrupt();
+            }
+            catch (Exception e)
+            {
+               //ok
+            }
+         }
       }
 
       Thread threadTearDown = new Thread("TearDown/HornetQActivation")

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivationSpec.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivationSpec.java b/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivationSpec.java
index ed40b94..f9ce2f2 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivationSpec.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQActivationSpec.java
@@ -12,13 +12,20 @@
  */
 package org.hornetq.ra.inflow;
 
+import javax.jms.Queue;
 import javax.jms.Session;
+import javax.jms.Topic;
 import javax.resource.ResourceException;
 import javax.resource.spi.ActivationSpec;
 import javax.resource.spi.InvalidPropertyException;
 import javax.resource.spi.ResourceAdapter;
+import java.beans.IntrospectionException;
+import java.beans.PropertyDescriptor;
 import java.io.Serializable;
+import java.util.ArrayList;
 import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
 
 import org.hornetq.ra.ConnectionFactoryProperties;
 import org.hornetq.ra.HornetQRALogger;
@@ -773,9 +780,47 @@ public class HornetQActivationSpec extends ConnectionFactoryProperties implement
          HornetQRALogger.LOGGER.trace("validate()");
       }
 
-      if (destination == null || destination.trim().equals(""))
+      List<String> errorMessages = new ArrayList<String>();
+      List<PropertyDescriptor> propsNotSet = new ArrayList<PropertyDescriptor>();
+
+      try
+      {
+         if (destination == null || destination.trim().equals(""))
+         {
+            propsNotSet.add(new PropertyDescriptor("destination", HornetQActivationSpec.class));
+            errorMessages.add("Destination is mandatory.");
+         }
+
+         if (destinationType != null && !Topic.class.getName().equals(destinationType) && !Queue.class.getName().equals(destinationType))
+         {
+            propsNotSet.add(new PropertyDescriptor("destinationType", HornetQActivationSpec.class));
+            errorMessages.add("If set, the destinationType must be either 'javax.jms.Topic' or 'javax.jms.Queue'.");
+         }
+
+         if ((destinationType == null || destinationType.length() == 0 || Topic.class.getName().equals(destinationType)) && isSubscriptionDurable() && (subscriptionName == null || subscriptionName.length() == 0))
+         {
+            propsNotSet.add(new PropertyDescriptor("subscriptionName", HornetQActivationSpec.class));
+            errorMessages.add("If subscription is durable then subscription name must be specified.");
+         }
+      }
+      catch (IntrospectionException e)
+      {
+         e.printStackTrace();
+      }
+
+      if (propsNotSet.size() > 0)
       {
-         throw new InvalidPropertyException("Destination is mandatory");
+         StringBuffer b = new StringBuffer();
+         b.append("Invalid settings:");
+         for (Iterator<String> iter = errorMessages.iterator(); iter.hasNext();)
+         {
+            b.append(" ");
+            b.append(iter.next());
+         }
+         InvalidPropertyException e = new InvalidPropertyException(b.toString());
+         final PropertyDescriptor[] descriptors = propsNotSet.toArray(new PropertyDescriptor[propsNotSet.size()]);
+         e.setInvalidPropertyDescriptors(descriptors);
+         throw e;
       }
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQMessageHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQMessageHandler.java b/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQMessageHandler.java
index 82b811d..eeb5b06 100644
--- a/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQMessageHandler.java
+++ b/hornetq-ra/src/main/java/org/hornetq/ra/inflow/HornetQMessageHandler.java
@@ -28,10 +28,14 @@ import org.hornetq.api.core.client.ClientSession.QueueQuery;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.MessageHandler;
 import org.hornetq.core.client.impl.ClientConsumerInternal;
+import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ClientSessionInternal;
 import org.hornetq.jms.client.HornetQDestination;
 import org.hornetq.jms.client.HornetQMessage;
 import org.hornetq.ra.HornetQRALogger;
+import org.hornetq.ra.HornetQResourceAdapter;
+import org.hornetq.ra.HornetQXAResourceWrapper;
+import org.hornetq.utils.FutureLatch;
 
 /**
  * The message handler
@@ -39,6 +43,7 @@ import org.hornetq.ra.HornetQRALogger;
  * @author <a href="adrian@jboss.com">Adrian Brock</a>
  * @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a>
  * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class HornetQMessageHandler implements MessageHandler
 {
@@ -99,11 +104,9 @@ public class HornetQMessageHandler implements MessageHandler
       SimpleString selectorString = selector == null || selector.trim().equals("") ? null : new SimpleString(selector);
       if (activation.isTopic() && spec.isSubscriptionDurable())
       {
-         String subscriptionName = spec.getSubscriptionName();
-         String clientID = spec.getClientID();
-
-         SimpleString queueName = new SimpleString(HornetQDestination.createQueueNameForDurableSubscription(true, clientID,
-                                                                                                            subscriptionName));
+         SimpleString queueName = new SimpleString(HornetQDestination.createQueueNameForDurableSubscription(true,
+                                                                                                            spec.getClientID(),
+                                                                                                            spec.getSubscriptionName()));
 
          QueueQuery subResponse = session.queueQuery(queueName);
 
@@ -188,7 +191,10 @@ public class HornetQMessageHandler implements MessageHandler
       transacted = activation.isDeliveryTransacted();
       if (activation.isDeliveryTransacted() && !activation.getActivationSpec().isUseLocalTx())
       {
-         endpoint = endpointFactory.createEndpoint(session);
+         XAResource xaResource = new HornetQXAResourceWrapper(session,
+                                                     ((HornetQResourceAdapter) spec.getResourceAdapter()).getJndiName(),
+                                                     ((ClientSessionFactoryInternal) cf).getLiveNodeId());
+         endpoint = endpointFactory.createEndpoint(xaResource);
          useXA = true;
       }
       else
@@ -204,19 +210,20 @@ public class HornetQMessageHandler implements MessageHandler
       return useXA ? session : null;
    }
 
-   public void interruptConsumer()
+   public Thread interruptConsumer(FutureLatch future)
    {
       try
       {
          if (consumer != null)
          {
-            consumer.interruptHandlers();
+            return consumer.prepareForClose(future);
          }
       }
       catch (Throwable e)
       {
          HornetQRALogger.LOGGER.warn("Error interrupting handler on endpoint " + endpoint + " handler=" + consumer);
       }
+      return null;
    }
 
    /**

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-rest/src/test/java/org/hornetq/rest/test/Embedded.java
----------------------------------------------------------------------
diff --git a/hornetq-rest/src/test/java/org/hornetq/rest/test/Embedded.java b/hornetq-rest/src/test/java/org/hornetq/rest/test/Embedded.java
index b51bd8b..aa6aff1 100644
--- a/hornetq-rest/src/test/java/org/hornetq/rest/test/Embedded.java
+++ b/hornetq-rest/src/test/java/org/hornetq/rest/test/Embedded.java
@@ -78,10 +78,10 @@ public class Embedded
       System.out.println("\nStarting Embedded");
       if (hornetqServer == null)
       {
-         Configuration configuration = new ConfigurationImpl();
-         configuration.setPersistenceEnabled(false);
-         configuration.setSecurityEnabled(false);
-         configuration.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+         Configuration configuration = new ConfigurationImpl()
+            .setPersistenceEnabled(false)
+            .setSecurityEnabled(false)
+            .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
 
          hornetqServer = HornetQServers.newHornetQServer(configuration);
          hornetqServer.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushQueueConsumerTest.java
----------------------------------------------------------------------
diff --git a/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushQueueConsumerTest.java b/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushQueueConsumerTest.java
index dd1111a..bbf4ba6 100644
--- a/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushQueueConsumerTest.java
+++ b/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushQueueConsumerTest.java
@@ -46,10 +46,10 @@ public class PersistentPushQueueConsumerTest
 
    public static void startup() throws Exception
    {
-      Configuration configuration = new ConfigurationImpl();
-      configuration.setPersistenceEnabled(false);
-      configuration.setSecurityEnabled(false);
-      configuration.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration configuration = new ConfigurationImpl()
+         .setPersistenceEnabled(false)
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
 
       hornetqServer = HornetQServers.newHornetQServer(configuration);
       hornetqServer.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushTopicConsumerTest.java
----------------------------------------------------------------------
diff --git a/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushTopicConsumerTest.java b/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushTopicConsumerTest.java
index e21fdda..135286a 100644
--- a/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushTopicConsumerTest.java
+++ b/hornetq-rest/src/test/java/org/hornetq/rest/test/PersistentPushTopicConsumerTest.java
@@ -57,10 +57,10 @@ public class PersistentPushTopicConsumerTest
    @BeforeClass
    public static void setup() throws Exception
    {
-      Configuration configuration = new ConfigurationImpl();
-      configuration.setPersistenceEnabled(false);
-      configuration.setSecurityEnabled(false);
-      configuration.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration configuration = new ConfigurationImpl()
+         .setPersistenceEnabled(false)
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
 
       server = HornetQServers.newHornetQServer(configuration);
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-rest/src/test/java/org/hornetq/rest/test/RawAckTest.java
----------------------------------------------------------------------
diff --git a/hornetq-rest/src/test/java/org/hornetq/rest/test/RawAckTest.java b/hornetq-rest/src/test/java/org/hornetq/rest/test/RawAckTest.java
index 21a5dae..a3eed8c 100644
--- a/hornetq-rest/src/test/java/org/hornetq/rest/test/RawAckTest.java
+++ b/hornetq-rest/src/test/java/org/hornetq/rest/test/RawAckTest.java
@@ -53,10 +53,10 @@ public class RawAckTest
    @BeforeClass
    public static void setup() throws Exception
    {
-      Configuration configuration = new ConfigurationImpl();
-      configuration.setPersistenceEnabled(false);
-      configuration.setSecurityEnabled(false);
-      configuration.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration configuration = new ConfigurationImpl()
+         .setPersistenceEnabled(false)
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
 
       hornetqServer = HornetQServers.newHornetQServer(configuration);
       hornetqServer.start();


[45/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/pom.xml
----------------------------------------------------------------------
diff --git a/examples/soak/normal/pom.xml b/examples/soak/normal/pom.xml
new file mode 100644
index 0000000..37cec41
--- /dev/null
+++ b/examples/soak/normal/pom.xml
@@ -0,0 +1,195 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+   <modelVersion>4.0.0</modelVersion>
+   <artifactId>hornetq-jms-soak-example</artifactId>
+   <packaging>jar</packaging>
+   <name>HornetQ Soak Normal Example</name>
+
+   <parent>
+      <groupId>org.hornetq.example.soak</groupId>
+      <artifactId>soak-examples</artifactId>
+      <version>2.5.0-SNAPSHOT</version>
+   </parent>
+
+   <dependencies>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-jms-client</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+   </dependencies>
+
+   <properties>
+      <server.dir>${basedir}/server0/</server.dir>
+   </properties>
+
+   <build>
+      <plugins>
+         <plugin>
+            <groupId>org.hornetq</groupId>
+            <artifactId>hornetq-maven-plugin</artifactId>
+            <dependencies>
+               <dependency>
+                  <groupId>org.hornetq.example.soak</groupId>
+                  <artifactId>hornetq-jms-soak-example</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-server</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-jms-server</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>io.netty</groupId>
+                  <artifactId>netty-all</artifactId>
+                  <version>${netty.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.jboss.naming</groupId>
+                  <artifactId>jnpserver</artifactId>
+                  <version>5.0.3.GA</version>
+               </dependency>
+            </dependencies>
+            <configuration>
+               <waitOnStart>false</waitOnStart>
+               <systemProperties>
+                  <property>
+                     <name>build.directory</name>
+                     <value>${basedir}/target/</value>
+                  </property>
+               </systemProperties>
+            </configuration>
+         </plugin>
+      </plugins>
+   </build>
+
+   <profiles>
+      <profile>
+         <id>local</id>
+         <activation>
+            <activeByDefault>true</activeByDefault>
+         </activation>
+         <build>
+            <plugins>
+               <plugin>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-maven-plugin</artifactId>
+                  <executions>
+                     <execution>
+                        <id>start</id>
+                        <goals>
+                           <goal>start</goal>
+                        </goals>
+                        <configuration>
+                           <fork>true</fork>
+                           <hornetqConfigurationDir>${server.dir}</hornetqConfigurationDir>
+                        </configuration>
+                     </execution>
+                     <execution>
+                        <id>runConsumer</id>
+                        <goals>
+                           <goal>runClient</goal>
+                        </goals>
+                        <configuration>
+                           <clientClass>org.hornetq.jms.soak.example.SoakReceiver</clientClass>
+                           <args>
+                              <param>jnp://localhost:1099</param>
+                           </args>
+                        </configuration>
+                     </execution>
+                     <execution>
+                        <id>runProducer</id>
+                        <goals>
+                           <goal>runClient</goal>
+                        </goals>
+                        <configuration>
+                           <clientClass>org.hornetq.jms.soak.example.SoakSender</clientClass>
+                           <args>
+                              <param>jnp://localhost:1099</param>
+                           </args>
+                        </configuration>
+                     </execution>
+                     <execution>
+                        <id>stop</id>
+                        <goals>
+                           <goal>stop</goal>
+                        </goals>
+                        <configuration>
+                           <hornetqConfigurationDir>${server.dir}</hornetqConfigurationDir>
+                        </configuration>
+                     </execution>
+                  </executions>
+               </plugin>
+            </plugins>
+         </build>
+      </profile>
+      <profile>
+         <id>remote</id>
+         <build>
+            <plugins>
+               <plugin>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-maven-plugin</artifactId>
+                  <executions>
+                     <execution>
+                        <id>runConsumer</id>
+                        <goals>
+                           <goal>runClient</goal>
+                        </goals>
+                        <configuration>
+                           <clientClass>org.hornetq.jms.soak.example.SoakReceiver</clientClass>
+                           <args>
+                              <param>jnp://localhost:1099</param>
+                           </args>
+                        </configuration>
+                     </execution>
+                     <execution>
+                        <id>runProducer</id>
+                        <goals>
+                           <goal>runClient</goal>
+                        </goals>
+                        <configuration>
+                           <clientClass>org.hornetq.jms.soak.example.SoakSender</clientClass>
+                           <args>
+                              <param>jnp://localhost:1099</param>
+                           </args>
+                        </configuration>
+                     </execution>
+                  </executions>
+               </plugin>
+            </plugins>
+         </build>
+      </profile>
+      <profile>
+         <id>server</id>
+         <build>
+            <plugins>
+               <plugin>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-maven-plugin</artifactId>
+                  <executions>
+                     <execution>
+                        <id>start</id>
+                        <goals>
+                           <goal>start</goal>
+                        </goals>
+                        <configuration>
+                           <hornetqConfigurationDir>${server.dir}</hornetqConfigurationDir>
+                           <fork>true</fork>
+                           <waitOnStart>true</waitOnStart>
+                        </configuration>
+                     </execution>
+                  </executions>
+               </plugin>
+            </plugins>
+         </build>
+      </profile>
+   </profiles>
+
+</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/soak/normal/server0/hornetq-beans.xml b/examples/soak/normal/server0/hornetq-beans.xml
deleted file mode 100644
index cd364f3..0000000
--- a/examples/soak/normal/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-<bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>         
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>   
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakBase.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakBase.java b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakBase.java
new file mode 100644
index 0000000..dd654ac
--- /dev/null
+++ b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakBase.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.jms.soak.example;
+
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.Random;
+import java.util.logging.Logger;
+
+/**
+ *
+ * A SoakBase
+ *
+ * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
+ *
+ *
+ */
+public class SoakBase
+{
+   private static final Logger log = Logger.getLogger(SoakBase.class.getName());
+
+   private static final String DEFAULT_SOAK_PROPERTIES_FILE_NAME = "soak.properties";
+
+   public static final int TO_MILLIS = 60 * 1000; // from minute to milliseconds
+
+   public static byte[] randomByteArray(final int length)
+   {
+      byte[] bytes = new byte[length];
+
+      Random random = new Random();
+
+      for (int i = 0; i < length; i++)
+      {
+         bytes[i] = Integer.valueOf(random.nextInt()).byteValue();
+      }
+
+      return bytes;
+   }
+
+   protected static String getPerfFileName()
+   {
+      String fileName = System.getProperty("soak.props");
+      if (fileName == null)
+      {
+         fileName = SoakBase.DEFAULT_SOAK_PROPERTIES_FILE_NAME;
+      }
+      return fileName;
+   }
+
+   protected static SoakParams getParams(final String fileName) throws Exception
+   {
+      Properties props = null;
+
+      InputStream is = null;
+
+      try
+      {
+         is = new FileInputStream(fileName);
+
+         props = new Properties();
+
+         props.load(is);
+      }
+      finally
+      {
+         if (is != null)
+         {
+            is.close();
+         }
+      }
+
+      int durationInMinutes = Integer.valueOf(props.getProperty("duration-in-minutes"));
+      int noOfWarmupMessages = Integer.valueOf(props.getProperty("num-warmup-messages"));
+      int messageSize = Integer.valueOf(props.getProperty("message-size"));
+      boolean durable = Boolean.valueOf(props.getProperty("durable"));
+      boolean transacted = Boolean.valueOf(props.getProperty("transacted"));
+      int batchSize = Integer.valueOf(props.getProperty("batch-size"));
+      boolean drainQueue = Boolean.valueOf(props.getProperty("drain-queue"));
+      String destinationLookup = props.getProperty("destination-lookup");
+      String connectionFactoryLookup = props.getProperty("connection-factory-lookup");
+      int throttleRate = Integer.valueOf(props.getProperty("throttle-rate"));
+      boolean dupsOK = Boolean.valueOf(props.getProperty("dups-ok-acknowlege"));
+      boolean disableMessageID = Boolean.valueOf(props.getProperty("disable-message-id"));
+      boolean disableTimestamp = Boolean.valueOf(props.getProperty("disable-message-timestamp"));
+
+      SoakBase.log.info("duration-in-minutes: " + durationInMinutes);
+      SoakBase.log.info("num-warmup-messages: " + noOfWarmupMessages);
+      SoakBase.log.info("message-size: " + messageSize);
+      SoakBase.log.info("durable: " + durable);
+      SoakBase.log.info("transacted: " + transacted);
+      SoakBase.log.info("batch-size: " + batchSize);
+      SoakBase.log.info("drain-queue: " + drainQueue);
+      SoakBase.log.info("throttle-rate: " + throttleRate);
+      SoakBase.log.info("connection-factory-lookup: " + connectionFactoryLookup);
+      SoakBase.log.info("destination-lookup: " + destinationLookup);
+      SoakBase.log.info("disable-message-id: " + disableMessageID);
+      SoakBase.log.info("disable-message-timestamp: " + disableTimestamp);
+      SoakBase.log.info("dups-ok-acknowledge: " + dupsOK);
+
+      SoakParams soakParams = new SoakParams();
+      soakParams.setDurationInMinutes(durationInMinutes);
+      soakParams.setNoOfWarmupMessages(noOfWarmupMessages);
+      soakParams.setMessageSize(messageSize);
+      soakParams.setDurable(durable);
+      soakParams.setSessionTransacted(transacted);
+      soakParams.setBatchSize(batchSize);
+      soakParams.setDrainQueue(drainQueue);
+      soakParams.setConnectionFactoryLookup(connectionFactoryLookup);
+      soakParams.setDestinationLookup(destinationLookup);
+      soakParams.setThrottleRate(throttleRate);
+      soakParams.setDisableMessageID(disableMessageID);
+      soakParams.setDisableTimestamp(disableTimestamp);
+      soakParams.setDupsOK(dupsOK);
+
+      return soakParams;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakParams.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakParams.java b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakParams.java
new file mode 100644
index 0000000..9b94d2b
--- /dev/null
+++ b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakParams.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.jms.soak.example;
+
+import java.io.Serializable;
+
+/**
+ *
+ * Class that holds the parameters used in the performance examples
+ *
+ * @author <a href="ataylor@redhat.com">Andy Taylor</a>
+ */
+public class SoakParams implements Serializable
+{
+   private static final long serialVersionUID = -4336539641012356002L;
+
+   private int durationInMinutes = 60;
+
+   private int noOfWarmupMessages;
+
+   private int messageSize = 1024; // in bytes
+
+   private boolean durable = false;
+
+   private boolean isSessionTransacted = false;
+
+   private int batchSize = 5000;
+
+   private boolean drainQueue = true;
+
+   private String connectionFactoryLookup;
+
+   private String destinationLookup;
+
+   private int throttleRate;
+
+   private boolean disableMessageID;
+
+   private boolean disableTimestamp;
+
+   private boolean dupsOK;
+
+   public synchronized int getDurationInMinutes()
+   {
+      return durationInMinutes;
+   }
+
+   public synchronized void setDurationInMinutes(final int durationInMinutes)
+   {
+      this.durationInMinutes = durationInMinutes;
+   }
+
+   public synchronized int getNoOfWarmupMessages()
+   {
+      return noOfWarmupMessages;
+   }
+
+   public synchronized void setNoOfWarmupMessages(final int noOfWarmupMessages)
+   {
+      this.noOfWarmupMessages = noOfWarmupMessages;
+   }
+
+   public synchronized int getMessageSize()
+   {
+      return messageSize;
+   }
+
+   public synchronized void setMessageSize(final int messageSize)
+   {
+      this.messageSize = messageSize;
+   }
+
+   public synchronized boolean isDurable()
+   {
+      return durable;
+   }
+
+   public synchronized void setDurable(final boolean durable)
+   {
+      this.durable = durable;
+   }
+
+   public synchronized boolean isSessionTransacted()
+   {
+      return isSessionTransacted;
+   }
+
+   public synchronized void setSessionTransacted(final boolean isSessionTransacted)
+   {
+      this.isSessionTransacted = isSessionTransacted;
+   }
+
+   public synchronized int getBatchSize()
+   {
+      return batchSize;
+   }
+
+   public synchronized void setBatchSize(final int batchSize)
+   {
+      this.batchSize = batchSize;
+   }
+
+   public synchronized boolean isDrainQueue()
+   {
+      return drainQueue;
+   }
+
+   public synchronized void setDrainQueue(final boolean drainQueue)
+   {
+      this.drainQueue = drainQueue;
+   }
+
+   public synchronized String getConnectionFactoryLookup()
+   {
+      return connectionFactoryLookup;
+   }
+
+   public synchronized void setConnectionFactoryLookup(final String connectionFactoryLookup)
+   {
+      this.connectionFactoryLookup = connectionFactoryLookup;
+   }
+
+   public synchronized String getDestinationLookup()
+   {
+      return destinationLookup;
+   }
+
+   public synchronized void setDestinationLookup(final String destinationLookup)
+   {
+      this.destinationLookup = destinationLookup;
+   }
+
+   public synchronized int getThrottleRate()
+   {
+      return throttleRate;
+   }
+
+   public synchronized void setThrottleRate(final int throttleRate)
+   {
+      this.throttleRate = throttleRate;
+   }
+
+   public synchronized boolean isDisableMessageID()
+   {
+      return disableMessageID;
+   }
+
+   public synchronized void setDisableMessageID(final boolean disableMessageID)
+   {
+      this.disableMessageID = disableMessageID;
+   }
+
+   public synchronized boolean isDisableTimestamp()
+   {
+      return disableTimestamp;
+   }
+
+   public synchronized void setDisableTimestamp(final boolean disableTimestamp)
+   {
+      this.disableTimestamp = disableTimestamp;
+   }
+
+   public synchronized boolean isDupsOK()
+   {
+      return dupsOK;
+   }
+
+   public synchronized void setDupsOK(final boolean dupsOK)
+   {
+      this.dupsOK = dupsOK;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakReceiver.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakReceiver.java b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakReceiver.java
new file mode 100644
index 0000000..913a2f7
--- /dev/null
+++ b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakReceiver.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.jms.soak.example;
+
+import java.lang.Override;
+import java.lang.Runnable;
+import java.util.Hashtable;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.logging.Logger;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.Destination;
+import javax.jms.ExceptionListener;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Session;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+public class SoakReceiver
+{
+   private static final Logger log = Logger.getLogger(SoakReceiver.class.getName());
+
+   private static final String EOF = UUID.randomUUID().toString();
+
+   public static void main(final String[] args)
+   {
+      Runnable runnable = new Runnable()
+      {
+         @Override
+         public void run()
+         {
+
+            String jndiURL = System.getProperty("jndi.address");
+            if(jndiURL == null)
+            {
+               jndiURL = args.length > 0 ? args[0] : "jnp://localhost:1099";
+            }
+
+            System.out.println("Connecting to JNDI at " + jndiURL);
+
+            try
+            {
+               String fileName = SoakBase.getPerfFileName();
+
+               SoakParams params = SoakBase.getParams(fileName);
+
+               Hashtable<String, String> jndiProps = new Hashtable<String, String>();
+               jndiProps.put("java.naming.provider.url", jndiURL);
+               jndiProps.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
+               jndiProps.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
+
+               final SoakReceiver receiver = new SoakReceiver(jndiProps, params);
+
+               Runtime.getRuntime().addShutdownHook(new Thread()
+               {
+                  @Override
+                  public void run()
+                  {
+                     receiver.disconnect();
+                  }
+               });
+
+               receiver.run();
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+            }
+         }
+      };
+
+      Thread t = new Thread(runnable);
+      t.start();
+   }
+
+   private final Hashtable<String, String> jndiProps;
+
+   private final SoakParams perfParams;
+
+   private final ExceptionListener exceptionListener = new ExceptionListener()
+   {
+      public void onException(final JMSException e)
+      {
+         disconnect();
+         connect();
+      }
+   };
+
+   private final MessageListener listener = new MessageListener()
+   {
+      int modulo = 10000;
+
+      private final AtomicLong count = new AtomicLong(0);
+
+      private final long start = System.currentTimeMillis();
+
+      long moduloStart = start;
+
+      public void onMessage(final Message msg)
+      {
+         long totalDuration = System.currentTimeMillis() - start;
+
+         try
+         {
+            if (SoakReceiver.EOF.equals(msg.getStringProperty("eof")))
+            {
+               SoakReceiver.log.info(String.format("Received %s messages in %.2f minutes", count, 1.0 * totalDuration /
+                                                                                                  SoakBase.TO_MILLIS));
+               SoakReceiver.log.info("END OF RUN");
+
+               return;
+            }
+         }
+         catch (JMSException e1)
+         {
+            e1.printStackTrace();
+         }
+         if (count.incrementAndGet() % modulo == 0)
+         {
+            double duration = (1.0 * System.currentTimeMillis() - moduloStart) / 1000;
+            moduloStart = System.currentTimeMillis();
+            SoakReceiver.log.info(String.format("received %s messages in %2.2fs (total: %.0fs)",
+                                                modulo,
+                                                duration,
+                                                totalDuration / 1000.0));
+         }
+      }
+   };
+
+   private Session session;
+
+   private Connection connection;
+
+   private SoakReceiver(final Hashtable<String, String> jndiProps, final SoakParams perfParams)
+   {
+      this.jndiProps = jndiProps;
+      this.perfParams = perfParams;
+   }
+
+   public void run() throws Exception
+   {
+      connect();
+
+      boolean runInfinitely = perfParams.getDurationInMinutes() == -1;
+
+      if (!runInfinitely)
+      {
+         Thread.sleep(perfParams.getDurationInMinutes() * SoakBase.TO_MILLIS);
+
+         // send EOF message
+         Message eof = session.createMessage();
+         eof.setStringProperty("eof", SoakReceiver.EOF);
+         listener.onMessage(eof);
+
+         if (connection != null)
+         {
+            connection.close();
+            connection = null;
+         }
+      }
+      else
+      {
+         while (true)
+         {
+            Thread.sleep(500);
+         }
+      }
+   }
+
+   private void disconnect()
+   {
+      if (connection != null)
+      {
+         try
+         {
+            connection.setExceptionListener(null);
+            connection.close();
+         }
+         catch (JMSException e)
+         {
+            e.printStackTrace();
+         }
+         finally
+         {
+            connection = null;
+         }
+      }
+   }
+
+   private void connect()
+   {
+      InitialContext ic = null;
+      try
+      {
+         ic = new InitialContext(jndiProps);
+
+         ConnectionFactory factory = (ConnectionFactory)ic.lookup(perfParams.getConnectionFactoryLookup());
+
+         Destination destination = (Destination)ic.lookup(perfParams.getDestinationLookup());
+
+         connection = factory.createConnection();
+         connection.setExceptionListener(exceptionListener);
+
+         session = connection.createSession(perfParams.isSessionTransacted(),
+                                            perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE
+                                                                 : Session.AUTO_ACKNOWLEDGE);
+
+         MessageConsumer messageConsumer = session.createConsumer(destination);
+         messageConsumer.setMessageListener(listener);
+
+         connection.start();
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+      }
+      finally
+      {
+         try
+         {
+            ic.close();
+         }
+         catch (NamingException e)
+         {
+            e.printStackTrace();
+         }
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakSender.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakSender.java b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakSender.java
new file mode 100644
index 0000000..3bc0705
--- /dev/null
+++ b/examples/soak/normal/src/main/java/org/hornetq/jms/soak/example/SoakSender.java
@@ -0,0 +1,245 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.jms.soak.example;
+
+import java.util.Hashtable;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.logging.Logger;
+
+import javax.jms.BytesMessage;
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+import javax.jms.ExceptionListener;
+import javax.jms.JMSException;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.hornetq.utils.TokenBucketLimiter;
+import org.hornetq.utils.TokenBucketLimiterImpl;
+
+public class SoakSender
+{
+   private static final Logger log = Logger.getLogger(SoakSender.class.getName());
+
+   public static void main(final String[] args)
+   {
+      String jndiURL = System.getProperty("jndi.address");
+      if(jndiURL == null)
+      {
+         jndiURL = args.length > 0 ? args[0] : "jnp://localhost:1099";
+      }
+
+      System.out.println("Connecting to JNDI at " + jndiURL);
+      try
+      {
+         String fileName = SoakBase.getPerfFileName();
+
+         SoakParams params = SoakBase.getParams(fileName);
+
+         Hashtable<String, String> jndiProps = new Hashtable<String, String>();
+         jndiProps.put("java.naming.provider.url", jndiURL);
+         jndiProps.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
+         jndiProps.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
+
+         final SoakSender sender = new SoakSender(jndiProps, params);
+
+         Runtime.getRuntime().addShutdownHook(new Thread()
+         {
+            @Override
+            public void run()
+            {
+               sender.disconnect();
+            }
+         });
+
+         sender.run();
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+      }
+   }
+
+   private final SoakParams perfParams;
+
+   private final Hashtable<String, String> jndiProps;
+
+   private Connection connection;
+
+   private Session session;
+
+   private MessageProducer producer;
+
+   private final ExceptionListener exceptionListener = new ExceptionListener()
+   {
+      public void onException(final JMSException e)
+      {
+         System.out.println("SoakReconnectableSender.exceptionListener.new ExceptionListener() {...}.onException()");
+         disconnect();
+         connect();
+      }
+
+   };
+
+   private SoakSender(final Hashtable<String, String> jndiProps, final SoakParams perfParams)
+   {
+      this.jndiProps = jndiProps;
+      this.perfParams = perfParams;
+   }
+
+   public void run() throws Exception
+   {
+      connect();
+
+      boolean runInfinitely = perfParams.getDurationInMinutes() == -1;
+
+      BytesMessage message = session.createBytesMessage();
+
+      byte[] payload = SoakBase.randomByteArray(perfParams.getMessageSize());
+
+      message.writeBytes(payload);
+
+      final int modulo = 10000;
+
+      TokenBucketLimiter tbl = perfParams.getThrottleRate() != -1 ? new TokenBucketLimiterImpl(perfParams.getThrottleRate(),
+                                                                                               false)
+                                                                 : null;
+
+      boolean transacted = perfParams.isSessionTransacted();
+      int txBatchSize = perfParams.getBatchSize();
+      boolean display = true;
+
+      long start = System.currentTimeMillis();
+      long moduleStart = start;
+      AtomicLong count = new AtomicLong(0);
+      while (true)
+      {
+         try
+         {
+            producer.send(message);
+            count.incrementAndGet();
+
+            if (transacted)
+            {
+               if (count.longValue() % txBatchSize == 0)
+               {
+                  session.commit();
+               }
+            }
+
+            long totalDuration = System.currentTimeMillis() - start;
+
+            if (display && count.longValue() % modulo == 0)
+            {
+               double duration = (1.0 * System.currentTimeMillis() - moduleStart) / 1000;
+               moduleStart = System.currentTimeMillis();
+               SoakSender.log.info(String.format("sent %s messages in %2.2fs (time: %.0fs)",
+                                                 modulo,
+                                                 duration,
+                                                 totalDuration / 1000.0));
+            }
+
+            if (tbl != null)
+            {
+               tbl.limit();
+            }
+
+            if (!runInfinitely && totalDuration > perfParams.getDurationInMinutes() * SoakBase.TO_MILLIS)
+            {
+               break;
+            }
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+         }
+      }
+
+      SoakSender.log.info(String.format("Sent %s messages in %s minutes", count, perfParams.getDurationInMinutes()));
+      SoakSender.log.info("END OF RUN");
+
+      if (connection != null)
+      {
+         connection.close();
+         connection = null;
+      }
+   }
+
+   private synchronized void disconnect()
+   {
+      if (connection != null)
+      {
+         try
+         {
+            connection.setExceptionListener(null);
+            connection.close();
+         }
+         catch (JMSException e)
+         {
+            e.printStackTrace();
+         }
+         finally
+         {
+            connection = null;
+         }
+      }
+   }
+
+   private void connect()
+   {
+      InitialContext ic = null;
+      try
+      {
+         ic = new InitialContext(jndiProps);
+
+         ConnectionFactory factory = (ConnectionFactory)ic.lookup(perfParams.getConnectionFactoryLookup());
+
+         Destination destination = (Destination)ic.lookup(perfParams.getDestinationLookup());
+
+         connection = factory.createConnection();
+
+         session = connection.createSession(perfParams.isSessionTransacted(),
+                                            perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE
+                                                                 : Session.AUTO_ACKNOWLEDGE);
+
+         producer = session.createProducer(destination);
+
+         producer.setDeliveryMode(perfParams.isDurable() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
+
+         producer.setDisableMessageID(perfParams.isDisableMessageID());
+
+         producer.setDisableMessageTimestamp(perfParams.isDisableTimestamp());
+
+         connection.setExceptionListener(exceptionListener);
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+      }
+      finally
+      {
+         try
+         {
+            ic.close();
+         }
+         catch (NamingException e)
+         {
+            e.printStackTrace();
+         }
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakBase.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakBase.java b/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakBase.java
deleted file mode 100644
index 1a413bd..0000000
--- a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakBase.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.soak.example;
-
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.util.Properties;
-import java.util.Random;
-import java.util.logging.Logger;
-
-/**
- *
- * A SoakBase
- *
- * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
- * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
- *
- *
- */
-public class SoakBase
-{
-   private static final Logger log = Logger.getLogger(SoakBase.class.getName());
-
-   private static final String DEFAULT_SOAK_PROPERTIES_FILE_NAME = "soak.properties";
-
-   public static final int TO_MILLIS = 60 * 1000; // from minute to milliseconds
-
-   public static byte[] randomByteArray(final int length)
-   {
-      byte[] bytes = new byte[length];
-
-      Random random = new Random();
-
-      for (int i = 0; i < length; i++)
-      {
-         bytes[i] = Integer.valueOf(random.nextInt()).byteValue();
-      }
-
-      return bytes;
-   }
-
-   protected static String getPerfFileName(final String[] args)
-   {
-      String fileName;
-
-      if (args.length > 1)
-      {
-         fileName = args[1];
-      }
-      else
-      {
-         fileName = SoakBase.DEFAULT_SOAK_PROPERTIES_FILE_NAME;
-      }
-      return fileName;
-   }
-
-   protected static SoakParams getParams(final String fileName) throws Exception
-   {
-      Properties props = null;
-
-      InputStream is = null;
-
-      try
-      {
-         is = new FileInputStream(fileName);
-
-         props = new Properties();
-
-         props.load(is);
-      }
-      finally
-      {
-         if (is != null)
-         {
-            is.close();
-         }
-      }
-
-      int durationInMinutes = Integer.valueOf(props.getProperty("duration-in-minutes"));
-      int noOfWarmupMessages = Integer.valueOf(props.getProperty("num-warmup-messages"));
-      int messageSize = Integer.valueOf(props.getProperty("message-size"));
-      boolean durable = Boolean.valueOf(props.getProperty("durable"));
-      boolean transacted = Boolean.valueOf(props.getProperty("transacted"));
-      int batchSize = Integer.valueOf(props.getProperty("batch-size"));
-      boolean drainQueue = Boolean.valueOf(props.getProperty("drain-queue"));
-      String destinationLookup = props.getProperty("destination-lookup");
-      String connectionFactoryLookup = props.getProperty("connection-factory-lookup");
-      int throttleRate = Integer.valueOf(props.getProperty("throttle-rate"));
-      boolean dupsOK = Boolean.valueOf(props.getProperty("dups-ok-acknowlege"));
-      boolean disableMessageID = Boolean.valueOf(props.getProperty("disable-message-id"));
-      boolean disableTimestamp = Boolean.valueOf(props.getProperty("disable-message-timestamp"));
-
-      SoakBase.log.info("duration-in-minutes: " + durationInMinutes);
-      SoakBase.log.info("num-warmup-messages: " + noOfWarmupMessages);
-      SoakBase.log.info("message-size: " + messageSize);
-      SoakBase.log.info("durable: " + durable);
-      SoakBase.log.info("transacted: " + transacted);
-      SoakBase.log.info("batch-size: " + batchSize);
-      SoakBase.log.info("drain-queue: " + drainQueue);
-      SoakBase.log.info("throttle-rate: " + throttleRate);
-      SoakBase.log.info("connection-factory-lookup: " + connectionFactoryLookup);
-      SoakBase.log.info("destination-lookup: " + destinationLookup);
-      SoakBase.log.info("disable-message-id: " + disableMessageID);
-      SoakBase.log.info("disable-message-timestamp: " + disableTimestamp);
-      SoakBase.log.info("dups-ok-acknowledge: " + dupsOK);
-
-      SoakParams soakParams = new SoakParams();
-      soakParams.setDurationInMinutes(durationInMinutes);
-      soakParams.setNoOfWarmupMessages(noOfWarmupMessages);
-      soakParams.setMessageSize(messageSize);
-      soakParams.setDurable(durable);
-      soakParams.setSessionTransacted(transacted);
-      soakParams.setBatchSize(batchSize);
-      soakParams.setDrainQueue(drainQueue);
-      soakParams.setConnectionFactoryLookup(connectionFactoryLookup);
-      soakParams.setDestinationLookup(destinationLookup);
-      soakParams.setThrottleRate(throttleRate);
-      soakParams.setDisableMessageID(disableMessageID);
-      soakParams.setDisableTimestamp(disableTimestamp);
-      soakParams.setDupsOK(dupsOK);
-
-      return soakParams;
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakParams.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakParams.java b/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakParams.java
deleted file mode 100644
index 9b94d2b..0000000
--- a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakParams.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.soak.example;
-
-import java.io.Serializable;
-
-/**
- *
- * Class that holds the parameters used in the performance examples
- *
- * @author <a href="ataylor@redhat.com">Andy Taylor</a>
- */
-public class SoakParams implements Serializable
-{
-   private static final long serialVersionUID = -4336539641012356002L;
-
-   private int durationInMinutes = 60;
-
-   private int noOfWarmupMessages;
-
-   private int messageSize = 1024; // in bytes
-
-   private boolean durable = false;
-
-   private boolean isSessionTransacted = false;
-
-   private int batchSize = 5000;
-
-   private boolean drainQueue = true;
-
-   private String connectionFactoryLookup;
-
-   private String destinationLookup;
-
-   private int throttleRate;
-
-   private boolean disableMessageID;
-
-   private boolean disableTimestamp;
-
-   private boolean dupsOK;
-
-   public synchronized int getDurationInMinutes()
-   {
-      return durationInMinutes;
-   }
-
-   public synchronized void setDurationInMinutes(final int durationInMinutes)
-   {
-      this.durationInMinutes = durationInMinutes;
-   }
-
-   public synchronized int getNoOfWarmupMessages()
-   {
-      return noOfWarmupMessages;
-   }
-
-   public synchronized void setNoOfWarmupMessages(final int noOfWarmupMessages)
-   {
-      this.noOfWarmupMessages = noOfWarmupMessages;
-   }
-
-   public synchronized int getMessageSize()
-   {
-      return messageSize;
-   }
-
-   public synchronized void setMessageSize(final int messageSize)
-   {
-      this.messageSize = messageSize;
-   }
-
-   public synchronized boolean isDurable()
-   {
-      return durable;
-   }
-
-   public synchronized void setDurable(final boolean durable)
-   {
-      this.durable = durable;
-   }
-
-   public synchronized boolean isSessionTransacted()
-   {
-      return isSessionTransacted;
-   }
-
-   public synchronized void setSessionTransacted(final boolean isSessionTransacted)
-   {
-      this.isSessionTransacted = isSessionTransacted;
-   }
-
-   public synchronized int getBatchSize()
-   {
-      return batchSize;
-   }
-
-   public synchronized void setBatchSize(final int batchSize)
-   {
-      this.batchSize = batchSize;
-   }
-
-   public synchronized boolean isDrainQueue()
-   {
-      return drainQueue;
-   }
-
-   public synchronized void setDrainQueue(final boolean drainQueue)
-   {
-      this.drainQueue = drainQueue;
-   }
-
-   public synchronized String getConnectionFactoryLookup()
-   {
-      return connectionFactoryLookup;
-   }
-
-   public synchronized void setConnectionFactoryLookup(final String connectionFactoryLookup)
-   {
-      this.connectionFactoryLookup = connectionFactoryLookup;
-   }
-
-   public synchronized String getDestinationLookup()
-   {
-      return destinationLookup;
-   }
-
-   public synchronized void setDestinationLookup(final String destinationLookup)
-   {
-      this.destinationLookup = destinationLookup;
-   }
-
-   public synchronized int getThrottleRate()
-   {
-      return throttleRate;
-   }
-
-   public synchronized void setThrottleRate(final int throttleRate)
-   {
-      this.throttleRate = throttleRate;
-   }
-
-   public synchronized boolean isDisableMessageID()
-   {
-      return disableMessageID;
-   }
-
-   public synchronized void setDisableMessageID(final boolean disableMessageID)
-   {
-      this.disableMessageID = disableMessageID;
-   }
-
-   public synchronized boolean isDisableTimestamp()
-   {
-      return disableTimestamp;
-   }
-
-   public synchronized void setDisableTimestamp(final boolean disableTimestamp)
-   {
-      this.disableTimestamp = disableTimestamp;
-   }
-
-   public synchronized boolean isDupsOK()
-   {
-      return dupsOK;
-   }
-
-   public synchronized void setDupsOK(final boolean dupsOK)
-   {
-      this.dupsOK = dupsOK;
-   }
-
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakReceiver.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakReceiver.java b/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakReceiver.java
deleted file mode 100644
index 7ecd710..0000000
--- a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakReceiver.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.soak.example;
-
-import java.util.Hashtable;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.logging.Logger;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.Session;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-public class SoakReceiver
-{
-   private static final Logger log = Logger.getLogger(SoakReceiver.class.getName());
-
-   private static final String EOF = UUID.randomUUID().toString();
-
-   public static void main(final String[] args)
-   {
-      for (int i = 0; i < args.length; i++)
-      {
-         System.out.println(i + ":" + args[i]);
-      }
-      String jndiURL = "jndi://localhost:1099";
-      if (args.length > 0)
-      {
-         jndiURL = args[0];
-      }
-
-      System.out.println("Connecting to JNDI at " + jndiURL);
-
-      try
-      {
-         String fileName = SoakBase.getPerfFileName(args);
-
-         SoakParams params = SoakBase.getParams(fileName);
-
-         Hashtable<String, String> jndiProps = new Hashtable<String, String>();
-         jndiProps.put("java.naming.provider.url", jndiURL);
-         jndiProps.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
-         jndiProps.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
-
-         final SoakReceiver receiver = new SoakReceiver(jndiProps, params);
-
-         Runtime.getRuntime().addShutdownHook(new Thread()
-         {
-            @Override
-            public void run()
-            {
-               receiver.disconnect();
-            }
-         });
-
-         receiver.run();
-      }
-      catch (Exception e)
-      {
-         e.printStackTrace();
-      }
-   }
-
-   private final Hashtable<String, String> jndiProps;
-
-   private final SoakParams perfParams;
-
-   private final ExceptionListener exceptionListener = new ExceptionListener()
-   {
-      public void onException(final JMSException e)
-      {
-         disconnect();
-         connect();
-      }
-   };
-
-   private final MessageListener listener = new MessageListener()
-   {
-      int modulo = 10000;
-
-      private final AtomicLong count = new AtomicLong(0);
-
-      private final long start = System.currentTimeMillis();
-
-      long moduloStart = start;
-
-      public void onMessage(final Message msg)
-      {
-         long totalDuration = System.currentTimeMillis() - start;
-
-         try
-         {
-            if (SoakReceiver.EOF.equals(msg.getStringProperty("eof")))
-            {
-               SoakReceiver.log.info(String.format("Received %s messages in %.2f minutes", count, 1.0 * totalDuration /
-                                                                                                  SoakBase.TO_MILLIS));
-               SoakReceiver.log.info("END OF RUN");
-
-               return;
-            }
-         }
-         catch (JMSException e1)
-         {
-            e1.printStackTrace();
-         }
-         if (count.incrementAndGet() % modulo == 0)
-         {
-            double duration = (1.0 * System.currentTimeMillis() - moduloStart) / 1000;
-            moduloStart = System.currentTimeMillis();
-            SoakReceiver.log.info(String.format("received %s messages in %2.2fs (total: %.0fs)",
-                                                modulo,
-                                                duration,
-                                                totalDuration / 1000.0));
-         }
-      }
-   };
-
-   private Session session;
-
-   private Connection connection;
-
-   private SoakReceiver(final Hashtable<String, String> jndiProps, final SoakParams perfParams)
-   {
-      this.jndiProps = jndiProps;
-      this.perfParams = perfParams;
-   }
-
-   public void run() throws Exception
-   {
-      connect();
-
-      boolean runInfinitely = perfParams.getDurationInMinutes() == -1;
-
-      if (!runInfinitely)
-      {
-         Thread.sleep(perfParams.getDurationInMinutes() * SoakBase.TO_MILLIS);
-
-         // send EOF message
-         Message eof = session.createMessage();
-         eof.setStringProperty("eof", SoakReceiver.EOF);
-         listener.onMessage(eof);
-
-         if (connection != null)
-         {
-            connection.close();
-            connection = null;
-         }
-      }
-      else
-      {
-         while (true)
-         {
-            Thread.sleep(500);
-         }
-      }
-   }
-
-   private void disconnect()
-   {
-      if (connection != null)
-      {
-         try
-         {
-            connection.setExceptionListener(null);
-            connection.close();
-         }
-         catch (JMSException e)
-         {
-            e.printStackTrace();
-         }
-         finally
-         {
-            connection = null;
-         }
-      }
-   }
-
-   private void connect()
-   {
-      InitialContext ic = null;
-      try
-      {
-         ic = new InitialContext(jndiProps);
-
-         ConnectionFactory factory = (ConnectionFactory)ic.lookup(perfParams.getConnectionFactoryLookup());
-
-         Destination destination = (Destination)ic.lookup(perfParams.getDestinationLookup());
-
-         connection = factory.createConnection();
-         connection.setExceptionListener(exceptionListener);
-
-         session = connection.createSession(perfParams.isSessionTransacted(),
-                                            perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE
-                                                                 : Session.AUTO_ACKNOWLEDGE);
-
-         MessageConsumer messageConsumer = session.createConsumer(destination);
-         messageConsumer.setMessageListener(listener);
-
-         connection.start();
-      }
-      catch (Exception e)
-      {
-         e.printStackTrace();
-      }
-      finally
-      {
-         try
-         {
-            ic.close();
-         }
-         catch (NamingException e)
-         {
-            e.printStackTrace();
-         }
-      }
-   }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakSender.java
----------------------------------------------------------------------
diff --git a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakSender.java b/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakSender.java
deleted file mode 100644
index 009b27b..0000000
--- a/examples/soak/normal/src/org/hornetq/jms/soak/example/SoakSender.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.soak.example;
-
-import java.util.Hashtable;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.logging.Logger;
-
-import javax.jms.BytesMessage;
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import org.hornetq.utils.TokenBucketLimiter;
-import org.hornetq.utils.TokenBucketLimiterImpl;
-
-public class SoakSender
-{
-   private static final Logger log = Logger.getLogger(SoakSender.class.getName());
-
-   public static void main(final String[] args)
-   {
-      for (int i = 0; i < args.length; i++)
-      {
-         System.out.println(i + ":" + args[i]);
-      }
-      String jndiURL = "jndi://localhost:1099";
-      if (args.length > 0)
-      {
-         jndiURL = args[0];
-      }
-
-      System.out.println("Connecting to JNDI at " + jndiURL);
-      try
-      {
-         String fileName = SoakBase.getPerfFileName(args);
-
-         SoakParams params = SoakBase.getParams(fileName);
-
-         Hashtable<String, String> jndiProps = new Hashtable<String, String>();
-         jndiProps.put("java.naming.provider.url", jndiURL);
-         jndiProps.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
-         jndiProps.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
-
-         final SoakSender sender = new SoakSender(jndiProps, params);
-
-         Runtime.getRuntime().addShutdownHook(new Thread()
-         {
-            @Override
-            public void run()
-            {
-               sender.disconnect();
-            }
-         });
-
-         sender.run();
-      }
-      catch (Exception e)
-      {
-         e.printStackTrace();
-      }
-   }
-
-   private final SoakParams perfParams;
-
-   private final Hashtable<String, String> jndiProps;
-
-   private Connection connection;
-
-   private Session session;
-
-   private MessageProducer producer;
-
-   private final ExceptionListener exceptionListener = new ExceptionListener()
-   {
-      public void onException(final JMSException e)
-      {
-         System.out.println("SoakReconnectableSender.exceptionListener.new ExceptionListener() {...}.onException()");
-         disconnect();
-         connect();
-      }
-
-   };
-
-   private SoakSender(final Hashtable<String, String> jndiProps, final SoakParams perfParams)
-   {
-      this.jndiProps = jndiProps;
-      this.perfParams = perfParams;
-   }
-
-   public void run() throws Exception
-   {
-      connect();
-
-      boolean runInfinitely = perfParams.getDurationInMinutes() == -1;
-
-      BytesMessage message = session.createBytesMessage();
-
-      byte[] payload = SoakBase.randomByteArray(perfParams.getMessageSize());
-
-      message.writeBytes(payload);
-
-      final int modulo = 10000;
-
-      TokenBucketLimiter tbl = perfParams.getThrottleRate() != -1 ? new TokenBucketLimiterImpl(perfParams.getThrottleRate(),
-                                                                                               false)
-                                                                 : null;
-
-      boolean transacted = perfParams.isSessionTransacted();
-      int txBatchSize = perfParams.getBatchSize();
-      boolean display = true;
-
-      long start = System.currentTimeMillis();
-      long moduleStart = start;
-      AtomicLong count = new AtomicLong(0);
-      while (true)
-      {
-         try
-         {
-            producer.send(message);
-            count.incrementAndGet();
-
-            if (transacted)
-            {
-               if (count.longValue() % txBatchSize == 0)
-               {
-                  session.commit();
-               }
-            }
-
-            long totalDuration = System.currentTimeMillis() - start;
-
-            if (display && count.longValue() % modulo == 0)
-            {
-               double duration = (1.0 * System.currentTimeMillis() - moduleStart) / 1000;
-               moduleStart = System.currentTimeMillis();
-               SoakSender.log.info(String.format("sent %s messages in %2.2fs (time: %.0fs)",
-                                                 modulo,
-                                                 duration,
-                                                 totalDuration / 1000.0));
-            }
-
-            if (tbl != null)
-            {
-               tbl.limit();
-            }
-
-            if (!runInfinitely && totalDuration > perfParams.getDurationInMinutes() * SoakBase.TO_MILLIS)
-            {
-               break;
-            }
-         }
-         catch (Exception e)
-         {
-            e.printStackTrace();
-         }
-      }
-
-      SoakSender.log.info(String.format("Sent %s messages in %s minutes", count, perfParams.getDurationInMinutes()));
-      SoakSender.log.info("END OF RUN");
-
-      if (connection != null)
-      {
-         connection.close();
-         connection = null;
-      }
-   }
-
-   private synchronized void disconnect()
-   {
-      if (connection != null)
-      {
-         try
-         {
-            connection.setExceptionListener(null);
-            connection.close();
-         }
-         catch (JMSException e)
-         {
-            e.printStackTrace();
-         }
-         finally
-         {
-            connection = null;
-         }
-      }
-   }
-
-   private void connect()
-   {
-      InitialContext ic = null;
-      try
-      {
-         ic = new InitialContext(jndiProps);
-
-         ConnectionFactory factory = (ConnectionFactory)ic.lookup(perfParams.getConnectionFactoryLookup());
-
-         Destination destination = (Destination)ic.lookup(perfParams.getDestinationLookup());
-
-         connection = factory.createConnection();
-
-         session = connection.createSession(perfParams.isSessionTransacted(),
-                                            perfParams.isDupsOK() ? Session.DUPS_OK_ACKNOWLEDGE
-                                                                 : Session.AUTO_ACKNOWLEDGE);
-
-         producer = session.createProducer(destination);
-
-         producer.setDeliveryMode(perfParams.isDurable() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
-
-         producer.setDisableMessageID(perfParams.isDisableMessageID());
-
-         producer.setDisableMessageTimestamp(perfParams.isDisableTimestamp());
-
-         connection.setExceptionListener(exceptionListener);
-      }
-      catch (Exception e)
-      {
-         e.printStackTrace();
-      }
-      finally
-      {
-         try
-         {
-            ic.close();
-         }
-         catch (NamingException e)
-         {
-            e.printStackTrace();
-         }
-      }
-   }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/pom.xml
----------------------------------------------------------------------
diff --git a/examples/soak/pom.xml b/examples/soak/pom.xml
new file mode 100644
index 0000000..82d1bd7
--- /dev/null
+++ b/examples/soak/pom.xml
@@ -0,0 +1,29 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.hornetq.examples</groupId>
+      <artifactId>hornetq-examples</artifactId>
+      <version>2.5.0-SNAPSHOT</version>
+   </parent>
+
+   <groupId>org.hornetq.example.soak</groupId>
+   <artifactId>soak-examples</artifactId>
+   <packaging>pom</packaging>
+   <name>HornetQ Soak Examples</name>
+
+   <!-- Properties -->
+   <properties>
+      <!--
+      Explicitly declaring the source encoding eliminates the following
+      message: [WARNING] Using platform encoding (UTF-8 actually) to copy
+      filtered resources, i.e. build is platform dependent!
+      -->
+      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+   </properties>
+
+   <modules>
+      <module>normal</module>
+   </modules>
+</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/README
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/README b/examples/soak/tx-restarts/README
deleted file mode 100644
index 42c8655..0000000
--- a/examples/soak/tx-restarts/README
+++ /dev/null
@@ -1,29 +0,0 @@
-****************************************************
-* Soak Test For TX survival over restarts
-****************************************************
-
-Run The Test
-==============
-
-To run the test simply use ./build.sh
-
-It's important that you always clean the data directory before starting the test, as it will validate for sequences generated.
-
-The test will start and stop a server multiple times.
-
-
-Run the server remotely
-=======================
-
-You can start the server directly if you want, you can just start the server as:
-
-./run.sh PATH_TO_HORNETQ/examples/soak/tx-restarts/server0
-
-
-Then you can run the test as:
-
-./build.sh runRemote
-
-
-And you can now kill and restart the server manually as many times as you want.
-

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/build.bat
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/build.bat b/examples/soak/tx-restarts/build.bat
deleted file mode 100644
index 1f414eb..0000000
--- a/examples/soak/tx-restarts/build.bat
+++ /dev/null
@@ -1,13 +0,0 @@
-@echo off
-
-set "OVERRIDE_ANT_HOME=..\..\..\tools\ant"
-
-if exist "..\..\..\src\bin\build.bat" (
-   rem running from TRUNK
-   call ..\..\..\src\bin\build.bat %*
-) else (
-   rem running from the distro
-   call ..\..\..\bin\build.bat %*
-)
-
-set "OVERRIDE_ANT_HOME="

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/build.sh
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/build.sh b/examples/soak/tx-restarts/build.sh
deleted file mode 100644
index 53ffb0d..0000000
--- a/examples/soak/tx-restarts/build.sh
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/sh
-
-OVERRIDE_ANT_HOME=../../tools/ant
-export OVERRIDE_ANT_HOME
-
-if [ -f "../../../src/bin/build.sh" ]; then
-   # running from TRUNK
-   ../../../src/bin/build.sh "$@"
-else
-   # running from the distro
-   ../../bin/build.sh "$@"
-fi
-
-
-

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/build.xml
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/build.xml b/examples/soak/tx-restarts/build.xml
deleted file mode 100644
index 0be1f02..0000000
--- a/examples/soak/tx-restarts/build.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE project [
-      <!ENTITY libraries SYSTEM "../../../thirdparty/libraries.ent">
-      ]>
-<!--
-  ~ Copyright 2009 Red Hat, Inc.
-  ~ Red Hat licenses this file to you under the Apache License, version
-  ~ 2.0 (the "License"); you may not use this file except in compliance
-  ~ with the License.  You may obtain a copy of the License at
-  ~    http://www.apache.org/licenses/LICENSE-2.0
-  ~ Unless required by applicable law or agreed to in writing, software
-  ~ distributed under the License is distributed on an "AS IS" BASIS,
-  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-  ~ implied.  See the License for the specific language governing
-  ~ permissions and limitations under the License.
-  -->
-
-<project default="run" name="TX-Restarts soak test">
-
-   <import file="../../common/build.xml"/>
-   <property file="ant.properties"/>
-   <target name="run">   	
-      <antcall target="runExample">
-         <param name="example.classname" value="org.hornetq.jms.example.TXRestartSoak"/>
-         
-     	   <param name="java-min-memory" value="1G"/>
-     	   <param name="java-max-memory" value="1G"/>
-      </antcall>
-   </target>
-
-   <target name="runRemote">
-      <antcall target="runExample">
-         <param name="example.classname" value="org.hornetq.jms.example.TXRestartSoak"/>
-         <param name="hornetq.example.runServer" value="false"/>
-      </antcall>
-   </target>
-   
-</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/server0/client-jndi.properties
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/server0/client-jndi.properties b/examples/soak/tx-restarts/server0/client-jndi.properties
deleted file mode 100644
index 080524f..0000000
--- a/examples/soak/tx-restarts/server0/client-jndi.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.provider.url=jnp://localhost:1099
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/server0/hornetq-beans.xml b/examples/soak/tx-restarts/server0/hornetq-beans.xml
deleted file mode 100644
index 171d373..0000000
--- a/examples/soak/tx-restarts/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/server0/hornetq-configuration.xml b/examples/soak/tx-restarts/server0/hornetq-configuration.xml
deleted file mode 100644
index 6909bde..0000000
--- a/examples/soak/tx-restarts/server0/hornetq-configuration.xml
+++ /dev/null
@@ -1,65 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-
-
-   <journal-file-size>102400</journal-file-size>
-
-   <!-- Connectors -->
-   <connectors>
-      <connector name="netty-connector">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>         
-      </connector>
-   </connectors>
-   
-   <!-- Acceptors -->
-   <acceptors>
-      <acceptor name="netty-acceptor">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>         
-      </acceptor>
-   </acceptors>
-
-   <address-settings>
-       <address-setting match="jms.queue.#">
-          <max-delivery-attempts>-1</max-delivery-attempts>
-          <!-- <max-size-bytes>335544320000</max-size-bytes> -->
-          <max-size-bytes>33554432</max-size-bytes>
-          <page-size-bytes>16777216</page-size-bytes>
-          <address-full-policy>PAGE</address-full-policy>
-       </address-setting>
-
-   </address-settings>
-
-
-   <diverts>
-      <divert name="div1">
-         <address>jms.queue.inputQueue</address>
-         <forwarding-address>jms.queue.diverted1</forwarding-address>
-         <exclusive>true</exclusive>
-      </divert>
-
-      <divert name="div2">
-         <address>jms.queue.inputQueue</address>
-         <forwarding-address>jms.queue.diverted2</forwarding-address>
-         <exclusive>true</exclusive>
-      </divert>
-   </diverts>
-
-
-
-
-   <!-- Other config -->
-
-   <security-settings>
-      <!--security for example queue-->
-      <security-setting match="jms.queue.#">
-         <permission type="createDurableQueue" roles="guest"/>
-         <permission type="deleteDurableQueue" roles="guest"/>
-         <permission type="createNonDurableQueue" roles="guest"/>
-         <permission type="deleteNonDurableQueue" roles="guest"/>
-         <permission type="consume" roles="guest"/>
-         <permission type="send" roles="guest"/>
-      </security-setting>
-   </security-settings>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/server0/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/server0/hornetq-jms.xml b/examples/soak/tx-restarts/server0/hornetq-jms.xml
deleted file mode 100644
index 67c67e6..0000000
--- a/examples/soak/tx-restarts/server0/hornetq-jms.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-   <!--the connection factory used by the example-->
-   <connection-factory name="ConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty-connector"/>
-      </connectors>
-      <min-large-message-size>100240</min-large-message-size>
-      <entries>
-         <entry name="ConnectionFactory"/>
-      </entries>
-   </connection-factory>
-
-   <!--the queue used by the example-->
-   <queue name="inputQueue">
-      <entry name="/queue/inputQueue"/>
-   </queue>
-
-   <queue name="diverted1">
-      <entry name="/queue/diverted1"/>
-   </queue>
-
-   <queue name="diverted2">
-      <entry name="/queue/diverted2"/>
-   </queue>
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/server0/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/server0/hornetq-users.xml b/examples/soak/tx-restarts/server0/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/examples/soak/tx-restarts/server0/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/server0/jndi.properties
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/server0/jndi.properties b/examples/soak/tx-restarts/server0/jndi.properties
deleted file mode 100644
index e2a9832..0000000
--- a/examples/soak/tx-restarts/server0/jndi.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/src/org/hornetq/jms/example/ClientAbstract.java
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/src/org/hornetq/jms/example/ClientAbstract.java b/examples/soak/tx-restarts/src/org/hornetq/jms/example/ClientAbstract.java
deleted file mode 100644
index 768a722..0000000
--- a/examples/soak/tx-restarts/src/org/hornetq/jms/example/ClientAbstract.java
+++ /dev/null
@@ -1,277 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.example;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Properties;
-import java.util.logging.Logger;
-
-import javax.jms.XAConnection;
-import javax.jms.XAConnectionFactory;
-import javax.jms.XASession;
-import javax.naming.InitialContext;
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-
-import org.hornetq.core.transaction.impl.XidImpl;
-import org.hornetq.utils.UUIDGenerator;
-
-/**
- * WARNING: This is not a sample on how you should handle XA.
- *          You are supposed to use a TransactionManager.
- *          This class is doing the job of a TransactionManager that fits for the purpose of this test only,
- *          however there are many more pitfalls to deal with Transactions.
- *
- *          This is just to stress and soak test Transactions with HornetQ.
- *
- *          And this is dealing with XA directly for the purpose testing only.
- *
- * @author <a href="mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- *
- *
- */
-public abstract class ClientAbstract extends Thread
-{
-
-   // Constants -----------------------------------------------------
-   private static final Logger log = Logger.getLogger(ClientAbstract.class.getName());
-
-   // Attributes ----------------------------------------------------
-
-   protected InitialContext ctx;
-
-   protected XAConnection conn;
-
-   protected XASession sess;
-
-   protected XAResource activeXAResource;
-
-   protected Xid activeXid;
-
-   protected volatile boolean running = true;
-
-   protected volatile int errors = 0;
-
-   /**
-    * A commit was called
-    * case we don't find the Xid, means it was accepted
-    */
-   protected volatile boolean pendingCommit = false;
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   // Public --------------------------------------------------------
-
-   protected InitialContext getContext(final int serverId) throws Exception
-   {
-      String jndiFilename = "server" + serverId + "/client-jndi.properties";
-      File jndiFile = new File(jndiFilename);
-      Properties props = new Properties();
-      FileInputStream inStream = null;
-      try
-      {
-         inStream = new FileInputStream(jndiFile);
-         props.load(inStream);
-      }
-      finally
-      {
-         if (inStream != null)
-         {
-            inStream.close();
-         }
-      }
-      return new InitialContext(props);
-
-   }
-
-   public XAConnection getConnection()
-   {
-      return conn;
-   }
-
-   public int getErrorsCount()
-   {
-      return errors;
-   }
-
-   public final void connect()
-   {
-      while (running)
-      {
-         try
-         {
-            disconnect();
-
-            ctx = getContext(0);
-
-            XAConnectionFactory cf = (XAConnectionFactory)ctx.lookup("/ConnectionFactory");
-
-            conn = cf.createXAConnection();
-
-            sess = conn.createXASession();
-
-            activeXAResource = sess.getXAResource();
-
-            if (activeXid != null)
-            {
-               synchronized (ClientAbstract.class)
-               {
-                  Xid[] xids = activeXAResource.recover(XAResource.TMSTARTRSCAN);
-                  boolean found = false;
-                  for (Xid recXid : xids)
-                  {
-                     if (recXid.equals(activeXid))
-                     {
-                        // System.out.println("Calling commit after a prepare on " + this);
-                        found = true;
-                        callCommit();
-                     }
-                  }
-
-                  if (!found)
-                  {
-                     if (pendingCommit)
-                     {
-                        System.out.println("Doing a commit based on a pending commit on " + this);
-                        onCommit();
-                     }
-                     else
-                     {
-                        System.out.println("Doing a rollback on " + this);
-                        onRollback();
-                     }
-
-                     activeXid = null;
-                     pendingCommit = false;
-                  }
-               }
-            }
-
-            connectClients();
-
-            break;
-         }
-         catch (Exception e)
-         {
-            ClientAbstract.log.warning("Can't connect to server, retrying");
-            disconnect();
-            try
-            {
-               Thread.sleep(1000);
-            }
-            catch (InterruptedException ignored)
-            {
-               // if an interruption was sent, we will respect it and leave the loop
-               break;
-            }
-         }
-      }
-   }
-
-   @Override
-   public void run()
-   {
-      connect();
-   }
-
-   protected void callCommit() throws Exception
-   {
-      pendingCommit = true;
-      activeXAResource.commit(activeXid, false);
-      pendingCommit = false;
-      activeXid = null;
-      onCommit();
-   }
-
-   protected void callPrepare() throws Exception
-   {
-      activeXAResource.prepare(activeXid);
-   }
-
-   public void beginTX() throws Exception
-   {
-      activeXid = newXID();
-
-      activeXAResource.start(activeXid, XAResource.TMNOFLAGS);
-   }
-
-   public void endTX() throws Exception
-   {
-      activeXAResource.end(activeXid, XAResource.TMSUCCESS);
-      callPrepare();
-      callCommit();
-   }
-
-   public void setRunning(final boolean running)
-   {
-      this.running = running;
-   }
-
-   /**
-    * @return
-    */
-   private XidImpl newXID()
-   {
-      return new XidImpl("tst".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-   }
-
-   protected abstract void connectClients() throws Exception;
-
-   protected abstract void onCommit();
-
-   protected abstract void onRollback();
-
-   public void disconnect()
-   {
-      try
-      {
-         if (conn != null)
-         {
-            conn.close();
-         }
-      }
-      catch (Exception ignored)
-      {
-         ignored.printStackTrace();
-      }
-
-      try
-      {
-         if (ctx != null)
-         {
-            ctx.close();
-         }
-      }
-      catch (Exception ignored)
-      {
-         ignored.printStackTrace();
-      }
-
-      ctx = null;
-      conn = null;
-      // it's not necessary to close the session as conn.close() will already take care of that
-      sess = null;
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/src/org/hornetq/jms/example/Receiver.java
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/src/org/hornetq/jms/example/Receiver.java b/examples/soak/tx-restarts/src/org/hornetq/jms/example/Receiver.java
deleted file mode 100644
index 5d484f1..0000000
--- a/examples/soak/tx-restarts/src/org/hornetq/jms/example/Receiver.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.example;
-
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.Queue;
-
-import org.hornetq.utils.ReusableLatch;
-
-/**
- * A Receiver
- *
- * @author <a href="mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- *
- *
- */
-public class Receiver extends ClientAbstract
-{
-
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   private Queue queue;
-
-   // We should leave some messages on paging. We don't want to consume all for this test
-   private final Semaphore minConsume = new Semaphore(0);
-
-   private final ReusableLatch latchMax = new ReusableLatch(0);
-
-   private static final int MAX_DIFF = 10000;
-
-   // The difference between producer and consuming
-   private final AtomicInteger currentDiff = new AtomicInteger(0);
-
-   private final String queueJNDI;
-
-   protected long msgs = 0;
-
-   protected int pendingMsgs = 0;
-
-   protected int pendingSemaphores = 0;
-
-   protected MessageConsumer cons;
-
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   public Receiver(String queueJNDI)
-   {
-      super();
-      this.queueJNDI = queueJNDI;
-   }
-
-   // Public --------------------------------------------------------
-
-   public void run()
-   {
-      super.run();
-
-      while (running)
-      {
-         try
-         {
-            beginTX();
-
-            for (int i = 0 ; i < 1000; i++)
-            {
-               Message msg = cons.receive(5000);
-               if (msg == null)
-               {
-                  break;
-               }
-
-               if (msg.getLongProperty("count") != msgs + pendingMsgs)
-               {
-                  errors++;
-                  System.out.println("count should be " + (msgs + pendingMsgs) + " when it was " + msg.getLongProperty("count") + " on " + queueJNDI);
-               }
-
-               pendingMsgs++;
-               if (!minConsume.tryAcquire(1, 5, TimeUnit.SECONDS))
-               {
-                  break;
-               }
-
-            }
-
-            endTX();
-         }
-         catch (Exception e)
-         {
-            connect();
-         }
-
-
-      }
-   }
-
-   /* (non-Javadoc)
-    * @see org.hornetq.jms.example.ClientAbstract#connectClients()
-    */
-   @Override
-   protected void connectClients() throws Exception
-   {
-
-      queue = (Queue)ctx.lookup(queueJNDI);
-
-      cons = sess.createConsumer(queue);
-
-      conn.start();
-   }
-
-   /* (non-Javadoc)
-    * @see org.hornetq.jms.example.ClientAbstract#onCommit()
-    */
-   @Override
-   protected void onCommit()
-   {
-      msgs += pendingMsgs;
-      this.currentDiff.addAndGet(-pendingMsgs);
-      latchMax.countDown(pendingMsgs);
-      pendingMsgs = 0;
-      System.out.println("Commit on consumer " + queueJNDI + ", msgs=" + msgs + " currentDiff = " + currentDiff);
-   }
-
-   /* (non-Javadoc)
-    * @see org.hornetq.jms.example.ClientAbstract#onRollback()
-    */
-   @Override
-   protected void onRollback()
-   {
-      System.out.println("Rollback on consumer " + queueJNDI + ", msgs=" + msgs);
-      minConsume.release(pendingMsgs);
-      pendingMsgs = 0;
-   }
-
-   public String toString()
-   {
-      return "Receiver::" + this.queueJNDI + ", msgs=" + msgs + ", pending=" + pendingMsgs;
-   }
-
-   /**
-    * @param pendingMsgs2
-    */
-   public void messageProduced(int producedMessages)
-   {
-      minConsume.release(producedMessages);
-      currentDiff.addAndGet(producedMessages);
-      System.out.println("Msg produced on " + this.queueJNDI + ", currentDiff = " + currentDiff);
-      if (currentDiff.get() > MAX_DIFF)
-      {
-         System.out.println("Holding producer for 5 seconds");
-         latchMax.setCount(currentDiff.get() - MAX_DIFF);
-         try
-         {
-            latchMax.await(5, TimeUnit.SECONDS);
-         }
-         catch (InterruptedException e)
-         {
-            e.printStackTrace();
-         }
-      }
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-
-}


[15/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/settings/RepositoryTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/settings/RepositoryTest.java b/hornetq-server/src/test/java/org/hornetq/core/settings/RepositoryTest.java
new file mode 100644
index 0000000..7875add
--- /dev/null
+++ b/hornetq-server/src/test/java/org/hornetq/core/settings/RepositoryTest.java
@@ -0,0 +1,281 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.settings;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.hornetq.core.security.Role;
+import org.hornetq.core.settings.impl.HierarchicalObjectRepository;
+import org.hornetq.tests.util.UnitTestCase;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author <a href="ataylor@redhat.com">Andy Taylor</a>
+ */
+public class RepositoryTest extends UnitTestCase
+{
+   HierarchicalRepository<HashSet<Role>> securityRepository;
+
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      super.setUp();
+
+      securityRepository = new HierarchicalObjectRepository<>();
+   }
+
+   @Test
+   public void testDefault()
+   {
+      securityRepository.setDefault(new HashSet<Role>());
+      HashSet<Role> roles = securityRepository.getMatch("queues.something");
+
+      Assert.assertEquals(roles.size(), 0);
+   }
+
+   @Test
+   public void testMatchingDocs() throws Throwable
+   {
+      HierarchicalObjectRepository<String> repo = new HierarchicalObjectRepository<>();
+
+      repo.addMatch("a.b.#", "ab#");
+      repo.addMatch("a.b.d.#", "abd#");
+      repo.addMatch("#", "root");
+
+      Assert.assertEquals("ab#", repo.getMatch("a.b"));
+      Assert.assertEquals("ab#", repo.getMatch("a.b.c"));
+      Assert.assertEquals("abd#", repo.getMatch("a.b.d.lll"));
+      Assert.assertEquals("root", repo.getMatch("z.z.z.z.z"));
+   }
+
+   @Test
+   public void testSingleMatch()
+   {
+      securityRepository.addMatch("queues.*", new HashSet<Role>());
+      HashSet<Role> hashSet = securityRepository.getMatch("queues.something");
+      Assert.assertEquals(hashSet.size(), 0);
+   }
+
+   @Test
+   public void testSingletwo()
+   {
+      securityRepository.addMatch("queues.another.aq.*", new HashSet<Role>());
+      HashSet<Role> roles = new HashSet<Role>(2);
+      roles.add(new Role("test1", true, true, true, true, true, true, true));
+      roles.add(new Role("test2", true, true, true, true, true, true, true));
+      securityRepository.addMatch("queues.aq", roles);
+      HashSet<Role> roles2 = new HashSet<Role>(2);
+      roles2.add(new Role("test1", true, true, true, true, true, true, true));
+      roles2.add(new Role("test2", true, true, true, true, true, true, true));
+      roles2.add(new Role("test3", true, true, true, true, true, true, true));
+      securityRepository.addMatch("queues.another.andanother", roles2);
+
+      HashSet<Role> hashSet = securityRepository.getMatch("queues.another.andanother");
+      Assert.assertEquals(hashSet.size(), 3);
+   }
+
+   @Test
+   public void testWithoutWildcard()
+   {
+      securityRepository.addMatch("queues.1.*", new HashSet<Role>());
+      HashSet<Role> roles = new HashSet<Role>(2);
+      roles.add(new Role("test1", true, true, true, true, true, true, true));
+      roles.add(new Role("test2", true, true, true, true, true, true, true));
+      securityRepository.addMatch("queues.2.aq", roles);
+      HashSet<Role> hashSet = securityRepository.getMatch("queues.2.aq");
+      Assert.assertEquals(hashSet.size(), 2);
+   }
+
+   @Test
+   public void testMultipleWildcards()
+   {
+      HierarchicalRepository<String> repository = new HierarchicalObjectRepository<String>();
+      repository.addMatch("#", "#");
+      repository.addMatch("a", "a");
+      repository.addMatch("a.#", "a.#");
+      repository.addMatch("a.*", "a.*");
+      repository.addMatch("a.b.c", "a.b.c");
+      repository.addMatch("a.*.c", "a.*.c");
+      repository.addMatch("a.d.c", "a.d.c");
+      repository.addMatch("a.b.#", "a.b.#");
+      repository.addMatch("a.b", "a.b");
+      repository.addMatch("a.b.c.#", "a.b.c.#");
+      repository.addMatch("a.b.c.d", "a.b.c.d");
+      repository.addMatch("a.*.*.d", "a.*.*.d");
+      repository.addMatch("a.*.d.#", "a.*.d.#");
+      String val = repository.getMatch("a");
+      Assert.assertEquals("a", val);
+      val = repository.getMatch("a.b");
+      Assert.assertEquals("a.b", val);
+      val = repository.getMatch("a.x");
+      Assert.assertEquals("a.*", val);
+      val = repository.getMatch("a.b.x");
+      Assert.assertEquals("a.b.#", val);
+      val = repository.getMatch("a.b.c");
+      Assert.assertEquals("a.b.c", val);
+      val = repository.getMatch("a.d.c");
+      Assert.assertEquals("a.d.c", val);
+      val = repository.getMatch("a.x.c");
+      Assert.assertEquals("a.*.c", val);
+      val = repository.getMatch("a.b.c.d");
+      Assert.assertEquals("a.b.c.d", val);
+      val = repository.getMatch("a.x.c.d");
+      Assert.assertEquals("a.*.*.d", val);
+      val = repository.getMatch("a.b.x.d");
+      Assert.assertEquals("a.*.*.d", val);
+      val = repository.getMatch("a.d.x.d");
+      Assert.assertEquals("a.*.*.d", val);
+      val = repository.getMatch("a.d.d.g");
+      Assert.assertEquals("a.*.d.#", val);
+      val = repository.getMatch("zzzz.z.z.z.d.r.g.f.sd.s.fsdfd.fsdfs");
+      Assert.assertEquals("#", val);
+   }
+
+   @Test
+   public void testRepositoryMerge()
+   {
+      HierarchicalRepository<DummyMergeable> repository = new HierarchicalObjectRepository<DummyMergeable>();
+      repository.addMatch("#", new DummyMergeable(1));
+      repository.addMatch("a.#", new DummyMergeable(2));
+      repository.addMatch("b.#", new DummyMergeable(3));
+      repository.addMatch("a.b.#", new DummyMergeable(4));
+      repository.addMatch("b.c.#", new DummyMergeable(5));
+      repository.addMatch("a.b.c.#", new DummyMergeable(6));
+      repository.addMatch("a.b.*.d", new DummyMergeable(7));
+      repository.addMatch("a.b.c.*", new DummyMergeable(8));
+      repository.getMatch("a.b.c.d");
+      Assert.assertEquals(5, DummyMergeable.timesMerged);
+      Assert.assertTrue(DummyMergeable.contains(1));
+      Assert.assertTrue(DummyMergeable.contains(2));
+      Assert.assertTrue(DummyMergeable.contains(4));
+      Assert.assertTrue(DummyMergeable.contains(7));
+      Assert.assertTrue(DummyMergeable.contains(8));
+      DummyMergeable.reset();
+      repository.getMatch("a.b.c");
+      Assert.assertEquals(3, DummyMergeable.timesMerged);
+      Assert.assertTrue(DummyMergeable.contains(1));
+      Assert.assertTrue(DummyMergeable.contains(2));
+      Assert.assertTrue(DummyMergeable.contains(4));
+      DummyMergeable.reset();
+      repository.getMatch("z");
+      Assert.assertEquals(0, DummyMergeable.timesMerged);
+      DummyMergeable.reset();
+   }
+
+
+   @Test
+   public void testAddListener()
+   {
+      HierarchicalRepository<String> repository = new HierarchicalObjectRepository<String>();
+      repository.addMatch("#", "1");
+      repository.addMatch("B", "2");
+
+      final AtomicInteger called = new AtomicInteger(0);
+      repository.registerListener(new HierarchicalRepositoryChangeListener()
+      {
+         @Override
+         public void onChange()
+         {
+            called.incrementAndGet();
+         }
+      });
+
+      assertEquals(1, called.get());
+
+      repository.disableListeners();
+
+      repository.addMatch("C", "3");
+
+      assertEquals(1, called.get());
+
+      repository.enableListeners();
+
+      assertEquals(2, called.get());
+
+      repository.addMatch("D", "4");
+
+      assertEquals(3, called.get());
+
+      repository.removeMatch("D");
+
+      assertEquals(4, called.get());
+
+      repository.disableListeners();
+
+      repository.removeMatch("C");
+
+      assertEquals(4, called.get());
+   }
+
+
+   @Test
+   public void testIllegalMatches()
+   {
+      HierarchicalRepository<String> repository = new HierarchicalObjectRepository<String>();
+      try
+      {
+         repository.addMatch("hjhjhjhjh.#.hhh", "test");
+         fail("expected exception");
+      }
+      catch (IllegalArgumentException e)
+      {
+         // pass
+      }
+      try
+      {
+         repository.addMatch(null, "test");
+         fail("expected exception");
+      }
+      catch (IllegalArgumentException e)
+      {
+         // pass
+      }
+   }
+
+   static class DummyMergeable implements Mergeable
+   {
+      static int timesMerged = 0;
+
+      static ArrayList<Integer> merged = new ArrayList<Integer>();
+
+      private final Integer id;
+
+      static void reset()
+      {
+         DummyMergeable.timesMerged = 0;
+         DummyMergeable.merged = new ArrayList<Integer>();
+      }
+
+      static boolean contains(final Integer i)
+      {
+         return DummyMergeable.merged.contains(i);
+      }
+
+      public DummyMergeable(final Integer id)
+      {
+         this.id = id;
+      }
+
+      public void merge(final Object merged)
+      {
+         DummyMergeable.timesMerged++;
+         DummyMergeable.merged.add(id);
+         DummyMergeable.merged.add(((DummyMergeable)merged).id);
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/tests/util/ColocatedHornetQServer.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/tests/util/ColocatedHornetQServer.java b/hornetq-server/src/test/java/org/hornetq/tests/util/ColocatedHornetQServer.java
index e8a118e..ecaca04 100644
--- a/hornetq-server/src/test/java/org/hornetq/tests/util/ColocatedHornetQServer.java
+++ b/hornetq-server/src/test/java/org/hornetq/tests/util/ColocatedHornetQServer.java
@@ -58,7 +58,7 @@ public class ColocatedHornetQServer extends HornetQServerImpl
 
    @Override
    protected NodeManager
-   createNodeManager(final String directory, final String nodeGroupName, boolean replicatingBackup)
+   createNodeManager(final String directory, boolean replicatingBackup)
    {
       if (replicatingBackup)
       {
@@ -76,12 +76,10 @@ public class ColocatedHornetQServer extends HornetQServerImpl
       {
          if (backup)
          {
-            nodeManagerBackup.setNodeGroupName(nodeGroupName);
             return nodeManagerBackup;
          }
          else
          {
-            nodeManagerLive.setNodeGroupName(nodeGroupName);
             return nodeManagerLive;
          }
       }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/tests/util/InVMNodeManagerServer.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/tests/util/InVMNodeManagerServer.java b/hornetq-server/src/test/java/org/hornetq/tests/util/InVMNodeManagerServer.java
index f8ab8c4..b1e45f1 100644
--- a/hornetq-server/src/test/java/org/hornetq/tests/util/InVMNodeManagerServer.java
+++ b/hornetq-server/src/test/java/org/hornetq/tests/util/InVMNodeManagerServer.java
@@ -64,9 +64,8 @@ public final class InVMNodeManagerServer extends HornetQServerImpl
    }
 
    @Override
-   protected NodeManager createNodeManager(final String directory, final String nodeGroupName, boolean replicatingBackup)
+   protected NodeManager createNodeManager(final String directory, boolean replicatingBackup)
    {
-      nodeManager.setNodeGroupName(nodeGroupName);
       return nodeManager;
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/tests/util/ServiceTestBase.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/tests/util/ServiceTestBase.java b/hornetq-server/src/test/java/org/hornetq/tests/util/ServiceTestBase.java
index 14425e9..3706c1b 100644
--- a/hornetq-server/src/test/java/org/hornetq/tests/util/ServiceTestBase.java
+++ b/hornetq-server/src/test/java/org/hornetq/tests/util/ServiceTestBase.java
@@ -61,7 +61,9 @@ import org.hornetq.core.server.NodeManager;
 import org.hornetq.core.server.Queue;
 import org.hornetq.core.server.cluster.ClusterConnection;
 import org.hornetq.core.server.cluster.RemoteQueueBinding;
+import org.hornetq.core.server.impl.Activation;
 import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.SharedNothingBackupActivation;
 import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
 import org.hornetq.core.settings.impl.AddressSettings;
 import org.hornetq.spi.core.security.HornetQSecurityManager;
@@ -337,7 +339,7 @@ public abstract class ServiceTestBase extends UnitTestCase
          fail("server didn't start: " + server);
       }
 
-      if (!server.getConfiguration().getHAPolicy().isBackup())
+      if (!server.getHAPolicy().isBackup())
       {
          if (!server.waitForActivation(wait, TimeUnit.MILLISECONDS))
             fail("Server didn't initialize: " + server);
@@ -383,10 +385,35 @@ public abstract class ServiceTestBase extends UnitTestCase
       final HornetQServerImpl actualServer = (HornetQServerImpl) backup;
       final long toWait = seconds * 1000;
       final long time = System.currentTimeMillis();
+      int loop = 0;
       while (true)
       {
+         Activation activation = actualServer.getActivation();
+         boolean isReplicated = !backup.getHAPolicy().isSharedStore();
+         boolean isRemoteUpToDate = true;
+         if (isReplicated)
+         {
+            if (activation instanceof SharedNothingBackupActivation)
+            {
+               isRemoteUpToDate = ((SharedNothingBackupActivation) activation).isRemoteBackupUpToDate();
+            }
+            else
+            {
+               //we may have already failed over and changed the Activation
+               if (actualServer.isStarted())
+               {
+                  //let it fail a few time to have time to start stopping in the case of waiting to failback
+                  isRemoteUpToDate = loop++ > 10;
+               }
+               //we could be waiting to failback or restart if the server is stopping
+               else
+               {
+                  isRemoteUpToDate = false;
+               }
+            }
+         }
          if ((sessionFactory == null || sessionFactory.getBackupConnector() != null) &&
-            (actualServer.isRemoteBackupUpToDate() || !waitForSync) &&
+               (isRemoteUpToDate || !waitForSync) &&
             (!waitForSync || actualServer.getBackupManager() != null && actualServer.getBackupManager().isBackupAnnounced()))
          {
             break;
@@ -394,7 +421,7 @@ public abstract class ServiceTestBase extends UnitTestCase
          if (System.currentTimeMillis() > (time + toWait))
          {
             fail("backup started? (" + actualServer.isStarted() + "). Finished synchronizing (" +
-                    actualServer.isRemoteBackupUpToDate() + "). SessionFactory!=null ? " + (sessionFactory != null) +
+                  (activation) + "). SessionFactory!=null ? " + (sessionFactory != null) +
                     " || sessionFactory.getBackupConnector()==" +
                     (sessionFactory != null ? sessionFactory.getBackupConnector() : "not-applicable"));
          }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/tests/util/SingleServerTestBase.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/tests/util/SingleServerTestBase.java b/hornetq-server/src/test/java/org/hornetq/tests/util/SingleServerTestBase.java
index 6fde9f6..06f2e6b 100644
--- a/hornetq-server/src/test/java/org/hornetq/tests/util/SingleServerTestBase.java
+++ b/hornetq-server/src/test/java/org/hornetq/tests/util/SingleServerTestBase.java
@@ -45,8 +45,8 @@ public abstract class SingleServerTestBase extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration configuration = createDefaultConfig();
-      configuration.setSecurityEnabled(false);
+      Configuration configuration = createDefaultConfig()
+         .setSecurityEnabled(false);
       server = createServer(false, configuration);
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/tests/util/UnitTestCase.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/tests/util/UnitTestCase.java b/hornetq-server/src/test/java/org/hornetq/tests/util/UnitTestCase.java
index 0e47347..a174014 100644
--- a/hornetq-server/src/test/java/org/hornetq/tests/util/UnitTestCase.java
+++ b/hornetq-server/src/test/java/org/hornetq/tests/util/UnitTestCase.java
@@ -218,25 +218,32 @@ public abstract class UnitTestCase extends CoreUnitTestCase
       }
    }
 
-   protected static final void basicClusterConnectionConfig(Configuration mainConfig, String connectorName,
-                                                            String... connectors)
+   protected static final ClusterConnectionConfiguration basicClusterConnectionConfig(String connectorName,
+                                                                                      String... connectors)
    {
       ArrayList<String> connectors0 = new ArrayList<String>();
       for (String c : connectors)
       {
          connectors0.add(c);
       }
-      basicClusterConnectionConfig(mainConfig, connectorName, connectors0);
+      return basicClusterConnectionConfig(connectorName, connectors0);
    }
 
-   protected static final void basicClusterConnectionConfig(Configuration mainConfig,
-                                                            String connectorName,
-                                                            List<String> connectors)
+   protected static final ClusterConnectionConfiguration basicClusterConnectionConfig(String connectorName,
+                                                                                      List<String> connectors)
    {
-      ClusterConnectionConfiguration ccc =
-         new ClusterConnectionConfiguration("cluster1", "jms", connectorName, 10, false, true, 1, 1, connectors,
-                                            false);
-      mainConfig.getClusterConfigurations().add(ccc);
+      ClusterConnectionConfiguration ccc = new ClusterConnectionConfiguration()
+         .setName("cluster1")
+         .setAddress("jms")
+         .setConnectorName(connectorName)
+         .setRetryInterval(1000)
+         .setDuplicateDetection(false)
+         .setForwardWhenNoConsumers(true)
+         .setMaxHops(1)
+         .setConfirmationWindowSize(1)
+         .setStaticConnectors(connectors);
+
+      return ccc;
    }
 
    protected Configuration createDefaultConfig(final int index,
@@ -275,72 +282,65 @@ public abstract class UnitTestCase extends CoreUnitTestCase
     */
    protected final ConfigurationImpl createBasicConfig(final int serverID)
    {
-      ConfigurationImpl configuration = new ConfigurationImpl();
-      configuration.setSecurityEnabled(false);
-      configuration.setJournalMinFiles(2);
-      configuration.setJournalFileSize(100 * 1024);
-
-      configuration.setJournalType(getDefaultJournalType());
+      ConfigurationImpl configuration = new ConfigurationImpl()
+         .setSecurityEnabled(false)
+         .setJournalMinFiles(2)
+         .setJournalFileSize(100 * 1024)
+         .setJournalType(getDefaultJournalType())
+         .setJournalDirectory(getJournalDir(serverID, false))
+         .setBindingsDirectory(getBindingsDir(serverID, false))
+         .setPagingDirectory(getPageDir(serverID, false))
+         .setLargeMessagesDirectory(getLargeMessagesDir(serverID, false))
+         .setJournalCompactMinFiles(0)
+         .setJournalCompactPercentage(0)
+         .setClusterPassword(CLUSTER_PASSWORD);
 
-      configuration.setJournalDirectory(getJournalDir(serverID, false));
-      configuration.setBindingsDirectory(getBindingsDir(serverID, false));
-      configuration.setPagingDirectory(getPageDir(serverID, false));
-      configuration.setLargeMessagesDirectory(getLargeMessagesDir(serverID, false));
-
-      configuration.setJournalCompactMinFiles(0);
-      configuration.setJournalCompactPercentage(0);
-      configuration.setClusterPassword(CLUSTER_PASSWORD);
       return configuration;
    }
 
    public static final ConfigurationImpl createBasicConfig(final String testDir, final int serverID)
    {
-      ConfigurationImpl configuration = new ConfigurationImpl();
-      configuration.setSecurityEnabled(false);
-      configuration.setJournalMinFiles(2);
-      configuration.setJournalFileSize(100 * 1024);
-
-      configuration.setJournalType(getDefaultJournalType());
+      ConfigurationImpl configuration = new ConfigurationImpl()
+         .setSecurityEnabled(false)
+         .setJournalMinFiles(2)
+         .setJournalFileSize(100 * 1024)
+         .setJournalType(getDefaultJournalType())
+         .setJournalDirectory(getJournalDir(testDir, serverID, false))
+         .setBindingsDirectory(getBindingsDir(testDir, serverID, false))
+         .setPagingDirectory(getPageDir(testDir, serverID, false))
+         .setLargeMessagesDirectory(getLargeMessagesDir(testDir, serverID, false))
+         .setJournalCompactMinFiles(0)
+         .setJournalCompactPercentage(0)
+         .setClusterPassword(CLUSTER_PASSWORD);
 
-      configuration.setJournalDirectory(getJournalDir(testDir, serverID, false));
-      configuration.setBindingsDirectory(getBindingsDir(testDir, serverID, false));
-      configuration.setPagingDirectory(getPageDir(testDir, serverID, false));
-      configuration.setLargeMessagesDirectory(getLargeMessagesDir(testDir, serverID, false));
-
-      configuration.setJournalCompactMinFiles(0);
-      configuration.setJournalCompactPercentage(0);
-      configuration.setClusterPassword(CLUSTER_PASSWORD);
       return configuration;
    }
 
    public static final ConfigurationImpl createBasicConfigNoDataFolder()
    {
-      ConfigurationImpl configuration = new ConfigurationImpl();
-      configuration.setSecurityEnabled(false);
-
-      configuration.setJournalType(getDefaultJournalType());
+      ConfigurationImpl configuration = new ConfigurationImpl()
+         .setSecurityEnabled(false)
+         .setJournalType(getDefaultJournalType())
+         .setJournalCompactMinFiles(0)
+         .setJournalCompactPercentage(0)
+         .setClusterPassword(CLUSTER_PASSWORD);
 
-      configuration.setJournalCompactMinFiles(0);
-      configuration.setJournalCompactPercentage(0);
-      configuration.setClusterPassword(CLUSTER_PASSWORD);
       return configuration;
    }
 
-   protected Configuration
-   createDefaultConfig(final Map<String, Object> params, final String... acceptors) throws Exception
+   protected Configuration createDefaultConfig(final Map<String, Object> params, final String... acceptors) throws Exception
    {
-      ConfigurationImpl configuration = createBasicConfig(-1);
-
-      configuration.setFileDeploymentEnabled(false);
-      configuration.setJMXManagementEnabled(false);
-
-      configuration.getAcceptorConfigurations().clear();
+      ConfigurationImpl configuration = createBasicConfig(-1)
+         .setFileDeploymentEnabled(false)
+         .setJMXManagementEnabled(false)
+         .clearAcceptorConfigurations();
 
       for (String acceptor : acceptors)
       {
          TransportConfiguration transportConfig = new TransportConfiguration(acceptor, params);
-         configuration.getAcceptorConfigurations().add(transportConfig);
+         configuration.addAcceptorConfiguration(transportConfig);
       }
+
       return configuration;
    }
 
@@ -1180,6 +1180,12 @@ public abstract class UnitTestCase extends CoreUnitTestCase
             checkThread = true;
          }
 
+         if (Thread.currentThread().getContextClassLoader() == null)
+         {
+            Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
+            fail("Thread Context ClassLoader was set to null at some point before this test. We will set to this.getClass().getClassLoader(), but you are supposed to fix your tests");
+         }
+
          checkFilesUsage();
       }
    }
@@ -1311,7 +1317,7 @@ public abstract class UnitTestCase extends CoreUnitTestCase
       {
          return true;
       }
-      else if (isSystemThread && threadName.equals("process reaper"))
+      else if ((javaVendor.contains("IBM") || isSystemThread) && threadName.equals("process reaper"))
       {
          return true;
       }
@@ -1659,12 +1665,25 @@ public abstract class UnitTestCase extends CoreUnitTestCase
 
       for (QueueBinding qBinding : bindings)
       {
-         messageCount += qBinding.getQueue().getMessageCount();
+         qBinding.getQueue().flushExecutor();
+         messageCount += getMessageCount(qBinding.getQueue());
       }
 
       return messageCount;
    }
 
+   protected int getMessageCount(final Queue queue)
+   {
+      queue.flushExecutor();
+      return (int)queue.getMessageCount();
+   }
+
+   protected int getMessagesAdded(final Queue queue)
+   {
+      queue.flushExecutor();
+      return (int)queue.getMessagesAdded();
+   }
+
    protected List<QueueBinding> getLocalQueueBindings(final PostOffice postOffice, final String address) throws Exception
    {
       ArrayList<QueueBinding> bindingsFound = new ArrayList<QueueBinding>();
@@ -1748,13 +1767,23 @@ public abstract class UnitTestCase extends CoreUnitTestCase
 
    protected final ServerLocator createNonHALocator(final boolean isNetty)
    {
-      ServerLocator locatorWithoutHA =
-         isNetty
-            ? HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY))
-            : HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+      ServerLocator locatorWithoutHA = internalCreateNonHALocator(isNetty);
       return addServerLocator(locatorWithoutHA);
    }
 
+   /**
+    * Creates the Locator without adding it to the list where the tearDown will take place
+    * This is because we don't want it closed in certain tests where we are issuing failures
+    * @param isNetty
+    * @return
+    */
+   protected ServerLocator internalCreateNonHALocator(boolean isNetty)
+   {
+      return isNetty
+         ? HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY))
+         : HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+   }
+
    protected static final void stopComponent(HornetQComponent component)
    {
       if (component == null)
@@ -2006,7 +2035,7 @@ public abstract class UnitTestCase extends CoreUnitTestCase
    }
 
    // This can be used to interrupt a thread if it takes more than timeoutMilliseconds
-   public void runWithTimeout(final RunnerWithEX runner, final long timeoutMilliseconds) throws Throwable
+   public boolean runWithTimeout(final RunnerWithEX runner, final long timeoutMilliseconds) throws Throwable
    {
 
       class ThreadRunner extends Thread
@@ -2044,6 +2073,11 @@ public abstract class UnitTestCase extends CoreUnitTestCase
          runnerThread.join(timeoutMilliseconds);
          if (runnerThread.isAlive())
          {
+            System.err.println("Thread still running, interrupting it now:");
+            for (Object t : runnerThread.getStackTrace())
+            {
+               System.err.println(t);
+            }
             hadToInterrupt = true;
             runnerThread.interrupt();
          }
@@ -2051,13 +2085,13 @@ public abstract class UnitTestCase extends CoreUnitTestCase
 
       if (runnerThread.t != null)
       {
+         runnerThread.t.printStackTrace();
          throw runnerThread.t;
       }
 
-      if (hadToInterrupt)
-      {
-         fail("Test would have hung. We had to issue an interrupt!");
-      }
+      // we are returning true if it ran ok.
+      // had to Interrupt is exactly the opposite of what we are returning
+      return !hadToInterrupt;
    }
 
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/ConfigurationTest-full-config.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/ConfigurationTest-full-config.xml b/hornetq-server/src/test/resources/ConfigurationTest-full-config.xml
index 1320545..b7545ea 100644
--- a/hornetq-server/src/test/resources/ConfigurationTest-full-config.xml
+++ b/hornetq-server/src/test/resources/ConfigurationTest-full-config.xml
@@ -161,33 +161,18 @@
              <discovery-group-ref discovery-group-name="dg1"/>
          </bridge>
       </bridges>
-      <ha-policy template="COLOCATED_REPLICATED">
-         <policy-type>COLOCATED_REPLICATED</policy-type>
-         <request-backup>true</request-backup>
-         <backup-request-retries>33</backup-request-retries>
-         <backup-request-retry-interval>1234</backup-request-retry-interval>
-         <max-backups>12</max-backups>
-         <backup-port-offset>1002</backup-port-offset>
-         <backup-strategy>SCALE_DOWN</backup-strategy>
-         <scale-down-discovery-group>wahey!</scale-down-discovery-group>
-         <scale-down-group-name>boo!</scale-down-group-name>
-         <scale-down-connectors>
-            <connector-ref>sd-connector1</connector-ref>
-            <connector-ref>sd-connector2</connector-ref>
-         </scale-down-connectors>
-         <backup-group-name>backupGroupName</backup-group-name>
-         <remote-connectors>
-            <connector-ref>remote-connector1</connector-ref>
-            <connector-ref>remote-connector2</connector-ref>
-         </remote-connectors>
-         <check-for-live-server>true</check-for-live-server>
-         <allow-failback>false</allow-failback>
-         <failback-delay>10000</failback-delay>
-         <failover-on-shutdown>true</failover-on-shutdown>
-         <replication-clustername>replicationClustername</replication-clustername>
-         <scale-down-clustername>scaleDownClustername</scale-down-clustername>
-         <max-saved-replicated-journals-size>3</max-saved-replicated-journals-size>
-         <scale-down>true</scale-down>
+      <ha-policy>
+         <!--only one of the following-->
+         <!--on server shutdown scale down to another live server-->
+         <live-only>
+            <scale-down>
+               <!--a grouping of servers that can be scaled down to-->
+               <group-name>boo!</group-name>
+               <!--either a discovery group-->
+               <discovery-group>wahey</discovery-group>
+            </scale-down>
+         </live-only>
+
       </ha-policy>
       <cluster-connections>
          <cluster-connection name="cluster-connection1">
@@ -267,6 +252,9 @@
          <page-size-bytes>81738173872337</page-size-bytes>
          <page-max-cache-size>10</page-max-cache-size>
          <message-counter-history-day-limit>4</message-counter-history-day-limit>
+         <slow-consumer-threshold>10</slow-consumer-threshold>
+         <slow-consumer-check-period>5</slow-consumer-check-period>
+         <slow-consumer-policy>NOTIFY</slow-consumer-policy>
       </address-setting>
       <address-setting match="a2">
          <dead-letter-address>a2.1</dead-letter-address>
@@ -276,6 +264,9 @@
          <page-size-bytes>7126716262626</page-size-bytes>
          <page-max-cache-size>20</page-max-cache-size>
          <message-counter-history-day-limit>8</message-counter-history-day-limit>
+         <slow-consumer-threshold>20</slow-consumer-threshold>
+         <slow-consumer-check-period>15</slow-consumer-check-period>
+         <slow-consumer-policy>KILL</slow-consumer-policy>
       </address-setting>
    </address-settings>
    <connector-services>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/colocated-hapolicy-config.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/colocated-hapolicy-config.xml b/hornetq-server/src/test/resources/colocated-hapolicy-config.xml
new file mode 100644
index 0000000..ad1adc5
--- /dev/null
+++ b/hornetq-server/src/test/resources/colocated-hapolicy-config.xml
@@ -0,0 +1,34 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <replication>
+         <colocated>
+            <backup-request-retries>44</backup-request-retries>
+            <backup-request-retry-interval>33</backup-request-retry-interval>
+            <max-backups>3</max-backups>
+            <request-backup>false</request-backup>
+            <backup-port-offset>33</backup-port-offset>
+            <master>
+               <group-name>purple</group-name>
+               <check-for-live-server>true</check-for-live-server>
+               <cluster-name>abcdefg</cluster-name>
+            </master>
+            <slave>
+               <group-name>tiddles</group-name>
+               <max-saved-replicated-journals-size>22</max-saved-replicated-journals-size>
+               <cluster-name>33rrrrr</cluster-name>
+               <restart-backup>false</restart-backup>
+               <scale-down>
+                  <!--a grouping of servers that can be scaled down to-->
+                  <group-name>boo!</group-name>
+                  <!--either a discovery group-->
+                  <discovery-group>wahey</discovery-group>
+               </scale-down>
+            </slave>
+         </colocated>
+      </replication>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/colocated-hapolicy-config2.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/colocated-hapolicy-config2.xml b/hornetq-server/src/test/resources/colocated-hapolicy-config2.xml
new file mode 100644
index 0000000..f970461
--- /dev/null
+++ b/hornetq-server/src/test/resources/colocated-hapolicy-config2.xml
@@ -0,0 +1,28 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <shared-store>
+         <colocated>
+            <backup-request-retries>44</backup-request-retries>
+            <backup-request-retry-interval>33</backup-request-retry-interval>
+            <max-backups>3</max-backups>
+            <request-backup>false</request-backup>
+            <backup-port-offset>33</backup-port-offset>
+            <master>
+               <failback-delay>1234</failback-delay>
+               <failover-on-shutdown>false</failover-on-shutdown>
+            </master>
+            <slave>
+               <failback-delay>44</failback-delay>
+               <failover-on-shutdown>false</failover-on-shutdown>
+               <restart-backup>false</restart-backup>
+               <scale-down/>
+            </slave>
+         </colocated>
+
+      </shared-store>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/live-only-hapolicy-config.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/live-only-hapolicy-config.xml b/hornetq-server/src/test/resources/live-only-hapolicy-config.xml
new file mode 100644
index 0000000..6cc3aa4
--- /dev/null
+++ b/hornetq-server/src/test/resources/live-only-hapolicy-config.xml
@@ -0,0 +1,16 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <live-only>
+         <scale-down>
+            <!--a grouping of servers that can be scaled down to-->
+            <group-name>boo!</group-name>
+            <!--either a discovery group-->
+            <discovery-group>wahey</discovery-group>
+         </scale-down>
+      </live-only>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/live-only-hapolicy-config2.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/live-only-hapolicy-config2.xml b/hornetq-server/src/test/resources/live-only-hapolicy-config2.xml
new file mode 100644
index 0000000..7ae2389
--- /dev/null
+++ b/hornetq-server/src/test/resources/live-only-hapolicy-config2.xml
@@ -0,0 +1,22 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <!--only one of the following-->
+      <!--on server shutdown scale down to another live server-->
+      <live-only>
+         <scale-down>
+            <enabled>false</enabled>
+            <!--a grouping of servers that can be scaled down to-->
+            <group-name>boo!</group-name>
+            <!--or some connectors-->
+            <connectors>
+               <connector-ref>sd-connector1</connector-ref>
+               <connector-ref>sd-connector2</connector-ref>
+            </connectors>
+         </scale-down>
+      </live-only>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/live-only-hapolicy-config3.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/live-only-hapolicy-config3.xml b/hornetq-server/src/test/resources/live-only-hapolicy-config3.xml
new file mode 100644
index 0000000..2239c78
--- /dev/null
+++ b/hornetq-server/src/test/resources/live-only-hapolicy-config3.xml
@@ -0,0 +1,11 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <!--only one of the following-->
+      <!--on server shutdown scale down to another live server-->
+      <live-only/>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/live-only-hapolicy-config4.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/live-only-hapolicy-config4.xml b/hornetq-server/src/test/resources/live-only-hapolicy-config4.xml
new file mode 100644
index 0000000..1ae6dd4
--- /dev/null
+++ b/hornetq-server/src/test/resources/live-only-hapolicy-config4.xml
@@ -0,0 +1,7 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy/>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/live-only-hapolicy-config5.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/live-only-hapolicy-config5.xml b/hornetq-server/src/test/resources/live-only-hapolicy-config5.xml
new file mode 100644
index 0000000..0037115
--- /dev/null
+++ b/hornetq-server/src/test/resources/live-only-hapolicy-config5.xml
@@ -0,0 +1,6 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/replica-hapolicy-config.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/replica-hapolicy-config.xml b/hornetq-server/src/test/resources/replica-hapolicy-config.xml
new file mode 100644
index 0000000..1a2c70d
--- /dev/null
+++ b/hornetq-server/src/test/resources/replica-hapolicy-config.xml
@@ -0,0 +1,24 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <replication>
+         <slave>
+            <group-name>tiddles</group-name>
+            <max-saved-replicated-journals-size>22</max-saved-replicated-journals-size>
+            <cluster-name>33rrrrr</cluster-name>
+            <restart-backup>false</restart-backup>
+            <allow-failback>true</allow-failback>
+            <failback-delay>9876</failback-delay>
+            <scale-down>
+               <!--a grouping of servers that can be scaled down to-->
+               <group-name>boo!</group-name>
+               <!--either a discovery group-->
+               <discovery-group>wahey</discovery-group>
+            </scale-down>
+         </slave>
+      </replication>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/replica-hapolicy-config2.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/replica-hapolicy-config2.xml b/hornetq-server/src/test/resources/replica-hapolicy-config2.xml
new file mode 100644
index 0000000..373c8e0
--- /dev/null
+++ b/hornetq-server/src/test/resources/replica-hapolicy-config2.xml
@@ -0,0 +1,25 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <replication>
+         <slave>
+            <group-name>tiddles</group-name>
+            <max-saved-replicated-journals-size>22</max-saved-replicated-journals-size>
+            <cluster-name>33rrrrr</cluster-name>
+            <restart-backup>false</restart-backup>
+            <scale-down>
+               <!--a grouping of servers that can be scaled down to-->
+               <group-name>boo!</group-name>
+               <!--or some connectors-->
+               <connectors>
+                  <connector-ref>sd-connector1</connector-ref>
+                  <connector-ref>sd-connector2</connector-ref>
+               </connectors>
+            </scale-down>
+         </slave>
+      </replication>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/replica-hapolicy-config3.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/replica-hapolicy-config3.xml b/hornetq-server/src/test/resources/replica-hapolicy-config3.xml
new file mode 100644
index 0000000..3b6bc23
--- /dev/null
+++ b/hornetq-server/src/test/resources/replica-hapolicy-config3.xml
@@ -0,0 +1,16 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <replication>
+         <slave>
+            <group-name>tiddles</group-name>
+            <max-saved-replicated-journals-size>22</max-saved-replicated-journals-size>
+            <cluster-name>33rrrrr</cluster-name>
+            <restart-backup>false</restart-backup>
+         </slave>
+      </replication>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/replicated-hapolicy-config.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/replicated-hapolicy-config.xml b/hornetq-server/src/test/resources/replicated-hapolicy-config.xml
new file mode 100644
index 0000000..82537cb
--- /dev/null
+++ b/hornetq-server/src/test/resources/replicated-hapolicy-config.xml
@@ -0,0 +1,15 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <replication>
+         <master>
+            <group-name>purple</group-name>
+            <check-for-live-server>true</check-for-live-server>
+            <cluster-name>abcdefg</cluster-name>
+         </master>
+      </replication>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/shared-store-master-hapolicy-config.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/shared-store-master-hapolicy-config.xml b/hornetq-server/src/test/resources/shared-store-master-hapolicy-config.xml
new file mode 100644
index 0000000..68a52d7
--- /dev/null
+++ b/hornetq-server/src/test/resources/shared-store-master-hapolicy-config.xml
@@ -0,0 +1,14 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <shared-store>
+         <master>
+            <failback-delay>3456</failback-delay>
+            <failover-on-shutdown>false</failover-on-shutdown>
+         </master>
+      </shared-store>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config.xml b/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config.xml
new file mode 100644
index 0000000..21a86a6
--- /dev/null
+++ b/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config.xml
@@ -0,0 +1,22 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <shared-store>
+         <slave>
+            <allow-failback>true</allow-failback>
+            <failback-delay>9876</failback-delay>
+            <failover-on-shutdown>false</failover-on-shutdown>
+            <restart-backup>false</restart-backup>
+            <scale-down>
+               <!--a grouping of servers that can be scaled down to-->
+               <group-name>boo!</group-name>
+               <!--either a discovery group-->
+               <discovery-group>wahey</discovery-group>
+            </scale-down>
+         </slave>
+      </shared-store>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config2.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config2.xml b/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config2.xml
new file mode 100644
index 0000000..fdf037a
--- /dev/null
+++ b/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config2.xml
@@ -0,0 +1,24 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <shared-store>
+         <slave>
+            <failback-delay>5678</failback-delay>
+            <failover-on-shutdown>true</failover-on-shutdown>
+            <restart-backup>true</restart-backup>
+            <scale-down>
+               <!--a grouping of servers that can be scaled down to-->
+               <group-name>boo!</group-name>
+               <!--or some connectors-->
+               <connectors>
+                  <connector-ref>sd-connector1</connector-ref>
+                  <connector-ref>sd-connector2</connector-ref>
+               </connectors>
+            </scale-down>
+         </slave>
+      </shared-store>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config3.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config3.xml b/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config3.xml
new file mode 100644
index 0000000..5709cfc
--- /dev/null
+++ b/hornetq-server/src/test/resources/shared-store-slave-hapolicy-config3.xml
@@ -0,0 +1,15 @@
+<configuration
+      xmlns="urn:hornetq"
+      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+      xsi:schemaLocation="urn:hornetq ../../../../hornetq-server/src/main/resources/schema/hornetq-configuration.xsd">
+   <ha-policy>
+      <shared-store>
+         <slave>
+            <failback-delay>5678</failback-delay>
+            <failover-on-shutdown>true</failover-on-shutdown>
+            <restart-backup>true</restart-backup>
+         </slave>
+      </shared-store>
+   </ha-policy>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-tools/src/main/java/org/hornetq/tools/Main.java
----------------------------------------------------------------------
diff --git a/hornetq-tools/src/main/java/org/hornetq/tools/Main.java b/hornetq-tools/src/main/java/org/hornetq/tools/Main.java
index b8da8ff..5ff73f9 100644
--- a/hornetq-tools/src/main/java/org/hornetq/tools/Main.java
+++ b/hornetq-tools/src/main/java/org/hornetq/tools/Main.java
@@ -21,7 +21,8 @@ public class Main
    private static final String PRINT_DATA = "print-data";
    private static final String PRINT_PAGES = "print-pages";
    private static final String DATA_TOOL = "data-tool";
-   private static final String OPTIONS =  " [" + IMPORT + "|" + EXPORT + "|" + PRINT_DATA + "|" + PRINT_PAGES + "|" + DATA_TOOL + "]";
+   private static final String TRANSFER = "transfer-queue";
+   private static final String OPTIONS = " [" + IMPORT + "|" + EXPORT + "|" + PRINT_DATA + "|" + PRINT_PAGES + "|" + DATA_TOOL + "|" + TRANSFER + "]";
 
    public static void main(String[] arg) throws Exception
    {
@@ -31,7 +32,13 @@ public class Main
          System.exit(-1);
       }
 
-      if (DATA_TOOL.equals(arg[0]))
+
+      if (TRANSFER.equals(arg[0]))
+      {
+         TransferQueue tool = new TransferQueue();
+         tool.process(arg);
+      }
+      else if (DATA_TOOL.equals(arg[0]))
       {
          DataTool dataTool = new DataTool();
          dataTool.process(arg);
@@ -90,9 +97,16 @@ public class Main
 
    protected static String getJarName()
    {
-      Class klass = Main.class;
-      String url = klass.getResource('/' + klass.getName().replace('.', '/') + ".class").toString();
-      String jarName = url.substring(0, url.lastIndexOf('!'));
-      return jarName.substring(jarName.lastIndexOf('/') + 1);
+      try
+      {
+         Class klass = Main.class;
+         String url = klass.getResource('/' + klass.getName().replace('.', '/') + ".class").toString();
+         String jarName = url.substring(0, url.lastIndexOf('!'));
+         return jarName.substring(jarName.lastIndexOf('/') + 1);
+      }
+      catch (Throwable e)
+      {
+         return "tool-jar-name.jar";
+      }
    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-tools/src/main/java/org/hornetq/tools/TransferQueue.java
----------------------------------------------------------------------
diff --git a/hornetq-tools/src/main/java/org/hornetq/tools/TransferQueue.java b/hornetq-tools/src/main/java/org/hornetq/tools/TransferQueue.java
new file mode 100644
index 0000000..c7c1084
--- /dev/null
+++ b/hornetq-tools/src/main/java/org/hornetq/tools/TransferQueue.java
@@ -0,0 +1,243 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.tools;
+
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.ClientConsumer;
+import org.hornetq.api.core.client.ClientMessage;
+import org.hornetq.api.core.client.ClientProducer;
+import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.api.core.client.ClientSessionFactory;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory;
+import org.hornetq.core.remoting.impl.netty.TransportConstants;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class TransferQueue // NO_UCD (unused code)
+{
+
+   public void process(String[] arg)
+   {
+      if (arg.length != 13 && arg.length != 14)
+      {
+         System.out.println("Invalid number of arguments! " + arg.length);
+         printUsage();
+         System.exit(-1);
+      }
+
+      String sourceHost;
+      String sourceUser;
+      String sourcePass;
+      int sourcePort;
+      String queue;
+
+      String targetHost;
+      int targetPort;
+      String targetUser;
+      String targetPassword;
+      String producingAddress;
+
+      int commit;
+
+      int waitTimeout;
+
+      String filter = null;
+
+      try
+      {
+         sourceHost = arg[1];
+         sourcePort = Integer.parseInt(arg[2]);
+         sourceUser = arg[3];
+         sourcePass = arg[4];
+         queue = arg[5];
+
+         targetHost = arg[6];
+         targetPort = Integer.parseInt(arg[7]);
+         targetUser = arg[8];
+         targetPassword = arg[9];
+         producingAddress = arg[10];
+
+         waitTimeout = Integer.parseInt(arg[11]);
+         commit = Integer.parseInt(arg[12]);
+
+         if (arg.length == 14)
+         {
+            filter = arg[13];
+         }
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+         printUsage();
+         System.exit(-1);
+         return; // the compiler doesn't understand exit as leaving the VM
+      }
+
+      Map<String, Object> sourceParameters = new HashMap<String, Object>();
+      sourceParameters.put(TransportConstants.HOST_PROP_NAME, sourceHost);
+      sourceParameters.put(TransportConstants.PORT_PROP_NAME, sourcePort);
+
+      Map<String, Object> targetParameters = new HashMap<String, Object>();
+      sourceParameters.put(TransportConstants.HOST_PROP_NAME, targetHost);
+      sourceParameters.put(TransportConstants.PORT_PROP_NAME, targetPort);
+
+
+      try
+      {
+         TransportConfiguration configurationSource = new TransportConfiguration(NettyConnectorFactory.class.getName(), sourceParameters);
+
+         ServerLocator locatorSource = HornetQClient.createServerLocator(false, configurationSource);
+
+         ClientSessionFactory factorySource = locatorSource.createSessionFactory();
+
+         ClientSession sessionSource = factorySource.createSession(sourceUser, sourcePass, false, false, false, false, 0);
+
+         ClientConsumer consumer;
+
+         if (filter == null)
+         {
+            consumer = sessionSource.createConsumer(queue);
+         }
+         else
+         {
+            consumer = sessionSource.createConsumer(queue, filter);
+         }
+
+
+         TransportConfiguration configurationTarget = new TransportConfiguration(NettyConnectorFactory.class.getName(), targetParameters);
+
+         ServerLocator locatorTarget = HornetQClient.createServerLocatorWithoutHA(configurationTarget);
+
+
+
+         ClientSessionFactory factoryTarget = locatorTarget.createSessionFactory();
+
+         ClientSession sessionTarget = factoryTarget.createSession(targetUser, targetPassword, false, false, false, false, 0);
+
+         ClientProducer producer = sessionTarget.createProducer(producingAddress);
+
+         sessionSource.start();
+
+         int countMessage = 0;
+
+         while (true)
+         {
+            ClientMessage message = consumer.receive(waitTimeout);
+            if (message == null)
+            {
+               break;
+            }
+
+            message.acknowledge();
+
+            if (!message.containsProperty("_HQ_TOOL_original_address"))
+            {
+               message.putStringProperty("_HQ_TOOL_original_address", message.getAddress().toString());
+            }
+
+            LinkedList<String> listToRemove = new LinkedList<String>();
+
+            for (SimpleString name : message.getPropertyNames())
+            {
+               if (name.toString().startsWith("_HQ_ROUTE_TO"))
+               {
+                  listToRemove.add(name.toString());
+               }
+            }
+
+            for (String str: listToRemove)
+            {
+               message.removeProperty(str);
+            }
+
+            producer.send(message);
+
+            if (countMessage++ % commit == 0)
+            {
+               System.out.println("Sent " + countMessage + " messages");
+               sessionTarget.commit();
+               sessionSource.commit();
+            }
+
+         }
+
+
+         sessionTarget.commit();
+         sessionSource.commit();
+         consumer.close();
+         producer.close();
+
+         sessionSource.close();
+         sessionTarget.close();
+
+         locatorSource.close();
+         locatorTarget.close();
+
+
+
+
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+         printUsage();
+         System.exit(-1);
+      }
+
+   }
+
+
+   public void printUsage()
+   {
+      for (int i = 0; i < 10; i++)
+      {
+         System.err.println();
+      }
+      System.err.println("This method will transfer messages from one queue into another, while removing internal properties such as ROUTE_TO.");
+      System.err.println();
+      System.err.println(Main.USAGE + " <source-IP> <source-port> <user> <password> <source-queue> <target-IP> <target-port> <user> <password> <target-address> <wait-timeout> <commit-size> [filter]");
+      System.err.println();
+      System.err.println("source-host: IP/hostname for the originating server for the messages");
+      System.err.println("source-port: port for the originating server for the messages");
+      System.err.println("user: Username used to connect to the source");
+      System.err.println("password: Password used to connect to the source");
+      System.err.println("source-port: port for the originating server for the messages");
+
+      System.err.println("source-queue: originating queue for the messages");
+      System.err.println();
+      System.err.println("target-host: IP/hostname for the destination server for the messages");
+      System.err.println("target-port: port for the destination server for the messages");
+      System.err.println("user: Username used to connect to the target");
+      System.err.println("password: Password used to connect to the target");
+      System.err.println("target-address: address at the destination server");
+      System.err.println();
+      System.err.println("wait-timeout: time in milliseconds");
+      System.err.println("commit-size: batch size for each transaction (in number of messages)");
+      System.err.println();
+      System.err.println("filter: You can optionally add a filter to the original queue");
+      for (int i = 0; i < 10; i++)
+      {
+         System.err.println();
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataConstants.java
----------------------------------------------------------------------
diff --git a/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataConstants.java b/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataConstants.java
index 70848f0..6cea6ea 100644
--- a/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataConstants.java
+++ b/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataConstants.java
@@ -117,4 +117,6 @@ public final class XmlDataConstants
    static final String JMS_JNDI_ENTRY = "entry";
 
    public static final String JNDI_COMPATIBILITY_PREFIX = "java:jboss/exported/";
+
+   static final String NULL = "_HQ_NULL";
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataExporter.java
----------------------------------------------------------------------
diff --git a/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataExporter.java b/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataExporter.java
index 454b850..99b0d16 100644
--- a/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataExporter.java
+++ b/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataExporter.java
@@ -135,12 +135,12 @@ public final class XmlDataExporter
    public XmlDataExporter(OutputStream out, String bindingsDir, String journalDir, String pagingDir,
                           String largeMessagesDir) throws Exception
    {
-      config = new ConfigurationImpl();
-      config.setBindingsDirectory(bindingsDir);
-      config.setJournalDirectory(journalDir);
-      config.setPagingDirectory(pagingDir);
-      config.setLargeMessagesDirectory(largeMessagesDir);
-      config.setJournalType(JournalType.NIO);
+      config = new ConfigurationImpl()
+         .setBindingsDirectory(bindingsDir)
+         .setJournalDirectory(journalDir)
+         .setPagingDirectory(pagingDir)
+         .setLargeMessagesDirectory(largeMessagesDir)
+         .setJournalType(JournalType.NIO);
       final ExecutorService executor = Executors.newFixedThreadPool(1);
       ExecutorFactory executorFactory = new ExecutorFactory()
       {
@@ -950,7 +950,7 @@ public final class XmlDataExporter
          }
          else
          {
-            xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_VALUE, value.toString());
+            xmlWriter.writeAttribute(XmlDataConstants.PROPERTY_VALUE, value == null ? XmlDataConstants.NULL : value.toString());
          }
 
          if (value instanceof Boolean)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataImporter.java
----------------------------------------------------------------------
diff --git a/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataImporter.java b/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataImporter.java
index 41a7c08..ae33615 100644
--- a/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataImporter.java
+++ b/hornetq-tools/src/main/java/org/hornetq/tools/XmlDataImporter.java
@@ -407,6 +407,7 @@ public final class XmlDataImporter
       String key = "";
       String value = "";
       String propertyType = "";
+      String realValue = null;
 
       for (int i = 0; i < reader.getAttributeCount(); i++)
       {
@@ -452,10 +453,18 @@ public final class XmlDataImporter
             message.putLongProperty(key, Long.parseLong(value));
             break;
          case XmlDataConstants.PROPERTY_TYPE_SIMPLE_STRING:
-            message.putStringProperty(new SimpleString(key), new SimpleString(value));
+            if (!value.equals(XmlDataConstants.NULL))
+            {
+               realValue = value;
+            }
+            message.putStringProperty(new SimpleString(key), new SimpleString(realValue));
             break;
          case XmlDataConstants.PROPERTY_TYPE_STRING:
-            message.putStringProperty(key, value);
+            if (!value.equals(XmlDataConstants.NULL))
+            {
+               realValue = value;
+            }
+            message.putStringProperty(key, realValue);
             break;
       }
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq_doap.rdf
----------------------------------------------------------------------
diff --git a/hornetq_doap.rdf b/hornetq_doap.rdf
new file mode 100644
index 0000000..2dd7031
--- /dev/null
+++ b/hornetq_doap.rdf
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<rdf:RDF xml:lang="en" xmlns="http://usefulinc.com/ns/doap#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
+  <Project rdf:about="">
+    <name></name>
+    <homepage rdf:resource="" />
+    <shortdesc></shortdesc>
+    <description></description>
+    
+    <maintainer>
+      <foaf:Person>
+        <foaf:name>Clebert Suconic</foaf:name>
+        <foaf:status>Project Lead</foaf:status>
+        <foaf:firstName>Clebert</foaf:firstName>
+        <foaf:lastName>Suconic</foaf:lastName>
+      </foaf:Person>
+    </maintainer>
+    <developer>
+      <foaf:Person>
+        <foaf:name>Andy Taylor</foaf:name>
+        <foaf:firstName>Andy</foaf:firstName>
+        <foaf:lastName>Taylor</foaf:lastName>
+      </foaf:Person>
+    </developer>
+    <developer>
+      <foaf:Person>
+        <foaf:name>Howard Gao</foaf:name>
+        <foaf:firstName>Howard</foaf:firstName>
+        <foaf:lastName>Gao</foaf:lastName>
+      </foaf:Person>
+    </developer>
+    <developer>
+      <foaf:Person>
+        <foaf:name>Justin Bertram</foaf:name>
+        <foaf:firstName>Justin</foaf:firstName>
+        <foaf:lastName>Bertram</foaf:lastName>
+      </foaf:Person>
+    </developer>
+    <developer>
+      <foaf:Person>
+        <foaf:name>Martyn Taylor</foaf:name>
+        <foaf:firstName>Martyn</foaf:firstName>
+        <foaf:lastName>Taylor</foaf:lastName>
+      </foaf:Person>
+    </developer>
+    
+    <release>
+      <Version>
+        <name>2.4.0</name>
+        <revision>2.4.0.final</revision>
+        <created>2013-16-12</created>
+      </Version>
+    </release>
+    <license rdf:resource="" />
+    
+    
+    <programming-language>Java</programming-language>
+    <programming-language>C/C++</programming-language>
+    <vendor>Red Hat</vendor>
+    <implements>
+      <Specification>
+        <name>JMS 2.0</name>
+        <description></description>
+        <rdfs:seeAlso rdf:resource="" />
+      </Specification>
+    </implements>
+    <foaf:logo rdf:resource="" />
+    <foaf:account>
+      <foaf:OnlineAccount>
+        <rdf:type rdf:resource="http://xmlns.com/foaf/0.1/OnlineChatAccount" />
+        <foaf:accountServiceHomepage rdf:resource="http://twitter.com/" />
+        <foaf:accountName>hornetq</foaf:accountName>
+      </foaf:OnlineAccount>
+    </foaf:account>
+  </Project>
+</rdf:RDF>
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/integration/hornetq-aerogear-integration/pom.xml
----------------------------------------------------------------------
diff --git a/integration/hornetq-aerogear-integration/pom.xml b/integration/hornetq-aerogear-integration/pom.xml
index 1840a34..3375f4d 100644
--- a/integration/hornetq-aerogear-integration/pom.xml
+++ b/integration/hornetq-aerogear-integration/pom.xml
@@ -39,7 +39,7 @@
       <dependency>
          <groupId>org.jboss.aerogear</groupId>
          <artifactId>unifiedpush-java-client</artifactId>
-         <version>0.4.0</version>
+         <version>1.0.0</version>
       </dependency>
       <!-- RestEasy's Jackson Plugin -->
       <dependency>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConnectorService.java
----------------------------------------------------------------------
diff --git a/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConnectorService.java b/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConnectorService.java
index 031696b..ed5cea7 100644
--- a/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConnectorService.java
+++ b/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConnectorService.java
@@ -62,6 +62,10 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes
 
    private final String sound;
 
+   private final boolean contentAvailable;
+
+   private final String actionCategory;
+
    private String[] variants;
 
    private String[] aliases;
@@ -96,6 +100,8 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes
       this.ttl = ConfigurationHelper.getIntProperty(AeroGearConstants.TTL_NAME, AeroGearConstants.DEFAULT_TTL, configuration);
       this.badge = ConfigurationHelper.getStringProperty(AeroGearConstants.BADGE_NAME, null, configuration);
       this.sound = ConfigurationHelper.getStringProperty(AeroGearConstants.SOUND_NAME, AeroGearConstants.DEFAULT_SOUND, configuration);
+      this.contentAvailable = ConfigurationHelper.getBooleanProperty(AeroGearConstants.CONTENT_AVAILABLE_NAME, false, configuration);
+      this.actionCategory = ConfigurationHelper.getStringProperty(AeroGearConstants.ACTION_CATEGORY_NAME, null, configuration);
       this.filterString = ConfigurationHelper.getStringProperty(AeroGearConstants.FILTER_NAME, null, configuration);
       this.retryInterval = ConfigurationHelper.getIntProperty(AeroGearConstants.RETRY_INTERVAL_NAME, AeroGearConstants.DEFAULT_RETRY_INTERVAL, configuration);
       this.retryAttempts = ConfigurationHelper.getIntProperty(AeroGearConstants.RETRY_ATTEMPTS_NAME, AeroGearConstants.DEFAULT_RETRY_ATTEMPTS, configuration);
@@ -202,7 +208,7 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes
 
       String alert = message.getTypedProperties().getProperty(AeroGearConstants.AEROGEAR_ALERT).toString();
 
-      JavaSender sender = new SenderClient(endpoint);
+      JavaSender sender = new SenderClient.Builder(endpoint).build();
 
       UnifiedMessage.Builder builder = new UnifiedMessage.Builder();
 
@@ -224,6 +230,20 @@ public class AeroGearConnectorService implements ConnectorService, Consumer, Mes
          builder.badge(badge);
       }
 
+      boolean contentAvailable = message.containsProperty(AeroGearConstants.AEROGEAR_CONTENT_AVAILABLE) ? message.getBooleanProperty(AeroGearConstants.AEROGEAR_CONTENT_AVAILABLE) : this.contentAvailable;
+
+      if (contentAvailable)
+      {
+         builder.contentAvailable();
+      }
+
+      String actionCategory = message.containsProperty(AeroGearConstants.AEROGEAR_ACTION_CATEGORY) ? message.getStringProperty(AeroGearConstants.AEROGEAR_ACTION_CATEGORY) : this.actionCategory;
+
+      if (actionCategory != null)
+      {
+         builder.actionCategory(actionCategory);
+      }
+
       Integer ttl = message.containsProperty(AeroGearConstants.AEROGEAR_TTL) ? message.getIntProperty(AeroGearConstants.AEROGEAR_TTL) : this.ttl;
 
       if (ttl != null)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConstants.java
----------------------------------------------------------------------
diff --git a/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConstants.java b/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConstants.java
index aac0a0d..a0349c8 100644
--- a/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConstants.java
+++ b/integration/hornetq-aerogear-integration/src/main/java/org/hornetq/integration/aerogear/AeroGearConstants.java
@@ -29,6 +29,8 @@ public class AeroGearConstants
    public static final String TTL_NAME = "ttl";
    public static final String BADGE_NAME = "badge";
    public static final String SOUND_NAME = "sound";
+   public static final String CONTENT_AVAILABLE_NAME = "content-available";
+   public static final String ACTION_CATEGORY_NAME = "action-category";
    public static final String FILTER_NAME = "filter";
    public static final String RETRY_INTERVAL_NAME = "retry-interval";
    public static final String RETRY_ATTEMPTS_NAME = "retry-attempts";
@@ -39,6 +41,8 @@ public class AeroGearConstants
 
    public static final SimpleString AEROGEAR_ALERT = new SimpleString("AEROGEAR_ALERT");
    public static final SimpleString AEROGEAR_SOUND = new SimpleString("AEROGEAR_SOUND");
+   public static final SimpleString AEROGEAR_CONTENT_AVAILABLE = new SimpleString("AEROGEAR_CONTENT_AVAILABLE");
+   public static final SimpleString AEROGEAR_ACTION_CATEGORY = new SimpleString("AEROGEAR_ACTION_CATEGORY");
    public static final SimpleString AEROGEAR_BADGE = new SimpleString("AEROGEAR_BADGE");
    public static final SimpleString AEROGEAR_TTL = new SimpleString("AEROGEAR_TTL");
    public static final SimpleString AEROGEAR_VARIANTS = new SimpleString("AEROGEAR_VARIANTS");
@@ -59,6 +63,8 @@ public class AeroGearConstants
       ALLOWABLE_PROPERTIES.add(TTL_NAME);
       ALLOWABLE_PROPERTIES.add(BADGE_NAME);
       ALLOWABLE_PROPERTIES.add(SOUND_NAME);
+      ALLOWABLE_PROPERTIES.add(CONTENT_AVAILABLE_NAME);
+      ALLOWABLE_PROPERTIES.add(ACTION_CATEGORY_NAME);
       ALLOWABLE_PROPERTIES.add(FILTER_NAME);
       ALLOWABLE_PROPERTIES.add(RETRY_INTERVAL_NAME);
       ALLOWABLE_PROPERTIES.add(RETRY_ATTEMPTS_NAME);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/integration/hornetq-jboss-as-integration/pom.xml
----------------------------------------------------------------------
diff --git a/integration/hornetq-jboss-as-integration/pom.xml b/integration/hornetq-jboss-as-integration/pom.xml
index fd11dd1..e159478 100644
--- a/integration/hornetq-jboss-as-integration/pom.xml
+++ b/integration/hornetq-jboss-as-integration/pom.xml
@@ -45,7 +45,7 @@
       </dependency>
       <dependency>
          <groupId>org.jboss.spec.javax.transaction</groupId>
-         <artifactId>jboss-transaction-api_1.1_spec</artifactId>
+         <artifactId>jboss-transaction-api_1.2_spec</artifactId>
       </dependency>
       <dependency>
          <groupId>org.jboss</groupId>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/integration/hornetq-twitter-integration/src/main/java/org/hornetq/integration/twitter/impl/IncomingTweetsHandler.java
----------------------------------------------------------------------
diff --git a/integration/hornetq-twitter-integration/src/main/java/org/hornetq/integration/twitter/impl/IncomingTweetsHandler.java b/integration/hornetq-twitter-integration/src/main/java/org/hornetq/integration/twitter/impl/IncomingTweetsHandler.java
index 3d47c41..d9f1650 100644
--- a/integration/hornetq-twitter-integration/src/main/java/org/hornetq/integration/twitter/impl/IncomingTweetsHandler.java
+++ b/integration/hornetq-twitter-integration/src/main/java/org/hornetq/integration/twitter/impl/IncomingTweetsHandler.java
@@ -161,7 +161,7 @@ public class IncomingTweetsHandler implements ConnectorService
       {
          Status status = (Status) res.get(i);
 
-         ServerMessage msg = new ServerMessageImpl(this.storageManager.generateUniqueID(),
+         ServerMessage msg = new ServerMessageImpl(this.storageManager.generateID(),
                                                    TwitterConstants.INITIAL_MESSAGE_BUFFER_SIZE);
          msg.setAddress(new SimpleString(this.queueName));
          msg.setDurable(true);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/integration/hornetq-vertx-integration/pom.xml
----------------------------------------------------------------------
diff --git a/integration/hornetq-vertx-integration/pom.xml b/integration/hornetq-vertx-integration/pom.xml
index a060023..3521603 100644
--- a/integration/hornetq-vertx-integration/pom.xml
+++ b/integration/hornetq-vertx-integration/pom.xml
@@ -37,15 +37,15 @@
     <mods.directory>target/mods</mods.directory>
 
     <!--Dependency versions-->
-    <vertx.version>2.1.1</vertx.version>
-    <vertx.testtools.version>2.0.2-final</vertx.testtools.version>
+    <vertx.version>2.1.2</vertx.version>
+    <vertx.testtools.version>2.0.3-final</vertx.testtools.version>
     <junit.version>4.11</junit.version>
 
     <!--Plugin versions-->
     <maven.compiler.plugin.version>3.0</maven.compiler.plugin.version>
     <maven.resources.plugin.version>2.6</maven.resources.plugin.version>
     <maven.clean.plugin.version>2.5</maven.clean.plugin.version>
-    <maven.vertx.plugin.version>2.0.1-final</maven.vertx.plugin.version>
+    <maven.vertx.plugin.version>2.0.8-final</maven.vertx.plugin.version>
     <maven.surefire.plugin.version>2.14</maven.surefire.plugin.version>
     <maven.failsafe.plugin.version>2.14</maven.failsafe.plugin.version>
     <maven.surefire.report.plugin.version>2.14</maven.surefire.report.plugin.version>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/integration/hornetq-vertx-integration/src/main/java/org/hornetq/integration/vertx/IncomingVertxEventHandler.java
----------------------------------------------------------------------
diff --git a/integration/hornetq-vertx-integration/src/main/java/org/hornetq/integration/vertx/IncomingVertxEventHandler.java b/integration/hornetq-vertx-integration/src/main/java/org/hornetq/integration/vertx/IncomingVertxEventHandler.java
index 667b758..7cb3d14 100644
--- a/integration/hornetq-vertx-integration/src/main/java/org/hornetq/integration/vertx/IncomingVertxEventHandler.java
+++ b/integration/hornetq-vertx-integration/src/main/java/org/hornetq/integration/vertx/IncomingVertxEventHandler.java
@@ -150,7 +150,7 @@ public class IncomingVertxEventHandler implements ConnectorService
       @Override
       public void handle(Message<?> message)
       {
-         ServerMessage msg = new ServerMessageImpl(storageManager.generateUniqueID(),
+         ServerMessage msg = new ServerMessageImpl(storageManager.generateID(),
                   VertxConstants.INITIAL_MESSAGE_BUFFER_SIZE);
          msg.setAddress(new SimpleString(queueName));
          msg.setDurable(true);


[14/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index f34dcb4..5576fc4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -7,6 +7,7 @@
    <version>2.5.0-SNAPSHOT</version>
    <modules>
       <module>hornetq-protocols</module>
+     <module>hornetq-dto</module>
    </modules>
 
    <name>HornetQ Parent</name>
@@ -45,7 +46,8 @@
          ${hornetq.version.majorVersion}.${hornetq.version.minorVersion}.${hornetq.version.microVersion}.${hornetq.version.versionSuffix}
          (${hornetq.version.versionName}, ${hornetq.version.incrementingVersion})
       </HornetQ-Version>
-      <resteasy.version>3.0.4.Final</resteasy.version>
+      <resteasy.version>3.0.9.Final</resteasy.version>
+      <jackson-databind.version>2.3.1</jackson-databind.version>
       <skipUnitTests>true</skipUnitTests>
       <skipJmsTests>true</skipJmsTests>
       <skipBytemanTests>true</skipBytemanTests>
@@ -209,10 +211,9 @@
          </dependency>
          <dependency>
             <groupId>org.jboss.spec.javax.transaction</groupId>
-            <artifactId>jboss-transaction-api_1.1_spec</artifactId>
+            <artifactId>jboss-transaction-api_1.2_spec</artifactId>
             <version>1.0.0.Final</version>
          </dependency>
-
          <!--this specifically for the JMS Bridge-->
          <dependency>
             <groupId>org.jboss</groupId>
@@ -231,6 +232,12 @@
             <artifactId>jbossjts-jacorb</artifactId>
             <version>4.17.13.Final</version>
          </dependency>
+         <!-- this for Ironjacamar SPI XAResourceWrapper implementation -->
+         <dependency>
+            <groupId>org.jboss.ironjacamar</groupId>
+            <artifactId>ironjacamar-core-api</artifactId>
+            <version>1.2.0.Beta2</version>
+         </dependency>
          <!--needed to compile security-->
          <dependency>
             <groupId>org.jboss.security</groupId>
@@ -244,58 +251,15 @@
          </dependency>
          <!--needed to compile the bootstrap jar-->
          <dependency>
-            <groupId>org.jboss.microcontainer</groupId>
-            <artifactId>jboss-kernel</artifactId>
-            <version>2.0.6.GA</version>
-            <exclusions>
-               <exclusion>
-                  <groupId>org.jboss.logging</groupId>
-                  <artifactId>jboss-logging-spi</artifactId>
-               </exclusion>
-            </exclusions>
-         </dependency>
-         <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jboss-common-core</artifactId>
-            <version>2.2.14.GA</version>
-            <exclusions>
-               <exclusion>
-                  <groupId>org.jboss.logging</groupId>
-                  <artifactId>jboss-logging-spi</artifactId>
-               </exclusion>
-            </exclusions>
-         </dependency>
-         <dependency>
             <groupId>org.jgroups</groupId>
             <artifactId>jgroups</artifactId>
             <version>3.3.4.Final</version>
          </dependency>
-         <!--needed for microntainer deps in distro-->
-         <dependency>
-            <groupId>org.jboss.microcontainer</groupId>
-            <artifactId>jboss-dependency</artifactId>
-            <version>2.0.6.GA</version>
-         </dependency>
-         <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jboss-reflect</artifactId>
-            <version>2.0.2.GA</version>
-         </dependency>
-         <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jboss-mdr</artifactId>
-            <version>2.0.1.GA</version>
-         </dependency>
-         <dependency>
-            <groupId>org.jboss</groupId>
-            <artifactId>jbossxb</artifactId>
-            <version>2.0.1.GA</version>
-         </dependency>
-         <dependency>
-            <groupId>sun-jaxb</groupId>
-            <artifactId>jaxb-api</artifactId>
-            <version>2.1.9</version>
-         </dependency>
+        <dependency>
+            <groupId>io.airlift</groupId>
+            <artifactId>airline</artifactId>
+            <version>0.6</version>
+        </dependency>
          <!--needed to compile transport jar-->
          <dependency>
             <groupId>io.netty</groupId>
@@ -324,19 +288,25 @@
 
          <dependency>
             <groupId>org.apache.qpid</groupId>
-            <artifactId>proton-api</artifactId>
-            <version>0.5</version>
+            <artifactId>proton-j</artifactId>
+            <version>0.8</version>
          </dependency>
          <dependency>
             <groupId>org.apache.qpid</groupId>
-            <artifactId>proton-j-impl</artifactId>
-            <version>0.5</version>
+            <artifactId>proton-jms</artifactId>
+            <version>0.8</version>
          </dependency>
          <dependency>
-            <groupId>org.apache.qpid</groupId>
-            <artifactId>proton-jms</artifactId>
-            <version>0.5</version>
+            <groupId>org.apache.activemq</groupId>
+            <artifactId>activemq-client</artifactId>
+            <version>5.10.0</version>
          </dependency>
+         <dependency>
+           <groupId>org.slf4j</groupId>
+           <artifactId>slf4j-api</artifactId>
+           <version>1.7.5</version>
+         </dependency>
+
          <!--needed to compile the spring support-->
          <dependency>
             <groupId>org.springframework</groupId>
@@ -397,7 +367,6 @@
             <artifactId>jboss-jaspi-api</artifactId>
             <version>1.0.0.GA</version>
          </dependency>
-
          <!--needed to run the jms tests -->
          <dependency>
             <groupId>org.jboss.naming</groupId>
@@ -432,6 +401,12 @@
             <groupId>org.jboss.javaee</groupId>
             <artifactId>jboss-jca-api</artifactId>
             <version>1.5.0.GA</version>
+            <exclusions>
+               <exclusion>
+                  <groupId>org.jboss.logging</groupId>
+                  <artifactId>jboss-logging-spi</artifactId>
+               </exclusion>
+            </exclusions>
          </dependency>
 
          <!-- needed for javadoc graphics-->
@@ -457,6 +432,25 @@
          <name>JBoss releases</name>
          <url>https://repository.jboss.org/nexus/content/groups/public/</url>
       </repository>
+      <!--
+	This is a repository for intermediate releases from Proton.
+        In case there's an API broken, we will release an intermediate release here, on that case we will uncomment this and
+        use this repository again
+
+      <repository>
+         <snapshots>
+            <enabled>false</enabled>
+            <updatePolicy>never</updatePolicy>
+         </snapshots>
+         <releases>
+            <enabled>true</enabled>
+            <updatePolicy>interval:10080</updatePolicy>
+         </releases>
+         <id>fuse.release</id>
+         <name>Fuse releases</name>
+         <url>https://repository.jboss.org/nexus/content/repositories/fs-releases/</url>
+      </repository>
+      -->
    </repositories>
    <pluginRepositories>
       <pluginRepository>
@@ -482,6 +476,7 @@
             <activeByDefault>true</activeByDefault>
          </activation>
          <modules>
+            <module>hornetq-dto</module>
             <module>hornetq-bootstrap</module>
             <module>hornetq-commons</module>
             <module>hornetq-selector</module>
@@ -506,6 +501,7 @@
       <profile>
          <id>maven-release</id>
          <modules>
+            <module>hornetq-dto</module>
             <module>hornetq-bootstrap</module>
             <module>hornetq-commons</module>
             <module>hornetq-selector</module>
@@ -530,6 +526,7 @@
       <profile>
          <id>release</id>
          <modules>
+            <module>hornetq-dto</module>
             <module>hornetq-bootstrap</module>
             <module>hornetq-commons</module>
             <module>hornetq-selector</module>
@@ -556,6 +553,7 @@
       <profile>
          <id>hudson-tests</id>
          <modules>
+            <module>hornetq-dto</module>
             <module>hornetq-bootstrap</module>
             <module>hornetq-commons</module>
             <module>hornetq-selector</module>
@@ -593,6 +591,7 @@
       <profile>
          <id>jenkins-fast-tests</id>
          <modules>
+            <module>hornetq-dto</module>
             <module>hornetq-bootstrap</module>
             <module>hornetq-commons</module>
             <module>hornetq-selector</module>
@@ -626,6 +625,7 @@
       <profile>
          <id>examples</id>
          <modules>
+            <module>hornetq-dto</module>
             <module>hornetq-bootstrap</module>
             <module>hornetq-commons</module>
             <module>hornetq-selector</module>
@@ -847,6 +847,15 @@
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-checkstyle-plugin</artifactId>
             <version>2.12</version>
+            <dependencies>
+               <!-- This was initially done to enforce name on Parameter annotation
+                    I've developed a customized check and I needed this jar to deploy the specialized checkstyle -->
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-checkstyle-checks</artifactId>
+                  <version>0.2</version>
+               </dependency>
+            </dependencies>
             <configuration>
                <skip>${skipStyleCheck}</skip>
                <configLocation>${hornetq.basedir}/etc/checkstyle.xml</configLocation>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/pom.xml
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/pom.xml b/tests/byteman-tests/pom.xml
index bac33d0..cd3bffa 100644
--- a/tests/byteman-tests/pom.xml
+++ b/tests/byteman-tests/pom.xml
@@ -13,7 +13,7 @@
 
    <properties>
       <tools.jar>${java.home}/../lib/tools.jar</tools.jar>
-      <byteman.version>2.1.4.1</byteman.version>
+      <byteman.version>2.2.0</byteman.version>
       <hornetq.basedir>${project.basedir}/../..</hornetq.basedir>
    </properties>
 
@@ -132,7 +132,7 @@
       </dependency>
       <dependency>
          <groupId>org.jboss.spec.javax.transaction</groupId>
-         <artifactId>jboss-transaction-api_1.1_spec</artifactId>
+         <artifactId>jboss-transaction-api_1.2_spec</artifactId>
       </dependency>
       <!--this specifically for the JMS Bridge -->
       <dependency>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BMFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BMFailoverTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BMFailoverTest.java
index 4182c8c..4724891 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BMFailoverTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BMFailoverTest.java
@@ -19,6 +19,7 @@ import javax.transaction.xa.Xid;
 
 import org.hornetq.api.core.HornetQTransactionOutcomeUnknownException;
 import org.hornetq.api.core.HornetQTransactionRolledBackException;
+import org.hornetq.api.core.HornetQUnBlockedException;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientConsumer;
@@ -27,6 +28,7 @@ import org.hornetq.api.core.client.ClientProducer;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.client.impl.ClientMessageImpl;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ClientSessionInternal;
@@ -35,11 +37,13 @@ import org.hornetq.core.server.Queue;
 import org.hornetq.core.transaction.impl.XidImpl;
 import org.hornetq.tests.integration.cluster.failover.FailoverTestBase;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
+import org.hornetq.tests.util.RandomUtil;
 import org.hornetq.utils.UUIDGenerator;
 import org.jboss.byteman.contrib.bmunit.BMRule;
 import org.jboss.byteman.contrib.bmunit.BMRules;
 import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
 import org.junit.After;
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -61,6 +65,7 @@ public class BMFailoverTest extends FailoverTestBase
    public void setUp() throws Exception
    {
       super.setUp();
+      stopped = false;
       locator = getServerLocator();
    }
 
@@ -71,6 +76,122 @@ public class BMFailoverTest extends FailoverTestBase
       super.tearDown();
    }
 
+   private static boolean stopped = false;
+   public static void stopAndThrow() throws HornetQUnBlockedException
+   {
+      if (!stopped)
+      {
+         try
+         {
+            serverToStop.getServer().stop(true);
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+         }
+         try
+         {
+            Thread.sleep(2000);
+         }
+         catch (InterruptedException e)
+         {
+            e.printStackTrace();
+         }
+         stopped = true;
+         throw HornetQClientMessageBundle.BUNDLE.unblockingACall(null);
+      }
+   }
+   @Test
+   @BMRules
+   (
+         rules =
+               {
+                     @BMRule
+                           (
+                                 name = "trace HornetQSessionContext xaEnd",
+                                 targetClass = "org.hornetq.core.protocol.core.impl.HornetQSessionContext",
+                                 targetMethod = "xaEnd",
+                                 targetLocation = "AT EXIT",
+                                 action = "org.hornetq.byteman.tests.BMFailoverTest.stopAndThrow()"
+                           )
+               }
+   )
+   //https://bugzilla.redhat.com/show_bug.cgi?id=1152410
+   public void testFailOnEndAndRetry() throws Exception
+   {
+      serverToStop = liveServer;
+
+      createSessionFactory();
+
+      ClientSession session = createSession(sf, true, false, false);
+
+      session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true);
+
+      ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);
+
+      for (int i = 0; i < 100; i++)
+      {
+         producer.send(createMessage(session, i, true));
+      }
+
+      ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS);
+
+      Xid xid = RandomUtil.randomXid();
+
+      session.start(xid, XAResource.TMNOFLAGS);
+      session.start();
+      // Receive MSGs but don't ack!
+      for (int i = 0; i < 100; i++)
+      {
+         ClientMessage message = consumer.receive(1000);
+
+         Assert.assertNotNull(message);
+
+         assertMessageBody(i, message);
+
+         Assert.assertEquals(i, message.getIntProperty("counter").intValue());
+      }
+      try
+      {
+         //top level prepare
+         session.end(xid, XAResource.TMSUCCESS);
+      }
+      catch (XAException e)
+      {
+         try
+         {
+            //top level abort
+            session.end(xid, XAResource.TMFAIL);
+         }
+         catch (XAException e1)
+         {
+            try
+            {
+               //rollback
+               session.rollback(xid);
+            }
+            catch (XAException e2)
+            {
+            }
+         }
+      }
+      xid = RandomUtil.randomXid();
+      session.start(xid, XAResource.TMNOFLAGS);
+
+      for (int i = 0; i < 50; i++)
+      {
+         ClientMessage message = consumer.receive(1000);
+
+         Assert.assertNotNull(message);
+
+         assertMessageBody(i, message);
+
+         Assert.assertEquals(i, message.getIntProperty("counter").intValue());
+      }
+      session.end(xid, XAResource.TMSUCCESS);
+      session.commit(xid, true);
+   }
+
    @Test
    @BMRules
       (
@@ -170,7 +291,7 @@ public class BMFailoverTest extends FailoverTestBase
       //let's close the consumer so anything pending is handled
       consumer.close();
 
-      assertTrue("actual message count=" + inQ.getMessageCount(), inQ.getMessageCount() == 1);
+      assertEquals(1, getMessageCount(inQ));
    }
 
 
@@ -212,7 +333,7 @@ public class BMFailoverTest extends FailoverTestBase
       sendMessages(session, producer, 10);
       session.commit();
       Queue bindable = (Queue) backupServer.getServer().getPostOffice().getBinding(FailoverTestBase.ADDRESS).getBindable();
-      assertTrue(bindable.getMessageCount() == 10);
+      assertEquals(10, getMessageCount(bindable));
    }
 
    @Test
@@ -266,7 +387,8 @@ public class BMFailoverTest extends FailoverTestBase
          //pass
       }
       Queue bindable = (Queue) backupServer.getServer().getPostOffice().getBinding(FailoverTestBase.ADDRESS).getBindable();
-      assertTrue("messager count = " + bindable.getMessageCount(), bindable.getMessageCount() == 10);
+      assertEquals(10, getMessageCount(bindable));
+
    }
 
    @Override
@@ -303,6 +425,13 @@ public class BMFailoverTest extends FailoverTestBase
       return addClientSession(sf1.createSession(autoCommitSends, autoCommitAcks));
    }
 
+   protected ClientSession
+   createSession(ClientSessionFactory sf1, boolean xa, boolean autoCommitSends,   boolean autoCommitAcks) throws Exception
+   {
+      return addClientSession(sf1.createSession(xa, autoCommitSends, autoCommitAcks));
+   }
+
+
    private void createSessionFactory() throws Exception
    {
       locator.setBlockOnNonDurableSend(true);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BridgeServerLocatorConfigurationTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BridgeServerLocatorConfigurationTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BridgeServerLocatorConfigurationTest.java
index 7b28da0..c30b7b9 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BridgeServerLocatorConfigurationTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/BridgeServerLocatorConfigurationTest.java
@@ -17,9 +17,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.config.BridgeConfiguration;
 import org.hornetq.core.config.CoreQueueConfiguration;
@@ -98,24 +96,31 @@ public class BridgeServerLocatorConfigurationTest extends ServiceTestBase
          ArrayList<String> staticConnectors = new ArrayList<String>();
          staticConnectors.add(server1tc.getName());
 
-         BridgeConfiguration bridgeConfiguration =
-                  new BridgeConfiguration(BRIDGE_NAME, queueName0, forwardAddress, null, null,
-                                          HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                          HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD, BRIDGE_TTL, 1000,
-                                          HornetQClient.DEFAULT_MAX_RETRY_INTERVAL, 1d, -1, 0, 0, true, 1024,
-                                          staticConnectors, false, HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                          HornetQDefaultConfiguration.getDefaultClusterPassword());
+         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+            .setName(BRIDGE_NAME)
+            .setQueueName(queueName0)
+            .setForwardingAddress(forwardAddress)
+            .setConnectionTTL(BRIDGE_TTL)
+            .setRetryInterval(1000)
+            .setReconnectAttempts(0)
+            .setReconnectAttemptsOnSameNode(0)
+            .setConfirmationWindowSize(1024)
+            .setStaticConnectors(staticConnectors);
 
          List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
          bridgeConfigs.add(bridgeConfiguration);
          serverWithBridge.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+            .setAddress(testAddress)
+            .setName(queueName0);
          List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs0.add(queueConfig0);
          serverWithBridge.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+            .setAddress(forwardAddress)
+            .setName(queueName1);
          List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs1.add(queueConfig1);
          server1.getConfiguration().setQueueConfigurations(queueConfigs1);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ClusteredGroupingTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ClusteredGroupingTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ClusteredGroupingTest.java
index 19852f9..cd27a49 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ClusteredGroupingTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ClusteredGroupingTest.java
@@ -19,7 +19,7 @@ import org.hornetq.api.core.HornetQNonExistentQueueException;
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.group.impl.GroupingHandlerConfiguration;
 import org.hornetq.core.server.group.impl.Response;
@@ -419,7 +419,7 @@ public class ClusteredGroupingTest extends ClusterTestBase
 
    public static void pause2(Notification notification)
    {
-      if (notification.getType() == NotificationType.BINDING_REMOVED)
+      if (notification.getType() == CoreNotificationType.BINDING_REMOVED)
       {
          SimpleString clusterName = notification.getProperties()
             .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/HornetQMessageHandlerTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/HornetQMessageHandlerTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/HornetQMessageHandlerTest.java
index 178643f..e800d79 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/HornetQMessageHandlerTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/HornetQMessageHandlerTest.java
@@ -96,6 +96,7 @@ public class HornetQMessageHandlerTest extends HornetQRATestBase
 
       HornetQActivationSpec spec = new HornetQActivationSpec();
       spec.setMaxSession(1);
+      spec.setCallTimeout(1000L);
       spec.setResourceAdapter(qResourceAdapter);
       spec.setUseJNDI(false);
       spec.setDestinationType("javax.jms.Queue");
@@ -131,7 +132,7 @@ public class HornetQMessageHandlerTest extends HornetQRATestBase
       qResourceAdapter.stop();
 
       Binding binding = server.getPostOffice().getBinding(SimpleString.toSimpleString(MDBQUEUEPREFIXED));
-      assertEquals(1, ((Queue) binding.getBindable()).getMessageCount());
+      assertEquals(1, getMessageCount(((Queue) binding.getBindable())));
 
       server.stop();
       server.start();
@@ -175,6 +176,7 @@ public class HornetQMessageHandlerTest extends HornetQRATestBase
 
       HornetQActivationSpec spec = new HornetQActivationSpec();
       spec.setMaxSession(1);
+      spec.setCallTimeout(1000L);
       spec.setResourceAdapter(qResourceAdapter);
       spec.setUseJNDI(false);
       spec.setDestinationType("javax.jms.Queue");
@@ -210,7 +212,8 @@ public class HornetQMessageHandlerTest extends HornetQRATestBase
       qResourceAdapter.stop();
 
       Binding binding = server.getPostOffice().getBinding(SimpleString.toSimpleString(MDBQUEUEPREFIXED));
-      assertEquals(1, ((Queue) binding.getBindable()).getMessageCount());
+      assertEquals(1, getMessageCount(((Queue) binding.getBindable())));
+
 
       server.stop();
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/JMSBridgeReconnectionTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/JMSBridgeReconnectionTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/JMSBridgeReconnectionTest.java
new file mode 100644
index 0000000..e0db2e3
--- /dev/null
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/JMSBridgeReconnectionTest.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.byteman.tests;
+
+import org.hornetq.core.client.impl.ClientProducerCredits;
+import org.hornetq.core.message.impl.MessageInternal;
+import org.hornetq.core.protocol.core.Packet;
+import org.hornetq.core.protocol.core.impl.PacketImpl;
+import org.hornetq.core.protocol.core.impl.wireformat.SessionSendMessage;
+import org.hornetq.jms.bridge.ConnectionFactoryFactory;
+import org.hornetq.jms.bridge.QualityOfServiceMode;
+import org.hornetq.jms.bridge.impl.JMSBridgeImpl;
+import org.hornetq.jms.server.JMSServerManager;
+import org.hornetq.tests.integration.jms.bridge.BridgeTestBase;
+import org.jboss.byteman.contrib.bmunit.BMRule;
+import org.jboss.byteman.contrib.bmunit.BMRules;
+import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+@RunWith(BMUnitRunner.class)
+public class JMSBridgeReconnectionTest extends BridgeTestBase
+{
+
+   @Test
+   @BMRules
+         (
+               rules =
+                     {
+                           @BMRule
+                                 (
+                                       name = "trace clientsessionimpl send",
+                                       targetClass = "org.hornetq.core.protocol.core.impl.ChannelImpl",
+                                       targetMethod = "send",
+                                       targetLocation = "ENTRY",
+                                       action = "org.hornetq.byteman.tests.JMSBridgeReconnectionTest.pause($1);"
+                                 ),
+                           @BMRule
+                                 (
+                                       name = "trace sendRegularMessage",
+                                       targetClass = "org.hornetq.core.client.impl.ClientProducerImpl",
+                                       targetMethod = "sendRegularMessage",
+                                       targetLocation = "ENTRY",
+                                       action = "org.hornetq.byteman.tests.JMSBridgeReconnectionTest.pause2($1,$2,$3);"
+                                 )
+                     }
+         )
+   public void performCrashDestinationStopBridge() throws Exception
+   {
+      hornetQServer = jmsServer1;
+      ConnectionFactoryFactory factInUse0 = cff0;
+      ConnectionFactoryFactory factInUse1 = cff1;
+      final JMSBridgeImpl bridge =
+            new JMSBridgeImpl(factInUse0,
+                  factInUse1,
+                  sourceQueueFactory,
+                  targetQueueFactory,
+                  null,
+                  null,
+                  null,
+                  null,
+                  null,
+                  1000,
+                  -1,
+                  QualityOfServiceMode.DUPLICATES_OK,
+                  10,
+                  -1,
+                  null,
+                  null,
+                  false);
+
+      addHornetQComponent(bridge);
+      bridge.setTransactionManager(newTransactionManager());
+      bridge.start();
+      final CountDownLatch latch = new CountDownLatch(20);
+      Thread clientThread = new Thread(new Runnable()
+      {
+         @Override
+         public void run()
+         {
+            while (bridge.isStarted())
+            {
+               try
+               {
+                  sendMessages(cf0, sourceQueue, 0, 1, false, false);
+                  latch.countDown();
+               }
+               catch (Exception e)
+               {
+                  e.printStackTrace();
+               }
+            }
+         }
+      });
+
+      clientThread.start();
+
+      stopLatch.await(10000, TimeUnit.MILLISECONDS);
+
+      bridge.stop();
+
+      clientThread.join(5000);
+
+      assertTrue(!clientThread.isAlive());
+   }
+
+   public static void pause(Packet packet)
+   {
+      if (packet.getType() == PacketImpl.SESS_SEND)
+      {
+         SessionSendMessage sendMessage = (SessionSendMessage) packet;
+         if (sendMessage.getMessage().containsProperty("__HQ_CID") && count < 0 && !stopped)
+         {
+            try
+            {
+               hornetQServer.stop();
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+            }
+            stopped = true;
+            try
+            {
+               Thread.sleep(5000);
+            }
+            catch (InterruptedException e)
+            {
+               e.printStackTrace();
+            }
+            stopLatch.countDown();
+         }
+      }
+   }
+
+   static JMSServerManager hornetQServer;
+   static boolean stopped = false;
+   static int count = 20;
+   static CountDownLatch stopLatch = new CountDownLatch(1);
+   public static void pause2(MessageInternal msgI, boolean sendBlocking, final ClientProducerCredits theCredits)
+   {
+      if (msgI.containsProperty("__HQ_CID"))
+      {
+         count--;
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/OrphanedConsumerTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/OrphanedConsumerTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/OrphanedConsumerTest.java
new file mode 100644
index 0000000..6a278fe
--- /dev/null
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/OrphanedConsumerTest.java
@@ -0,0 +1,298 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.byteman.tests;
+
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.client.ClientConsumer;
+import org.hornetq.api.core.client.ClientMessage;
+import org.hornetq.api.core.client.ClientProducer;
+import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.Queue;
+import org.hornetq.tests.util.ServiceTestBase;
+import org.jboss.byteman.contrib.bmunit.BMRule;
+import org.jboss.byteman.contrib.bmunit.BMRules;
+import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * @author Clebert Suconic
+ */
+@RunWith(BMUnitRunner.class)
+public class OrphanedConsumerTest extends ServiceTestBase
+{
+
+   private static boolean conditionActive = true;
+
+   public static final boolean isConditionActive()
+   {
+      return conditionActive;
+   }
+
+
+   public static final void setConditionActive(boolean _conditionActive)
+   {
+      conditionActive = _conditionActive;
+   }
+
+
+   public static void throwException() throws Exception
+   {
+      throw new InterruptedException("nice.. I interrupted this!");
+   }
+
+   private HornetQServer server;
+
+   private ServerLocator locator;
+
+   static HornetQServer staticServer;
+
+   /**
+    * {@link #leavingCloseOnTestCountersWhileClosing()} will set this in case of any issues.
+    * the test must then validate for this being null
+    */
+   static AssertionError verification;
+
+   /**
+    * This static method is an entry point for the byteman rules on {@link #testOrphanedConsumers()}
+    * */
+   public static void leavingCloseOnTestCountersWhileClosing()
+   {
+      if (staticServer.getConnectionCount() == 0)
+      {
+         verification = new AssertionError("The connection was closed before the consumers and sessions, this may cause issues on management leaving Orphaned Consumers!");
+      }
+
+      if (staticServer.getSessions().size() == 0)
+      {
+         verification = new AssertionError("The session was closed before the consumers, this may cause issues on management leaving Orphaned Consumers!");
+      }
+   }
+
+
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      super.setUp();
+      setConditionActive(true);
+      /** I'm using the internal method here because closing
+       *  this locator on tear down would hang.
+       *  as we are tweaking with the internal state and making it fail */
+      locator = internalCreateNonHALocator(true);
+   }
+
+
+   @Override
+   @After
+   public void tearDown() throws Exception
+   {
+      super.tearDown();
+      setConditionActive(false);
+
+      staticServer = null;
+   }
+
+
+   /**
+    * This is like being two tests in one:
+    * I - validating that any exception during the close wouldn't stop connection from being closed
+    * II - validating that the connection is only removed at the end of the process and you wouldn't see
+    *      inconsistencies on management
+    * @throws Exception
+    */
+   @Test
+   @BMRules
+      (
+         rules =
+            {
+               @BMRule
+                  (
+                     name = "closeExit",
+                     targetClass = "org.hornetq.core.server.impl.ServerConsumerImpl",
+                     targetMethod = "close",
+                     targetLocation = "AT EXIT",
+                     condition = "org.hornetq.byteman.tests.OrphanedConsumerTest.isConditionActive()",
+                     action = "System.out.println(\"throwing stuff\");throw new InterruptedException()"
+                  ),
+               @BMRule
+                  (
+                     name = "closeEnter",
+                     targetClass = "org.hornetq.core.server.impl.ServerConsumerImpl",
+                     targetMethod = "close",
+                     targetLocation = "ENTRY",
+                     condition = "org.hornetq.byteman.tests.OrphanedConsumerTest.isConditionActive()",
+                     action = "org.hornetq.byteman.tests.OrphanedConsumerTest.leavingCloseOnTestCountersWhileClosing()"
+                  )
+
+            }
+      )
+   public void testOrphanedConsumers() throws Exception
+   {
+      internalTestOrphanedConsumers(false);
+   }
+
+
+   /**
+    * This is like being two tests in one:
+    * I - validating that any exception during the close wouldn't stop connection from being closed
+    * II - validating that the connection is only removed at the end of the process and you wouldn't see
+    *      inconsistencies on management
+    * @throws Exception
+    */
+   @Test
+   @BMRules
+      (
+         rules =
+            {
+               @BMRule
+                  (
+                     name = "closeExit",
+                     targetClass = "org.hornetq.core.server.impl.ServerConsumerImpl",
+                     targetMethod = "close",
+                     targetLocation = "AT EXIT",
+                     condition = "org.hornetq.byteman.tests.OrphanedConsumerTest.isConditionActive()",
+                     action = "System.out.println(\"throwing stuff\");throw new InterruptedException()"
+                  ),
+               @BMRule
+                  (
+                     name = "closeEnter",
+                     targetClass = "org.hornetq.core.server.impl.ServerConsumerImpl",
+                     targetMethod = "close",
+                     targetLocation = "ENTRY",
+                     condition = "org.hornetq.byteman.tests.OrphanedConsumerTest.isConditionActive()",
+                     action = "org.hornetq.byteman.tests.OrphanedConsumerTest.leavingCloseOnTestCountersWhileClosing()"
+                  )
+
+            }
+      )
+   public void testOrphanedConsumersByManagement() throws Exception
+   {
+      internalTestOrphanedConsumers(true);
+   }
+
+   /**
+    *
+    * @param useManagement true = it will use a management operation to make the connection failure, false through ping
+    * @throws Exception
+    */
+   private void internalTestOrphanedConsumers(boolean useManagement) throws Exception
+   {
+      final int NUMBER_OF_MESSAGES = 2;
+      server = createServer(true, true);
+      server.start();
+      staticServer = server;
+
+      locator.setBlockOnNonDurableSend(false);
+      locator.setBlockOnDurableSend(false);
+      locator.setBlockOnAcknowledge(true);
+      locator.setConnectionTTL(1000);
+      locator.setClientFailureCheckPeriod(100);
+      locator.setReconnectAttempts(0);
+      // We are not interested on consumer-window-size on this test
+      // We want that every message is delivered
+      // as we asserting for number of consumers available and round-robin on delivery
+      locator.setConsumerWindowSize(-1);
+
+      ClientSessionFactoryImpl sf = (ClientSessionFactoryImpl)createSessionFactory(locator);
+
+      ClientSession session = sf.createSession(true, true, 0);
+
+      session.createQueue("queue", "queue1", true);
+      session.createQueue("queue", "queue2", true);
+
+      ClientProducer prod = session.createProducer("queue");
+
+      ClientConsumer consumer = session.createConsumer("queue1");
+      ClientConsumer consumer2 = session.createConsumer("queue2");
+
+
+      Queue queue1 = server.locateQueue(new SimpleString("queue1"));
+
+      Queue queue2 = server.locateQueue(new SimpleString("queue2"));
+
+      session.start();
+
+
+      if (!useManagement)
+      {
+         sf.stopPingingAfterOne();
+
+         for (long timeout = System.currentTimeMillis() + 6000; timeout > System.currentTimeMillis() && server.getConnectionCount() != 0; )
+         {
+            Thread.sleep(100);
+         }
+
+         // an extra second to avoid races of something closing the session while we are asserting it
+         Thread.sleep(1000);
+      }
+      else
+      {
+         server.getHornetQServerControl().closeConnectionsForAddress("127.0.0.1");
+      }
+
+      if (verification != null)
+      {
+         throw verification;
+      }
+
+      assertEquals(0, queue1.getConsumerCount());
+      assertEquals(0, queue2.getConsumerCount());
+
+      setConditionActive(false);
+
+      locator = internalCreateNonHALocator(true);
+
+      locator.setBlockOnNonDurableSend(false);
+      locator.setBlockOnDurableSend(false);
+      locator.setBlockOnAcknowledge(true);
+      locator.setReconnectAttempts(0);
+      locator.setConsumerWindowSize(-1);
+
+      sf = (ClientSessionFactoryImpl)locator.createSessionFactory();
+      session = sf.createSession(true, true, 0);
+
+
+      session.start();
+
+
+      prod = session.createProducer("queue");
+
+      for (int i = 0; i < NUMBER_OF_MESSAGES; i++)
+      {
+         ClientMessage message = session.createMessage(true);
+         message.putIntProperty("i", i);
+         prod.send(message);
+      }
+
+      consumer = session.createConsumer("queue1");
+      consumer2 = session.createConsumer("queue2");
+
+      for (int i = 0; i < NUMBER_OF_MESSAGES; i++)
+      {
+         assertNotNull(consumer.receive(5000));
+         assertNotNull(consumer2.receive(5000));
+      }
+
+      session.close();
+   }
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/PagingLeakTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/PagingLeakTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/PagingLeakTest.java
new file mode 100644
index 0000000..654de4c
--- /dev/null
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/PagingLeakTest.java
@@ -0,0 +1,270 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.byteman.tests;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.ClientConsumer;
+import org.hornetq.api.core.client.ClientMessage;
+import org.hornetq.api.core.client.ClientProducer;
+import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.api.core.client.ClientSessionFactory;
+import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.paging.cursor.impl.PagePositionImpl;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServers;
+import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
+import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.tests.util.ServiceTestBase;
+import org.jboss.byteman.contrib.bmunit.BMRule;
+import org.jboss.byteman.contrib.bmunit.BMRules;
+import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(BMUnitRunner.class)
+public class PagingLeakTest extends ServiceTestBase
+{
+
+   private static final AtomicInteger pagePosInstances = new AtomicInteger(0);
+
+   public static void newPosition()
+   {
+      pagePosInstances.incrementAndGet();
+   }
+
+   public static void deletePosition()
+   {
+      pagePosInstances.decrementAndGet();
+   }
+
+   @Before
+   public void setup()
+   {
+      pagePosInstances.set(0);
+   }
+
+   @Test
+   @BMRules
+      (
+         rules =
+            {
+               @BMRule
+                  (
+                     name = "newPosition",
+                     targetClass = "org.hornetq.core.paging.cursor.impl.PagePositionImpl",
+                     targetMethod = "<init>()",
+                     targetLocation = "ENTRY",
+                     action = "org.hornetq.byteman.tests.PagingLeakTest.newPosition()"
+                  ),
+               @BMRule
+                  (
+                     name = "finalPosition",
+                     targetClass = "org.hornetq.core.paging.cursor.impl.PagePositionImpl",
+                     targetMethod = "finalize",
+                     targetLocation = "ENTRY",
+                     action = "org.hornetq.byteman.tests.PagingLeakTest.deletePosition()"
+                  )
+            }
+      )
+   public void testValidateLeak() throws Throwable
+   {
+
+      List<PagePositionImpl> positions = new ArrayList<PagePositionImpl>();
+
+      for (int i = 0; i < 300; i++)
+      {
+         positions.add(new PagePositionImpl(3, 3));
+      }
+
+      long timeout = System.currentTimeMillis() + 5000;
+      while (pagePosInstances.get() != 300 && timeout > System.currentTimeMillis())
+      {
+         forceGC();
+      }
+
+      // This is just to validate the rules are correctly applied on byteman
+      assertEquals("You have changed something on PagePositionImpl in such way that these byteman rules are no longer working", 300, pagePosInstances.get());
+
+      positions.clear();
+
+      timeout = System.currentTimeMillis() + 5000;
+      while (pagePosInstances.get() != 0 && timeout > System.currentTimeMillis())
+      {
+         forceGC();
+      }
+
+      // This is just to validate the rules are correctly applied on byteman
+      assertEquals("You have changed something on PagePositionImpl in such way that these byteman rules are no longer working", 0, pagePosInstances.get());
+
+      final ArrayList<Exception> errors = new ArrayList<Exception>();
+      // A backup that will be waiting to be activated
+      Configuration conf = createDefaultConfig(true)
+         .setSecurityEnabled(false)
+         .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+
+      final HornetQServer server = HornetQServers.newHornetQServer(conf, true);
+      addServer(server);
+
+
+      server.start();
+
+
+      AddressSettings settings = new AddressSettings();
+      settings.setPageSizeBytes(20 * 1024);
+      settings.setMaxSizeBytes(200 * 1024);
+      settings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE);
+
+
+      server.getAddressSettingsRepository().addMatch("#", settings);
+
+
+      final SimpleString address = new SimpleString("pgdAddress");
+
+      class Consumer extends Thread
+      {
+         final ServerLocator locator;
+         final ClientSessionFactory sf;
+         final ClientSession session;
+         final ClientConsumer consumer;
+
+         final int sleepTime;
+         final int maxConsumed;
+
+         Consumer(int sleepTime, String suffix, int maxConsumed) throws Exception
+         {
+
+            server.createQueue(address, address.concat(suffix), null, true, false);
+
+            this.sleepTime = sleepTime;
+            locator = createInVMLocator(0);
+            sf = locator.createSessionFactory();
+            session = sf.createSession(true, true);
+            consumer = session.createConsumer(address.concat(suffix));
+
+            this.maxConsumed = maxConsumed;
+         }
+
+         public void run()
+         {
+            try
+            {
+               session.start();
+
+               long lastTime = System.currentTimeMillis();
+
+               for (long i = 0; i < maxConsumed; i++)
+               {
+                  ClientMessage msg = consumer.receive(5000);
+
+                  if (msg == null)
+                  {
+                     errors.add(new Exception("didn't receive a message"));
+                     return;
+                  }
+
+                  msg.acknowledge();
+
+
+                  if (sleepTime > 0)
+                  {
+
+                     Thread.sleep(sleepTime);
+                  }
+
+                  if (i % 1000 == 0)
+                  {
+                     System.out.println("Consumed " + i + " events in " + (System.currentTimeMillis() - lastTime));
+                     lastTime = System.currentTimeMillis();
+                  }
+               }
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+            }
+         }
+      }
+
+
+      int numberOfMessages = 10000;
+
+      Consumer consumer1 = new Consumer(100, "-1", 150);
+      Consumer consumer2 = new Consumer(0, "-2", numberOfMessages);
+
+      final ServerLocator locator = createInVMLocator(0);
+      final ClientSessionFactory sf = locator.createSessionFactory();
+      final ClientSession session = sf.createSession(true, true);
+      final ClientProducer producer = session.createProducer(address);
+
+
+      byte[] b = new byte[1024];
+
+
+      for (long i = 0; i < numberOfMessages; i++)
+      {
+         ClientMessage msg = session.createMessage(true);
+         msg.getBodyBuffer().writeBytes(b);
+         producer.send(msg);
+
+         if (i == 1000)
+         {
+            System.out.println("Starting consumers!!!");
+            consumer1.start();
+            consumer2.start();
+         }
+
+         if (i % 1000 == 0)
+         {
+            validateInstances();
+         }
+
+      }
+
+
+      consumer1.join();
+      consumer2.join();
+
+      validateInstances();
+      Throwable elast = null;
+
+      for (Throwable e : errors)
+      {
+         e.printStackTrace();
+         elast = e;
+      }
+
+      if (elast != null)
+      {
+         throw elast;
+      }
+
+   }
+
+   private void validateInstances()
+   {
+      forceGC();
+      int count2 = pagePosInstances.get();
+      Assert.assertTrue("There is a leak, you shouldn't have this many instances (" + count2 + ")", count2 < 5000);
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailoverTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailoverTest.java
index 22a39da..05c7245 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailoverTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailoverTest.java
@@ -14,6 +14,8 @@ package org.hornetq.byteman.tests;
 
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientMessage;
+import org.hornetq.core.config.ScaleDownConfiguration;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
 import org.hornetq.core.remoting.impl.netty.TransportConstants;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.tests.integration.cluster.distribution.ClusterTestBase;
@@ -37,23 +39,30 @@ public class ScaleDownFailoverTest extends ClusterTestBase
    {
       super.setUp();
       stopCount = 0;
-      setupServer(0, isFileStorage(), isNetty());
-      setupServer(1, isFileStorage(), isNetty());
-      setupServer(2, isFileStorage(), isNetty());
+      setupLiveServer(0, isFileStorage(), false, isNetty(), true);
+      setupLiveServer(1, isFileStorage(), false, isNetty(), true);
+      setupLiveServer(2, isFileStorage(), false, isNetty(), true);
+      ScaleDownConfiguration scaleDownConfiguration = new ScaleDownConfiguration();
+      ScaleDownConfiguration scaleDownConfiguration2 = new ScaleDownConfiguration();
+      scaleDownConfiguration2.setEnabled(false);
+      ScaleDownConfiguration scaleDownConfiguration3 = new ScaleDownConfiguration();
+      scaleDownConfiguration3.setEnabled(false);
+      ((LiveOnlyPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration);
+      ((LiveOnlyPolicyConfiguration) servers[1].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration2);
+      ((LiveOnlyPolicyConfiguration) servers[2].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration3);
       if (isGrouped())
       {
-         servers[0].getConfiguration().getHAPolicy().setScaleDownGroupName("bill");
-         servers[1].getConfiguration().getHAPolicy().setScaleDownGroupName("bill");
-         servers[2].getConfiguration().getHAPolicy().setScaleDownGroupName("bill");
+         scaleDownConfiguration.setGroupName("bill");
+         scaleDownConfiguration2.setGroupName("bill");
+         scaleDownConfiguration3.setGroupName("bill");
       }
-      servers[0].getConfiguration().getHAPolicy().setScaleDown(true);
       staticServers = servers;
       setupClusterConnection("cluster0", "queues", false, 1, isNetty(), 0, 1, 2);
       setupClusterConnection("cluster1", "queues", false, 1, isNetty(), 1, 0, 2);
       setupClusterConnection("cluster2", "queues", false, 1, isNetty(), 2, 0, 1);
-      servers[0].getConfiguration().getHAPolicy().getScaleDownConnectors().addAll(servers[0].getConfiguration().getClusterConfigurations().iterator().next().getStaticConnectors());
-      servers[1].getConfiguration().getHAPolicy().getScaleDownConnectors().addAll(servers[1].getConfiguration().getClusterConfigurations().iterator().next().getStaticConnectors());
-      servers[2].getConfiguration().getHAPolicy().getScaleDownConnectors().addAll(servers[2].getConfiguration().getClusterConfigurations().iterator().next().getStaticConnectors());
+      scaleDownConfiguration.getConnectors().addAll(servers[0].getConfiguration().getClusterConfigurations().iterator().next().getStaticConnectors());
+      scaleDownConfiguration2.getConnectors().addAll(servers[1].getConfiguration().getClusterConfigurations().iterator().next().getStaticConnectors());
+      scaleDownConfiguration3.getConnectors().addAll(servers[2].getConfiguration().getClusterConfigurations().iterator().next().getStaticConnectors());
 
       startServers(0, 1, 2);
       setupSessionFactory(0, isNetty());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailureTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailureTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailureTest.java
index 1a7b254..44cd4df 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailureTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/ScaleDownFailureTest.java
@@ -13,6 +13,8 @@
 package org.hornetq.byteman.tests;
 
 import org.hornetq.api.core.client.ClientMessage;
+import org.hornetq.core.config.ScaleDownConfiguration;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
 import org.hornetq.tests.integration.cluster.distribution.ClusterTestBase;
 import org.jboss.byteman.contrib.bmunit.BMRule;
 import org.jboss.byteman.contrib.bmunit.BMUnitRunner;
@@ -30,14 +32,15 @@ public class ScaleDownFailureTest extends ClusterTestBase
    public void setUp() throws Exception
    {
       super.setUp();
-      setupServer(0, isFileStorage(), isNetty());
-      setupServer(1, isFileStorage(), isNetty());
+      setupLiveServer(0, isFileStorage(), false, isNetty(), true);
+      setupLiveServer(1, isFileStorage(), false, isNetty(), true);
       if (isGrouped())
       {
-         servers[0].getConfiguration().getHAPolicy().setScaleDownGroupName("bill");
-         servers[1].getConfiguration().getHAPolicy().setScaleDownGroupName("bill");
+         ScaleDownConfiguration scaleDownConfiguration = new ScaleDownConfiguration();
+         scaleDownConfiguration.setGroupName("bill");
+         ((LiveOnlyPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration);
+         ((LiveOnlyPolicyConfiguration) servers[1].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(scaleDownConfiguration);
       }
-      servers[0].getConfiguration().getHAPolicy().setScaleDown(true);
       setupClusterConnection("cluster0", "queues", false, 1, isNetty(), 0, 1);
       setupClusterConnection("cluster1", "queues", false, 1, isNetty(), 1, 0);
       startServers(0, 1);
@@ -62,7 +65,7 @@ public class ScaleDownFailureTest extends ClusterTestBase
       closeAllConsumers();
       closeAllSessionFactories();
       closeAllServerLocatorsFactories();
-      servers[0].getConfiguration().getHAPolicy().setScaleDown(false);
+      ((LiveOnlyPolicyConfiguration) servers[0].getConfiguration().getHAPolicyConfiguration()).setScaleDownConfiguration(null);
       stopServers(0, 1);
       super.tearDown();
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StartStopDeadlockTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StartStopDeadlockTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StartStopDeadlockTest.java
index 28bd89c..a813bfb 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StartStopDeadlockTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StartStopDeadlockTest.java
@@ -17,9 +17,10 @@ import java.util.concurrent.atomic.AtomicInteger;
 
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.jms.server.impl.JMSServerManagerImpl;
 import org.hornetq.tests.unit.util.InVMNamingContext;
 import org.hornetq.tests.util.ServiceTestBase;
@@ -76,20 +77,20 @@ public class StartStopDeadlockTest extends ServiceTestBase
    {
 
       // A live server that will always be crashed
-      Configuration confLive = createDefaultConfig(true);
-      confLive.setSecurityEnabled(false);
-      confLive.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      confLive.getConnectorConfigurations().put("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+      Configuration confLive = createDefaultConfig(true)
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration())
+         .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
       final HornetQServer serverLive = HornetQServers.newHornetQServer(confLive);
       serverLive.start();
       addServer(serverLive);
 
 
       // A backup that will be waiting to be activated
-      Configuration conf = createDefaultConfig(true);
-      conf.setSecurityEnabled(false);
-      conf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      conf.getConnectorConfigurations().put("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+      Configuration conf = createDefaultConfig(true)
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration())
+         .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
 
       final HornetQServer server = HornetQServers.newHornetQServer(conf, true);
       addServer(server);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StompInternalStateTest.java
----------------------------------------------------------------------
diff --git a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StompInternalStateTest.java b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StompInternalStateTest.java
index b446f13..7bde640 100644
--- a/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StompInternalStateTest.java
+++ b/tests/byteman-tests/src/test/java/org/hornetq/byteman/tests/StompInternalStateTest.java
@@ -20,7 +20,7 @@ import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.protocol.stomp.StompProtocolManagerFactory;
 import org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory;
@@ -88,12 +88,12 @@ public class StompInternalStateTest extends ServiceTestBase
    @Override
    protected Configuration createDefaultConfig(final boolean netty) throws Exception
    {
-      Configuration config = super.createDefaultConfig(netty);
-      config.setSecurityEnabled(false);
-      config.setPersistenceEnabled(false);
+      Configuration config = super.createDefaultConfig(netty)
+         .setSecurityEnabled(false)
+         .setPersistenceEnabled(false);
 
       Map<String, Object> params = new HashMap<String, Object>();
-      params.put(TransportConstants.PROTOCOL_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
+      params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
       params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT);
       params.put(TransportConstants.STOMP_CONSUMERS_CREDIT, "-1");
       TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params);
@@ -107,14 +107,14 @@ public class StompInternalStateTest extends ServiceTestBase
    public void verifyBindingAddRemove(Notification noti, Object obj)
    {
       Set<String> destinations = (Set<String>)obj;
-      if (noti.getType() == NotificationType.BINDING_ADDED)
+      if (noti.getType() == CoreNotificationType.BINDING_ADDED)
       {
          if (!destinations.contains(STOMP_QUEUE_NAME))
          {
             resultTestStompProtocolManagerLeak += "didn't save the queue when binding added " + destinations;
          }
       }
-      else if (noti.getType() == NotificationType.BINDING_REMOVED)
+      else if (noti.getType() == CoreNotificationType.BINDING_REMOVED)
       {
          if (destinations.contains(STOMP_QUEUE_NAME))
          {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/config/logging.properties.trace
----------------------------------------------------------------------
diff --git a/tests/config/logging.properties.trace b/tests/config/logging.properties.trace
new file mode 100644
index 0000000..5bafa56
--- /dev/null
+++ b/tests/config/logging.properties.trace
@@ -0,0 +1,68 @@
+#
+# JBoss, Home of Professional Open Source.
+# Copyright 2010, Red Hat, Inc., and individual contributors
+# as indicated by the @author tags. See the copyright.txt file 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.
+#
+
+# this is an example of a logging configuration where you could enable tracing at the testsuite
+
+# Additional logger names to configure (root logger is always configured)
+# Root logger option
+loggers=org.jboss.logging,org.hornetq.core.server,org.hornetq.utils,org.hornetq.journal,org.hornetq.jms,org.hornetq.ra,org.hornetq.tests.unit,org.hornetq.tests.integration,org.hornetq.jms.tests
+
+# Root logger level
+logger.level=INFO
+# HornetQ logger levels
+logger.org.hornetq.core.server.level=TRACE
+logger.org.hornetq.journal.level=INFO
+logger.org.hornetq.utils.level=INFO
+logger.org.hornetq.jms.level=INFO
+logger.org.hornetq.ra.level=INFO
+logger.org.hornetq.tests.unit.level=INFO
+logger.org.hornetq.tests.integration.level=INFO
+logger.org.hornetq.jms.tests.level=INFO
+
+# Root logger handlers
+logger.handlers=CONSOLE,TEST
+#logger.handlers=CONSOLE,FILE
+
+# Console handler configuration
+handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
+handler.CONSOLE.properties=autoFlush
+handler.CONSOLE.level=FINE
+handler.CONSOLE.autoFlush=true
+handler.CONSOLE.formatter=PATTERN
+
+# File handler configuration
+handler.FILE=org.jboss.logmanager.handlers.FileHandler
+handler.FILE.level=FINE
+handler.FILE.properties=autoFlush,fileName
+handler.FILE.autoFlush=true
+handler.FILE.fileName=target/hornetq.log
+handler.FILE.formatter=PATTERN
+
+# Console handler configuration
+handler.TEST=org.hornetq.tests.logging.AssertionLoggerHandler
+handler.TEST.level=TRACE
+handler.TEST.formatter=PATTERN
+
+# Formatter pattern configuration
+formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
+formatter.PATTERN.properties=pattern
+formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/pom.xml
----------------------------------------------------------------------
diff --git a/tests/integration-tests/pom.xml b/tests/integration-tests/pom.xml
index 05fc719..f25fddc 100644
--- a/tests/integration-tests/pom.xml
+++ b/tests/integration-tests/pom.xml
@@ -13,8 +13,8 @@
 
    <properties>
       <hornetq.basedir>${project.basedir}/../..</hornetq.basedir>
-      <vertx.version>2.1RC1</vertx.version>
-      <vertx.testtools.version>2.0.2-final</vertx.testtools.version>
+      <vertx.version>2.1.2</vertx.version>
+      <vertx.testtools.version>2.0.3-final</vertx.testtools.version>
    </properties>
 
    <dependencies>
@@ -66,6 +66,11 @@
       </dependency>
       <dependency>
          <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-tools</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
          <artifactId>hornetq-twitter-integration</artifactId>
          <version>${project.version}</version>
       </dependency>
@@ -96,12 +101,12 @@
       </dependency>
       <dependency>
          <groupId>org.hornetq</groupId>
-         <artifactId>hornetq-aerogear-integration</artifactId>
+         <artifactId>hornetq-openwire-protocol</artifactId>
          <version>${project.version}</version>
       </dependency>
       <dependency>
          <groupId>org.hornetq</groupId>
-         <artifactId>hornetq-tools</artifactId>
+         <artifactId>hornetq-aerogear-integration</artifactId>
          <version>${project.version}</version>
       </dependency>
       <dependency>
@@ -121,11 +126,6 @@
          <artifactId>twitter4j-core</artifactId>
       </dependency>
       <dependency>
-         <groupId>com.hazelcast</groupId>
-         <artifactId>hazelcast</artifactId>
-         <version>2.6.6</version>
-      </dependency>
-      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
       </dependency>
@@ -147,9 +147,13 @@
          <version>0.24</version>
       </dependency>
       <dependency>
-         <groupId>org.apache.qpid</groupId>
-         <artifactId>proton-jms</artifactId>
-      </dependency>
+          <groupId>org.apache.qpid</groupId>
+          <artifactId>proton-j</artifactId>
+       </dependency>
+       <dependency>
+          <groupId>org.apache.qpid</groupId>
+          <artifactId>proton-jms</artifactId>
+       </dependency>
       <dependency>
          <groupId>org.apache.qpid</groupId>
          <artifactId>qpid-client</artifactId>
@@ -205,6 +209,22 @@
          <version>${vertx.testtools.version}</version>
          <scope>test</scope>
       </dependency>
+      <dependency>
+         <groupId>org.apache.activemq</groupId>
+         <artifactId>activemq-client</artifactId>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.apache.geronimo.specs</groupId>
+         <artifactId>geronimo-j2ee-management_1.1_spec</artifactId>
+         <version>1.0.1</version>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.ironjacamar</groupId>
+         <artifactId>ironjacamar-core-api</artifactId>
+         <scope>test</scope>
+      </dependency>
    </dependencies>
 
    <build>
@@ -234,7 +254,6 @@
                <skipTests>${skipIntegrationTests}</skipTests>
                <excludes>
                   <exclude>**/ReplicatedJMSFailoverTest.java</exclude>
-                  <exclude>**/Colocated*Test.java</exclude>
                   <exclude>org/hornetq/tests/util/*.java</exclude>
                </excludes>
                <argLine>-Djgroups.bind_addr=::1 ${hornetq-surefire-argline}</argLine>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/DuplicateDetectionTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/DuplicateDetectionTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/DuplicateDetectionTest.java
index fc66974..e1a859e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/DuplicateDetectionTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/DuplicateDetectionTest.java
@@ -29,6 +29,7 @@ import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.message.impl.MessageImpl;
 import org.hornetq.core.postoffice.impl.PostOfficeImpl;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.transaction.impl.XidImpl;
@@ -169,6 +170,8 @@ public class DuplicateDetectionTest extends ServiceTestBase
 
       ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
 
+      locator.setBlockOnNonDurableSend(true);
+
       ClientSessionFactory sf = createSessionFactory(locator);
 
       ClientSession session = sf.createSession(false, true, true);
@@ -209,10 +212,23 @@ public class DuplicateDetectionTest extends ServiceTestBase
          message2 = consumer.receiveImmediate();
          Assert.assertNull(message2);
 
+         message = createMessage(session, 3);
+         message.putBytesProperty(MessageImpl.HDR_BRIDGE_DUPLICATE_ID, dupID.getData());
+         producer.send(message);
+         message2 = consumer.receive(1000);
+         Assert.assertEquals(3, message2.getObjectProperty(propKey));
+
+         message = createMessage(session, 4);
+         message.putBytesProperty(MessageImpl.HDR_BRIDGE_DUPLICATE_ID, dupID.getData());
+         producer.send(message);
+         message2 = consumer.receiveImmediate();
+         Assert.assertNull(message2);
+
          producer.close();
          consumer.close();
 
-         Assert.assertEquals(1, ((PostOfficeImpl)messagingService.getPostOffice()).getDuplicateIDCaches().size());
+         // there will be 2 ID caches, one for messages using "_HQ_DUPL_ID" and one for "_HQ_BRIDGE_DUP"
+         Assert.assertEquals(2, ((PostOfficeImpl)messagingService.getPostOffice()).getDuplicateIDCaches().size());
          session.deleteQueue(queueName);
          Assert.assertEquals(0, ((PostOfficeImpl)messagingService.getPostOffice()).getDuplicateIDCaches().size());
       }
@@ -1275,9 +1291,8 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -1361,11 +1376,10 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
       final int theCacheSize = 5;
 
-      conf.setIDCacheSize(theCacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(theCacheSize);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -1443,12 +1457,11 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
       final int initialCacheSize = 10;
       final int subsequentCacheSize = 5;
 
-      conf.setIDCacheSize(initialCacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(initialCacheSize);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -1537,12 +1550,11 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
       final int initialCacheSize = 10;
       final int subsequentCacheSize = 5;
 
-      conf.setIDCacheSize(initialCacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(initialCacheSize);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -1641,11 +1653,9 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
-
-      conf.setPersistIDCache(false);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize)
+         .setPersistIDCache(false);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -1729,11 +1739,9 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
-
-      conf.setPersistIDCache(false);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize)
+         .setPersistIDCache(false);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -1821,9 +1829,8 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -1941,11 +1948,9 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
-
-      conf.setPersistIDCache(false);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize)
+         .setPersistIDCache(false);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -2047,9 +2052,8 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -2149,9 +2153,8 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       messagingService.stop();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize);
 
       HornetQServer messagingService2 = createServer(conf);
 
@@ -2263,9 +2266,8 @@ public class DuplicateDetectionTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setIDCacheSize(cacheSize);
+      Configuration conf = createDefaultConfig()
+         .setIDCacheSize(cacheSize);
 
       messagingService = createServer(true, conf);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/String64KLimitTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/String64KLimitTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/String64KLimitTest.java
index b14d985..5ef7f85 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/String64KLimitTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/String64KLimitTest.java
@@ -207,9 +207,8 @@ public class String64KLimitTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration config = createBasicConfig();
-      config.setSecurityEnabled(false);
-      config.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration config = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       server = addServer(HornetQServers.newHornetQServer(config, false));
       server.start();
       locator = createInVMNonHALocator();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/aerogear/AeroGearBasicServerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/aerogear/AeroGearBasicServerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/aerogear/AeroGearBasicServerTest.java
index ae4223c..41819bb 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/aerogear/AeroGearBasicServerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/aerogear/AeroGearBasicServerTest.java
@@ -73,7 +73,6 @@ public class AeroGearBasicServerTest extends ServiceTestBase
       connector0.setHost("localhost");
       jetty.addConnector(connector0);
       jetty.start();
-      Configuration configuration = createDefaultConfig();
       HashMap<String, Object> params = new HashMap();
       params.put(AeroGearConstants.QUEUE_NAME, "testQueue");
       params.put(AeroGearConstants.ENDPOINT_NAME, "http://localhost:8080");
@@ -86,10 +85,15 @@ public class AeroGearBasicServerTest extends ServiceTestBase
       params.put(AeroGearConstants.DEVICE_TYPE_NAME, "android,ipad");
       params.put(AeroGearConstants.SOUND_NAME, "sound1");
       params.put(AeroGearConstants.VARIANTS_NAME, "variant1,variant2");
-      configuration.getConnectorServiceConfigurations().add(
-         new ConnectorServiceConfiguration(AeroGearConnectorServiceFactory.class.getName(), params, "TestAeroGearService"));
-
-      configuration.getQueueConfigurations().add(new CoreQueueConfiguration("testQueue", "testQueue", null, true));
+      Configuration configuration = createDefaultConfig()
+         .addConnectorServiceConfiguration(
+            new ConnectorServiceConfiguration()
+               .setFactoryClassName(AeroGearConnectorServiceFactory.class.getName())
+               .setParams(params)
+               .setName("TestAeroGearService"))
+         .addQueueConfiguration(new CoreQueueConfiguration()
+                                   .setAddress("testQueue")
+                                   .setName("testQueue"));
       server = createServer(configuration);
       server.start();
 
@@ -151,9 +155,6 @@ public class AeroGearBasicServerTest extends ServiceTestBase
       String badge = body.getString("badge");
       assertNotNull(badge);
       assertEquals(badge, "99");
-      Integer ttl = body.getInt("ttl");
-      assertNotNull(ttl);
-      assertEquals(ttl.intValue(), 3600);
       JSONArray jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("variants");
       assertNotNull(jsonArray);
       assertEquals(jsonArray.getString(0), "variant1");
@@ -167,6 +168,9 @@ public class AeroGearBasicServerTest extends ServiceTestBase
       assertNotNull(jsonArray);
       assertEquals(jsonArray.getString(0), "android");
       assertEquals(jsonArray.getString(1), "ipad");
+      Integer ttl = (Integer) aeroGearHandler.jsonObject.get("ttl");
+      assertNotNull(ttl);
+      assertEquals(ttl.intValue(), 3600);
       latch = new CountDownLatch(1);
       aeroGearHandler.resetLatch(latch);
 
@@ -194,9 +198,6 @@ public class AeroGearBasicServerTest extends ServiceTestBase
       badge = body.getString("badge");
       assertNotNull(badge);
       assertEquals(badge, "111");
-      ttl = body.getInt("ttl");
-      assertNotNull(ttl);
-      assertEquals(ttl.intValue(), 10000);
       jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("variants");
       assertNotNull(jsonArray);
       assertEquals(jsonArray.getString(0), "v1");
@@ -209,6 +210,9 @@ public class AeroGearBasicServerTest extends ServiceTestBase
       assertNotNull(jsonArray);
       assertEquals(jsonArray.getString(0), "dev1");
       assertEquals(jsonArray.getString(1), "dev2");
+      ttl = (Integer) aeroGearHandler.jsonObject.get("ttl");
+      assertNotNull(ttl);
+      assertEquals(ttl.intValue(), 10000);
       session.start();
       ClientMessage message = session.createConsumer("testQueue").receiveImmediate();
       assertNull(message);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/AcknowledgeTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/AcknowledgeTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/AcknowledgeTest.java
index d5b7426..5d0362c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/AcknowledgeTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/AcknowledgeTest.java
@@ -30,8 +30,10 @@ import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.MessageHandler;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.ClientSessionInternal;
+import org.hornetq.core.protocol.core.impl.HornetQConsumerContext;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.Queue;
+import org.hornetq.spi.core.remoting.ConsumerContext;
 import org.hornetq.tests.integration.IntegrationTestLogger;
 import org.hornetq.tests.util.ServiceTestBase;
 import org.hornetq.utils.UUID;
@@ -333,9 +335,9 @@ public class AcknowledgeTest extends ServiceTestBase
       }
 
       @Override
-      public Object getId()
+      public ConsumerContext getConsumerContext()
       {
-         return id;
+         return new HornetQConsumerContext(this.id);
       }
 
       @Override
@@ -363,9 +365,9 @@ public class AcknowledgeTest extends ServiceTestBase
       }
 
       @Override
-      public void setMessageHandler(MessageHandler handler) throws HornetQException
+      public FakeConsumerWithID setMessageHandler(MessageHandler handler) throws HornetQException
       {
-
+         return this;
       }
 
       @Override
@@ -410,9 +412,9 @@ public class AcknowledgeTest extends ServiceTestBase
       }
 
       @Override
-      public void setUserID(UUID userID)
+      public FakeMessageWithID setUserID(UUID userID)
       {
-
+         return this;
       }
 
       @Override
@@ -440,9 +442,9 @@ public class AcknowledgeTest extends ServiceTestBase
       }
 
       @Override
-      public void setDurable(boolean durable)
+      public FakeMessageWithID setDurable(boolean durable)
       {
-
+         return this;
       }
 
       @Override
@@ -458,9 +460,9 @@ public class AcknowledgeTest extends ServiceTestBase
       }
 
       @Override
-      public void setExpiration(long expiration)
+      public FakeMessageWithID setExpiration(long expiration)
       {
-
+         return this;
       }
 
       @Override
@@ -470,9 +472,9 @@ public class AcknowledgeTest extends ServiceTestBase
       }
 
       @Override
-      public void setTimestamp(long timestamp)
+      public FakeMessageWithID setTimestamp(long timestamp)
       {
-
+         return this;
       }
 
       @Override
@@ -482,9 +484,9 @@ public class AcknowledgeTest extends ServiceTestBase
       }
 
       @Override
-      public void setPriority(byte priority)
+      public FakeMessageWithID setPriority(byte priority)
       {
-
+         return this;
       }
 
       @Override
@@ -810,5 +812,17 @@ public class AcknowledgeTest extends ServiceTestBase
       {
          return null;
       }
+
+      @Override
+      public FakeMessageWithID writeBodyBufferBytes(byte[] bytes)
+      {
+         return this;
+      }
+
+      @Override
+      public FakeMessageWithID writeBodyBufferString(String string)
+      {
+         return this;
+      }
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CommitRollbackTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CommitRollbackTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CommitRollbackTest.java
index d4e88b9..ce687ac 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CommitRollbackTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CommitRollbackTest.java
@@ -156,9 +156,9 @@ public class CommitRollbackTest extends ServiceTestBase
       cc2.close();
       session.rollback();
       Assert.assertEquals(0, q2.getDeliveringCount());
-      Assert.assertEquals(numMessages, q.getMessageCount());
+      Assert.assertEquals(numMessages, getMessageCount(q));
       Assert.assertEquals(0, q2.getDeliveringCount());
-      Assert.assertEquals(numMessages, q.getMessageCount());
+      Assert.assertEquals(numMessages, getMessageCount(q));
       sendSession.close();
       session.close();
    }
@@ -209,10 +209,10 @@ public class CommitRollbackTest extends ServiceTestBase
       Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
       Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable();
       Assert.assertEquals(numMessages, q.getDeliveringCount());
-      Assert.assertEquals(numMessages, q.getMessageCount());
+      Assert.assertEquals(numMessages, getMessageCount(q));
       session.commit();
       Assert.assertEquals(0, q.getDeliveringCount());
-      Assert.assertEquals(0, q.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(q));
       sendSession.close();
       session.close();
 
@@ -243,11 +243,11 @@ public class CommitRollbackTest extends ServiceTestBase
       Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
       Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable();
       Assert.assertEquals(numMessages, q.getDeliveringCount());
-      Assert.assertEquals(numMessages, q.getMessageCount());
+      Assert.assertEquals(numMessages, getMessageCount(q));
       session.stop();
       session.rollback();
       Assert.assertEquals(0, q.getDeliveringCount());
-      Assert.assertEquals(numMessages, q.getMessageCount());
+      Assert.assertEquals(numMessages, getMessageCount(q));
       latch = new CountDownLatch(numMessages);
       cc.setMessageHandler(new ackHandler(session, latch));
       session.start();


[24/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/deployers/impl/FileConfigurationParser.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/deployers/impl/FileConfigurationParser.java b/hornetq-server/src/main/java/org/hornetq/core/deployers/impl/FileConfigurationParser.java
index ae5b41f..bed8d0a 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/deployers/impl/FileConfigurationParser.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/deployers/impl/FileConfigurationParser.java
@@ -32,13 +32,20 @@ import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.UDPBroadcastGroupConfiguration;
 import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.core.config.BackupStrategy;
 import org.hornetq.core.config.BridgeConfiguration;
 import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.ConnectorServiceConfiguration;
 import org.hornetq.core.config.CoreQueueConfiguration;
 import org.hornetq.core.config.DivertConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ScaleDownConfiguration;
+import org.hornetq.core.config.ha.ColocatedPolicyConfiguration;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.config.impl.ConfigurationImpl;
 import org.hornetq.core.config.impl.FileConfiguration;
 import org.hornetq.core.config.impl.Validators;
@@ -47,11 +54,10 @@ import org.hornetq.core.journal.impl.JournalConstants;
 import org.hornetq.core.security.Role;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.JournalType;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
-import org.hornetq.core.server.cluster.ha.HAPolicyTemplate;
 import org.hornetq.core.server.group.impl.GroupingHandlerConfiguration;
 import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
 import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.core.settings.impl.SlowConsumerPolicy;
 import org.hornetq.utils.DefaultSensitiveStringCodec;
 import org.hornetq.utils.PasswordMaskingUtil;
 import org.hornetq.utils.SensitiveDataCodec;
@@ -136,6 +142,12 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
 
    private static final String SEND_TO_DLA_ON_NO_ROUTE = "send-to-dla-on-no-route";
 
+   private static final String SLOW_CONSUMER_THRESHOLD_NODE_NAME = "slow-consumer-threshold";
+
+   private static final String SLOW_CONSUMER_CHECK_PERIOD_NODE_NAME = "slow-consumer-check-period";
+
+   private static final String SLOW_CONSUMER_POLICY_NODE_NAME = "slow-consumer-policy";
+
    // Attributes ----------------------------------------------------
 
    private boolean validateAIO = false;
@@ -195,6 +207,57 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          HornetQServerLogger.LOGGER.deprecatedConfigurationOption("clustered");
       }
 
+      // these are combined because they are both required for setting the correct HAPolicyConfiguration
+      if (parameterExists(e, "backup") || parameterExists(e, "shared-store"))
+      {
+         boolean backup = getBoolean(e, "backup", false);
+         boolean sharedStore = getBoolean(e, "shared-store", true);
+
+         if (containsHAPolicy)
+         {
+            if (parameterExists(e, "backup"))
+            {
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicy("backup");
+            }
+
+            if (parameterExists(e, "shared-store"))
+            {
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicy("shared-store");
+            }
+         }
+         else
+         {
+            if (parameterExists(e, "backup"))
+            {
+               HornetQServerLogger.LOGGER.deprecatedConfigurationOption("backup");
+            }
+
+            if (parameterExists(e, "shared-store"))
+            {
+               HornetQServerLogger.LOGGER.deprecatedConfigurationOption("shared-store");
+            }
+
+            if (backup && sharedStore)
+            {
+               config.setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
+            }
+            else if (backup && !sharedStore)
+            {
+               config.setHAPolicyConfiguration(new ReplicaPolicyConfiguration());
+            }
+            else if (!backup && sharedStore)
+            {
+               config.setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration());
+            }
+            else if (!backup && !sharedStore)
+            {
+               config.setHAPolicyConfiguration(new ReplicatedPolicyConfiguration());
+            }
+         }
+      }
+
+      HAPolicyConfiguration haPolicyConfig = config.getHAPolicyConfiguration();
+
       if (parameterExists(e, "check-for-live-server"))
       {
          if (containsHAPolicy)
@@ -205,7 +268,11 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             HornetQServerLogger.LOGGER.deprecatedConfigurationOption("check-for-live-server");
 
-            config.getHAPolicy().setCheckForLiveServer(getBoolean(e, "check-for-live-server", config.getHAPolicy().isCheckForLiveServer()));
+            if (haPolicyConfig instanceof ReplicatedPolicyConfiguration)
+            {
+               ReplicatedPolicyConfiguration hapc = (ReplicatedPolicyConfiguration) haPolicyConfig;
+               hapc.setCheckForLiveServer(getBoolean(e, "check-for-live-server", hapc.isCheckForLiveServer()));
+            }
          }
       }
 
@@ -219,7 +286,20 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             HornetQServerLogger.LOGGER.deprecatedConfigurationOption("allow-failback");
 
-            config.getHAPolicy().setAllowAutoFailBack(getBoolean(e, "allow-failback", config.getHAPolicy().isAllowAutoFailBack()));
+            if (haPolicyConfig instanceof ReplicaPolicyConfiguration)
+            {
+               ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfig;
+               hapc.setAllowFailBack(getBoolean(e, "allow-failback", hapc.isAllowFailBack()));
+            }
+            else if (haPolicyConfig instanceof SharedStoreSlavePolicyConfiguration)
+            {
+               SharedStoreSlavePolicyConfiguration hapc = (SharedStoreSlavePolicyConfiguration) haPolicyConfig;
+               hapc.setAllowFailBack(getBoolean(e, "allow-failback", hapc.isAllowFailBack()));
+            }
+            else
+            {
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicyChosen("check-for-live-server");
+            }
          }
       }
 
@@ -233,7 +313,20 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             HornetQServerLogger.LOGGER.deprecatedConfigurationOption("backup-group-name");
 
-            config.getHAPolicy().setBackupGroupName(getString(e, "backup-group-name", config.getHAPolicy().getBackupGroupName(), Validators.NO_CHECK));
+            if (haPolicyConfig instanceof ReplicaPolicyConfiguration)
+            {
+               ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfig;
+               hapc.setGroupName(getString(e, "backup-group-name", hapc.getGroupName(), Validators.NO_CHECK));
+            }
+            else if (haPolicyConfig instanceof ReplicatedPolicyConfiguration)
+            {
+               ReplicatedPolicyConfiguration hapc = (ReplicatedPolicyConfiguration) haPolicyConfig;
+               hapc.setGroupName(getString(e, "backup-group-name", hapc.getGroupName(), Validators.NO_CHECK));
+            }
+            else
+            {
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicyChosen("backup-group-name");
+            }
          }
       }
 
@@ -247,7 +340,25 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             HornetQServerLogger.LOGGER.deprecatedConfigurationOption("failback-delay");
 
-            config.getHAPolicy().setFailbackDelay(getLong(e, "failback-delay", config.getHAPolicy().getFailbackDelay(), Validators.GT_ZERO));
+            if (haPolicyConfig instanceof ReplicaPolicyConfiguration)
+            {
+               ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfig;
+               hapc.setFailbackDelay(getLong(e, "failback-delay", hapc.getFailbackDelay(), Validators.GT_ZERO));
+            }
+            else if (haPolicyConfig instanceof SharedStoreMasterPolicyConfiguration)
+            {
+               SharedStoreMasterPolicyConfiguration hapc = (SharedStoreMasterPolicyConfiguration) haPolicyConfig;
+               hapc.setFailbackDelay(getLong(e, "failback-delay", hapc.getFailbackDelay(), Validators.GT_ZERO));
+            }
+            else if (haPolicyConfig instanceof SharedStoreSlavePolicyConfiguration)
+            {
+               SharedStoreSlavePolicyConfiguration hapc = (SharedStoreSlavePolicyConfiguration) haPolicyConfig;
+               hapc.setFailbackDelay(getLong(e, "failback-delay", hapc.getFailbackDelay(), Validators.GT_ZERO));
+            }
+            else
+            {
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicyChosen("failback-delay");
+            }
          }
       }
 
@@ -261,7 +372,20 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             HornetQServerLogger.LOGGER.deprecatedConfigurationOption("failover-on-shutdown");
 
-            config.getHAPolicy().setFailoverOnServerShutdown(getBoolean(e, "failover-on-shutdown", config.getHAPolicy().isFailoverOnServerShutdown()));
+            if (haPolicyConfig instanceof SharedStoreMasterPolicyConfiguration)
+            {
+               SharedStoreMasterPolicyConfiguration hapc = (SharedStoreMasterPolicyConfiguration) haPolicyConfig;
+               hapc.setFailoverOnServerShutdown(getBoolean(e, "failover-on-shutdown", hapc.isFailoverOnServerShutdown()));
+            }
+            else if (haPolicyConfig instanceof SharedStoreSlavePolicyConfiguration)
+            {
+               SharedStoreSlavePolicyConfiguration hapc = (SharedStoreSlavePolicyConfiguration) haPolicyConfig;
+               hapc.setFailoverOnServerShutdown(getBoolean(e, "failover-on-shutdown", hapc.isFailoverOnServerShutdown()));
+            }
+            else
+            {
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicyChosen("failover-on-shutdown");
+            }
          }
       }
 
@@ -275,21 +399,20 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             HornetQServerLogger.LOGGER.deprecatedConfigurationOption("replication-clustername");
 
-            config.getHAPolicy().setReplicationClustername(getString(e, "replication-clustername", null, Validators.NO_CHECK));
-         }
-      }
-
-      if (parameterExists(e, "scale-down-clustername"))
-      {
-         if (containsHAPolicy)
-         {
-            HornetQServerLogger.LOGGER.incompatibleWithHAPolicy("scale-down-clustername");
-         }
-         else
-         {
-            HornetQServerLogger.LOGGER.deprecatedConfigurationOption("scale-down-clustername");
-
-            config.getHAPolicy().setScaleDownClustername(getString(e, "scale-down-clustername", null, Validators.NO_CHECK));
+            if (haPolicyConfig instanceof ReplicaPolicyConfiguration)
+            {
+               ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfig;
+               hapc.setClusterName(getString(e, "replication-clustername", null, Validators.NO_CHECK));
+            }
+            else if (haPolicyConfig instanceof ReplicatedPolicyConfiguration)
+            {
+               ReplicatedPolicyConfiguration hapc = (ReplicatedPolicyConfiguration) haPolicyConfig;
+               hapc.setClusterName(getString(e, "replication-clustername", null, Validators.NO_CHECK));
+            }
+            else
+            {
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicyChosen("replication-clustername");
+            }
          }
       }
 
@@ -303,60 +426,27 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             HornetQServerLogger.LOGGER.deprecatedConfigurationOption("max-saved-replicated-journals-size");
 
-            config.getHAPolicy().setMaxSavedReplicatedJournalSize(getInteger(e, "max-saved-replicated-journals-size",
-                                                                             config.getHAPolicy().getMaxSavedReplicatedJournalsSize(), Validators.MINUS_ONE_OR_GE_ZERO));
-         }
-      }
-
-      // these are combined because they are both required for setting the HAPolicy
-      if (parameterExists(e, "backup") || parameterExists(e, "shared-store"))
-      {
-         boolean backup = getBoolean(e, "backup", config.getHAPolicy().isBackup());
-         boolean sharedStore = getBoolean(e, "shared-store", config.getHAPolicy().isSharedStore());
-
-         if (containsHAPolicy)
-         {
-            if (parameterExists(e, "backup"))
-            {
-               HornetQServerLogger.LOGGER.incompatibleWithHAPolicy("backup");
-            }
-
-            if (parameterExists(e, "shared-store"))
-            {
-               HornetQServerLogger.LOGGER.incompatibleWithHAPolicy("shared-store");
-            }
-         }
-         else
-         {
-            if (parameterExists(e, "backup"))
-            {
-               HornetQServerLogger.LOGGER.deprecatedConfigurationOption("backup");
-            }
-
-            if (parameterExists(e, "shared-store"))
+            if (haPolicyConfig instanceof ReplicaPolicyConfiguration)
             {
-               HornetQServerLogger.LOGGER.deprecatedConfigurationOption("shared-store");
-            }
+               ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfig;
+               hapc.setMaxSavedReplicatedJournalsSize(getInteger(e, "max-saved-replicated-journals-size",
+                     hapc.getMaxSavedReplicatedJournalsSize(), Validators.MINUS_ONE_OR_GE_ZERO));
 
-            if (backup && sharedStore)
-            {
-               config.setHAPolicy(HAPolicyTemplate.BACKUP_SHARED_STORE.getHaPolicy());
-            }
-            else if (backup && !sharedStore)
-            {
-               config.setHAPolicy(HAPolicyTemplate.BACKUP_REPLICATED.getHaPolicy());
-            }
-            else if (!backup && sharedStore)
-            {
-               config.setHAPolicy(HAPolicyTemplate.SHARED_STORE.getHaPolicy());
             }
-            else if (!backup && !sharedStore)
+            else
             {
-               config.setHAPolicy(HAPolicyTemplate.REPLICATED.getHaPolicy());
+               HornetQServerLogger.LOGGER.incompatibleWithHAPolicyChosen("max-saved-replicated-journals-size");
             }
          }
       }
 
+      //if we aren already set then set to default
+      if (config.getHAPolicyConfiguration() == null)
+      {
+         config.setHAPolicyConfiguration(new LiveOnlyPolicyConfiguration());
+      }
+
+
       config.setResolveProtocols(getBoolean(e, "resolve-protocols", config.isResolveProtocols()));
 
       // Defaults to true when using FileConfiguration
@@ -1023,6 +1113,28 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          {
             addressSettings.setSendToDLAOnNoRoute(XMLUtil.parseBoolean(child));
          }
+         else if (SLOW_CONSUMER_THRESHOLD_NODE_NAME.equalsIgnoreCase(name))
+         {
+            long slowConsumerThreshold = XMLUtil.parseLong(child);
+            Validators.MINUS_ONE_OR_GT_ZERO.validate(SLOW_CONSUMER_THRESHOLD_NODE_NAME, slowConsumerThreshold);
+
+            addressSettings.setSlowConsumerThreshold(slowConsumerThreshold);
+         }
+         else if (SLOW_CONSUMER_CHECK_PERIOD_NODE_NAME.equalsIgnoreCase(name))
+         {
+            long slowConsumerCheckPeriod = XMLUtil.parseLong(child);
+            Validators.GT_ZERO.validate(SLOW_CONSUMER_CHECK_PERIOD_NODE_NAME, slowConsumerCheckPeriod);
+
+            addressSettings.setSlowConsumerCheckPeriod(slowConsumerCheckPeriod);
+         }
+         else if (SLOW_CONSUMER_POLICY_NODE_NAME.equalsIgnoreCase(name))
+         {
+            String value = getTrimmedTextContent(child);
+            Validators.SLOW_CONSUMER_POLICY_TYPE.validate(SLOW_CONSUMER_POLICY_NODE_NAME,
+                                                                 value);
+            SlowConsumerPolicy policy = Enum.valueOf(SlowConsumerPolicy.class, value);
+            addressSettings.setSlowConsumerPolicy(policy);
+         }
       }
       return setting;
    }
@@ -1054,7 +1166,11 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          }
       }
 
-      return new CoreQueueConfiguration(address, name, filterString, durable);
+      return new CoreQueueConfiguration()
+         .setAddress(address)
+         .setName(name)
+         .setFilterString(filterString)
+         .setDurable(durable);
    }
 
    private TransportConfiguration parseTransportConfiguration(final Element e, final Configuration mainConfig)
@@ -1097,74 +1213,180 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
       return new TransportConfiguration(clazz, params, name);
    }
 
+   private static final ArrayList<String> POLICY_LIST = new ArrayList<>();
+   static
+   {
+      POLICY_LIST.add("colocated");
+      POLICY_LIST.add("live-only");
+      POLICY_LIST.add("replicated");
+      POLICY_LIST.add("replica");
+      POLICY_LIST.add("shared-store-master");
+      POLICY_LIST.add("shared-store-slave");
+   }
+   private static final ArrayList<String> HA_LIST = new ArrayList<>();
+   static
+   {
+      HA_LIST.add("live-only");
+      HA_LIST.add("shared-store");
+      HA_LIST.add("replication");
+   }
    private void parseHAPolicyConfiguration(final Element e, final Configuration mainConfig)
    {
-      String policyTemplate = e.getAttribute("template");
-      HAPolicy policy;
-      if (policyTemplate.length() > 0)
-      {
-         policy = HAPolicyTemplate.valueOf(policyTemplate).getHaPolicy();
-      }
-      else
+      for (String haType : HA_LIST)
       {
-         policy = HAPolicyTemplate.NONE.getHaPolicy();
+         NodeList haNodeList = e.getElementsByTagName(haType);
+         if (haNodeList.getLength() > 0)
+         {
+            Element haNode = (Element) haNodeList.item(0);
+            if (haNode.getTagName().equals("replication"))
+            {
+               NodeList masterNodeList = e.getElementsByTagName("master");
+               if (masterNodeList.getLength() > 0)
+               {
+                  Element masterNode = (Element) masterNodeList.item(0);
+                  mainConfig.setHAPolicyConfiguration(createReplicatedHaPolicy(masterNode));
+               }
+               NodeList slaveNodeList = e.getElementsByTagName("slave");
+               if (slaveNodeList.getLength() > 0)
+               {
+                  Element slaveNode = (Element) slaveNodeList.item(0);
+                  mainConfig.setHAPolicyConfiguration(createReplicaHaPolicy(slaveNode));
+               }
+               NodeList colocatedNodeList = e.getElementsByTagName("colocated");
+               if (colocatedNodeList.getLength() > 0)
+               {
+                  Element colocatedNode = (Element) colocatedNodeList.item(0);
+                  mainConfig.setHAPolicyConfiguration(createColocatedHaPolicy(colocatedNode, true));
+               }
+            }
+            else if (haNode.getTagName().equals("shared-store"))
+            {
+               NodeList masterNodeList = e.getElementsByTagName("master");
+               if (masterNodeList.getLength() > 0)
+               {
+                  Element masterNode = (Element) masterNodeList.item(0);
+                  mainConfig.setHAPolicyConfiguration(createSharedStoreMasterHaPolicy(masterNode));
+               }
+               NodeList slaveNodeList = e.getElementsByTagName("slave");
+               if (slaveNodeList.getLength() > 0)
+               {
+                  Element slaveNode = (Element) slaveNodeList.item(0);
+                  mainConfig.setHAPolicyConfiguration(createSharedStoreSlaveHaPolicy(slaveNode));
+               }
+               NodeList colocatedNodeList = e.getElementsByTagName("colocated");
+               if (colocatedNodeList.getLength() > 0)
+               {
+                  Element colocatedNode = (Element) colocatedNodeList.item(0);
+                  mainConfig.setHAPolicyConfiguration(createColocatedHaPolicy(colocatedNode, false));
+               }
+            }
+            else if (haNode.getTagName().equals("live-only"))
+            {
+               NodeList noneNodeList = e.getElementsByTagName("live-only");
+               Element noneNode = (Element) noneNodeList.item(0);
+               mainConfig.setHAPolicyConfiguration(createLiveOnlyHaPolicy(noneNode));
+            }
+         }
       }
-      mainConfig.setHAPolicy(policy);
+   }
 
-      String policyType = getString(e, "policy-type", policy.getPolicyType().toString(), Validators.NOT_NULL_OR_EMPTY);
+   private LiveOnlyPolicyConfiguration createLiveOnlyHaPolicy(Element policyNode)
+   {
+      LiveOnlyPolicyConfiguration configuration = new LiveOnlyPolicyConfiguration();
 
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.valueOf(policyType));
+      configuration.setScaleDownConfiguration(parseScaleDownConfig(policyNode));
 
-      boolean requestBackup = getBoolean(e, "request-backup", policy.isRequestBackup());
+      return configuration;
+   }
 
-      policy.setRequestBackup(requestBackup);
+   private ReplicatedPolicyConfiguration createReplicatedHaPolicy(Element policyNode)
+   {
+      ReplicatedPolicyConfiguration configuration = new ReplicatedPolicyConfiguration();
 
-      int backupRequestRetries = getInteger(e, "backup-request-retries", policy.getBackupRequestRetries(), Validators.MINUS_ONE_OR_GE_ZERO);
+      configuration.setCheckForLiveServer(getBoolean(policyNode, "check-for-live-server", configuration.isCheckForLiveServer()));
 
-      policy.setBackupRequestRetries(backupRequestRetries);
+      configuration.setGroupName(getString(policyNode, "group-name", configuration.getGroupName(), Validators.NO_CHECK));
 
-      long backupRequestRetryInterval = getLong(e, "backup-request-retry-interval", policy.getBackupRequestRetryInterval(), Validators.GT_ZERO);
+      configuration.setClusterName(getString(policyNode, "cluster-name", configuration.getClusterName(), Validators.NO_CHECK));
 
-      policy.setBackupRequestRetryInterval(backupRequestRetryInterval);
+      return configuration;
+   }
 
-      int maxBackups = getInteger(e, "max-backups", policy.getMaxBackups(), Validators.GE_ZERO);
+   private ReplicaPolicyConfiguration createReplicaHaPolicy(Element policyNode)
+   {
+      ReplicaPolicyConfiguration configuration = new ReplicaPolicyConfiguration();
 
-      policy.setMaxBackups(maxBackups);
+      configuration.setRestartBackup(getBoolean(policyNode, "restart-backup", configuration.isRestartBackup()));
 
-      int backupPortOffset = getInteger(e, "backup-port-offset", policy.getBackupPortOffset(), Validators.GT_ZERO);
+      configuration.setGroupName(getString(policyNode, "group-name", configuration.getGroupName(), Validators.NO_CHECK));
 
-      policy.setBackupPortOffset(backupPortOffset);
+      configuration.setAllowFailBack(getBoolean(policyNode, "allow-failback", configuration.isAllowFailBack()));
 
-      String backupStrategy = getString(e, "backup-strategy", policy.getBackupStrategy().toString(), Validators.NOT_NULL_OR_EMPTY);
+      configuration.setFailbackDelay(getLong(policyNode, "failback-delay", configuration.getFailbackDelay(), Validators.GT_ZERO));
 
-      policy.setBackupStrategy(BackupStrategy.valueOf(backupStrategy));
+      configuration.setClusterName(getString(policyNode, "cluster-name", configuration.getClusterName(), Validators.NO_CHECK));
 
-      String scaleDownDiscoveryGroup = getString(e, "scale-down-discovery-group", policy.getScaleDownDiscoveryGroup(), Validators.NO_CHECK);
+      configuration.setMaxSavedReplicatedJournalsSize(getInteger(policyNode, "max-saved-replicated-journals-size",
+            configuration.getMaxSavedReplicatedJournalsSize(), Validators.MINUS_ONE_OR_GE_ZERO));
 
-      policy.setScaleDownDiscoveryGroup(scaleDownDiscoveryGroup);
+      configuration.setScaleDownConfiguration(parseScaleDownConfig(policyNode));
 
-      String scaleDownDiscoveryGroupName = getString(e, "scale-down-group-name", policy.getScaleDownGroupName(), Validators.NO_CHECK);
+      return configuration;
+   }
 
-      policy.setScaleDownGroupName(scaleDownDiscoveryGroupName);
+   private SharedStoreMasterPolicyConfiguration createSharedStoreMasterHaPolicy(Element policyNode)
+   {
+      SharedStoreMasterPolicyConfiguration configuration = new SharedStoreMasterPolicyConfiguration();
 
-      NodeList scaleDownConnectorNode = e.getElementsByTagName("scale-down-connectors");
+      configuration.setFailoverOnServerShutdown(getBoolean(policyNode, "failover-on-shutdown", configuration.isFailoverOnServerShutdown()));
 
-      if (scaleDownConnectorNode != null && scaleDownConnectorNode.getLength() > 0)
-      {
-         NodeList scaleDownConnectors = scaleDownConnectorNode.item(0).getChildNodes();
-         for (int i = 0; i < scaleDownConnectors.getLength(); i++)
-         {
-            Node child = scaleDownConnectors.item(i);
-            if (child.getNodeName().equals("connector-ref"))
-            {
-               String connectorName = getTrimmedTextContent(child);
+      configuration.setFailbackDelay(getLong(policyNode, "failback-delay", configuration.getFailbackDelay(), Validators.GT_ZERO));
 
-               policy.getScaleDownConnectors().add(connectorName);
-            }
-         }
-      }
+      return configuration;
+   }
+
+   private SharedStoreSlavePolicyConfiguration createSharedStoreSlaveHaPolicy(Element policyNode)
+   {
+      SharedStoreSlavePolicyConfiguration configuration = new SharedStoreSlavePolicyConfiguration();
+
+      configuration.setAllowFailBack(getBoolean(policyNode, "allow-failback", configuration.isAllowFailBack()));
 
-      NodeList remoteConnectorNode = e.getElementsByTagName("remote-connectors");
+      configuration.setFailoverOnServerShutdown(getBoolean(policyNode, "failover-on-shutdown", configuration.isFailoverOnServerShutdown()));
+
+      configuration.setFailbackDelay(getLong(policyNode, "failback-delay", configuration.getFailbackDelay(), Validators.GT_ZERO));
+
+      configuration.setRestartBackup(getBoolean(policyNode, "restart-backup", configuration.isRestartBackup()));
+
+      configuration.setScaleDownConfiguration(parseScaleDownConfig(policyNode));
+
+      return configuration;
+   }
+
+   private ColocatedPolicyConfiguration createColocatedHaPolicy(Element policyNode, boolean replicated)
+   {
+      ColocatedPolicyConfiguration configuration = new ColocatedPolicyConfiguration();
+
+      boolean requestBackup = getBoolean(policyNode, "request-backup", configuration.isRequestBackup());
+
+      configuration.setRequestBackup(requestBackup);
+
+      int backupRequestRetries = getInteger(policyNode, "backup-request-retries", configuration.getBackupRequestRetries(), Validators.MINUS_ONE_OR_GE_ZERO);
+
+      configuration.setBackupRequestRetries(backupRequestRetries);
+
+      long backupRequestRetryInterval = getLong(policyNode, "backup-request-retry-interval", configuration.getBackupRequestRetryInterval(), Validators.GT_ZERO);
+
+      configuration.setBackupRequestRetryInterval(backupRequestRetryInterval);
+
+      int maxBackups = getInteger(policyNode, "max-backups", configuration.getMaxBackups(), Validators.GE_ZERO);
+
+      configuration.setMaxBackups(maxBackups);
+
+      int backupPortOffset = getInteger(policyNode, "backup-port-offset", configuration.getBackupPortOffset(), Validators.GT_ZERO);
+
+      configuration.setBackupPortOffset(backupPortOffset);
+
+      NodeList remoteConnectorNode = policyNode.getElementsByTagName("excludes");
 
       if (remoteConnectorNode != null && remoteConnectorNode.getLength() > 0)
       {
@@ -1175,31 +1397,65 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
             if (child.getNodeName().equals("connector-ref"))
             {
                String connectorName = getTrimmedTextContent(child);
-               policy.getRemoteConnectors().add(connectorName);
+               configuration.getExcludedConnectors().add(connectorName);
             }
          }
       }
 
-      policy.setScaleDown(getBoolean(e, "scale-down", policy.isScaleDown()));
+      NodeList masterNodeList = policyNode.getElementsByTagName("master");
+      if (masterNodeList.getLength() > 0)
+      {
+         Element masterNode = (Element) masterNodeList.item(0);
+         configuration.setLiveConfig(replicated ? createReplicatedHaPolicy(masterNode) : createSharedStoreMasterHaPolicy(masterNode));
+      }
+      NodeList slaveNodeList = policyNode.getElementsByTagName("slave");
+      if (slaveNodeList.getLength() > 0)
+      {
+         Element slaveNode = (Element) slaveNodeList.item(0);
+         configuration.setBackupConfig(replicated ? createReplicaHaPolicy(slaveNode) : createSharedStoreSlaveHaPolicy(slaveNode));
+      }
 
-      policy.setScaleDownGroupName(getString(e, "scale-down-group-name", policy.getScaleDownGroupName(), Validators.NO_CHECK));
+      return configuration;
+   }
+   private ScaleDownConfiguration parseScaleDownConfig(Element policyNode)
+   {
+      NodeList scaleDownNode = policyNode.getElementsByTagName("scale-down");
 
-      policy.setCheckForLiveServer(getBoolean(e, "check-for-live-server", policy.isCheckForLiveServer()));
+      if (scaleDownNode.getLength() > 0)
+      {
+         ScaleDownConfiguration scaleDownConfiguration = new ScaleDownConfiguration();
 
-      policy.setAllowAutoFailBack(getBoolean(e, "allow-failback", policy.isCheckForLiveServer()));
+         Element scaleDownElement = (Element) scaleDownNode.item(0);
 
-      policy.setFailoverOnServerShutdown(getBoolean(e, "failover-on-shutdown", policy.isFailoverOnServerShutdown()));
+         scaleDownConfiguration.setEnabled(getBoolean(scaleDownElement, "enabled", scaleDownConfiguration.isEnabled()));
 
-      policy.setBackupGroupName(getString(e, "backup-group-name", policy.getBackupGroupName(), Validators.NO_CHECK));
+         String scaleDownDiscoveryGroup = getString(scaleDownElement, "discovery-group", scaleDownConfiguration.getDiscoveryGroup(), Validators.NO_CHECK);
 
-      policy.setFailbackDelay(getLong(e, "failback-delay", policy.getFailbackDelay(), Validators.GT_ZERO));
+         scaleDownConfiguration.setDiscoveryGroup(scaleDownDiscoveryGroup);
 
-      policy.setReplicationClustername(getString(e, "replication-clustername", null, Validators.NO_CHECK));
+         String scaleDownDiscoveryGroupName = getString(scaleDownElement, "group-name", scaleDownConfiguration.getGroupName(), Validators.NO_CHECK);
 
-      policy.setScaleDownClustername(getString(e, "scale-down-clustername", null, Validators.NO_CHECK));
+         scaleDownConfiguration.setGroupName(scaleDownDiscoveryGroupName);
 
-      policy.setMaxSavedReplicatedJournalSize(getInteger(e, "max-saved-replicated-journals-size",
-                                                         policy.getMaxSavedReplicatedJournalsSize(), Validators.MINUS_ONE_OR_GE_ZERO));
+         NodeList scaleDownConnectorNode = scaleDownElement.getElementsByTagName("connectors");
+
+         if (scaleDownConnectorNode != null && scaleDownConnectorNode.getLength() > 0)
+         {
+            NodeList scaleDownConnectors = scaleDownConnectorNode.item(0).getChildNodes();
+            for (int i = 0; i < scaleDownConnectors.getLength(); i++)
+            {
+               Node child = scaleDownConnectors.item(i);
+               if (child.getNodeName().equals("connector-ref"))
+               {
+                  String connectorName = getTrimmedTextContent(child);
+
+                  scaleDownConfiguration.getConnectors().add(connectorName);
+               }
+            }
+         }
+         return scaleDownConfiguration;
+      }
+      return null;
    }
 
    private void parseBroadcastGroupConfiguration(final Element e, final Configuration mainConfig)
@@ -1251,10 +1507,18 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
       }
       else
       {
-         endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration(groupAddress, groupPort, localAddress, localBindPort);
+         endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(groupAddress)
+            .setGroupPort(groupPort)
+            .setLocalBindAddress(localAddress)
+            .setLocalBindPort(localBindPort);
       }
 
-      BroadcastGroupConfiguration config = new BroadcastGroupConfiguration(name, broadcastPeriod, connectorNames, endpointFactoryConfiguration);
+      BroadcastGroupConfiguration config = new BroadcastGroupConfiguration()
+         .setName(name)
+         .setBroadcastPeriod(broadcastPeriod)
+         .setConnectorInfos(connectorNames)
+         .setEndpointFactoryConfiguration(endpointFactoryConfiguration);
 
       mainConfig.getBroadcastGroupConfigurations().add(config);
    }
@@ -1291,10 +1555,18 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
       }
       else
       {
-         endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration(groupAddress, groupPort, localBindAddress, localBindPort);
+         endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(groupAddress)
+            .setGroupPort(groupPort)
+            .setLocalBindAddress(localBindAddress)
+            .setLocalBindPort(localBindPort);
       }
 
-      DiscoveryGroupConfiguration config = new DiscoveryGroupConfiguration(name, refreshTimeout, discoveryInitialWaitTimeout, endpointFactoryConfiguration);
+      DiscoveryGroupConfiguration config = new DiscoveryGroupConfiguration()
+         .setName(name)
+         .setRefreshTimeout(refreshTimeout)
+         .setDiscoveryInitialWaitTimeout(discoveryInitialWaitTimeout)
+         .setBroadcastEndpointFactoryConfiguration(endpointFactoryConfiguration);
 
       if (mainConfig.getDiscoveryGroupConfigurations().containsKey(name))
       {
@@ -1357,7 +1629,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
 
 
       int confirmationWindowSize =
-         getInteger(e, "confirmation-window-size", FileConfiguration.DEFAULT_CONFIRMATION_WINDOW_SIZE,
+         getInteger(e, "confirmation-window-size", HornetQDefaultConfiguration.getDefaultClusterConfirmationWindowSize(),
                     Validators.GT_ZERO);
 
       long clusterNotificationInterval = getLong(e, "notification-interval", HornetQDefaultConfiguration.getDefaultClusterNotificationInterval(), Validators.GT_ZERO);
@@ -1393,44 +1665,35 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          }
       }
 
-      ClusterConnectionConfiguration config;
+      ClusterConnectionConfiguration config = new ClusterConnectionConfiguration()
+         .setName(name)
+         .setAddress(address)
+         .setConnectorName(connectorName)
+         .setMinLargeMessageSize(minLargeMessageSize)
+         .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+         .setConnectionTTL(connectionTTL)
+         .setRetryInterval(retryInterval)
+         .setRetryIntervalMultiplier(retryIntervalMultiplier)
+         .setMaxRetryInterval(maxRetryInterval)
+         .setInitialConnectAttempts(initialConnectAttempts)
+         .setReconnectAttempts(reconnectAttempts)
+         .setCallTimeout(callTimeout)
+         .setCallFailoverTimeout(callFailoverTimeout)
+         .setDuplicateDetection(duplicateDetection)
+         .setForwardWhenNoConsumers(forwardWhenNoConsumers)
+         .setMaxHops(maxHops)
+         .setConfirmationWindowSize(confirmationWindowSize)
+         .setAllowDirectConnectionsOnly(allowDirectConnectionsOnly)
+         .setClusterNotificationInterval(clusterNotificationInterval)
+         .setClusterNotificationAttempts(clusterNotificationAttempts);
 
       if (discoveryGroupName == null)
       {
-         config =
-            new ClusterConnectionConfiguration(name, address, connectorName,
-                                               minLargeMessageSize, clientFailureCheckPeriod, connectionTTL,
-                                               retryInterval, retryIntervalMultiplier, maxRetryInterval,
-                                               initialConnectAttempts, reconnectAttempts, callTimeout, callFailoverTimeout,
-                                               duplicateDetection, forwardWhenNoConsumers, maxHops,
-                                               confirmationWindowSize,
-                                               staticConnectorNames,
-                                               allowDirectConnectionsOnly,
-                                               clusterNotificationInterval,
-                                               clusterNotificationAttempts,
-                                               scaleDownConnector);
+         config.setStaticConnectors(staticConnectorNames);
       }
       else
       {
-         config =
-            new ClusterConnectionConfiguration(name, address, connectorName,
-                                               minLargeMessageSize, clientFailureCheckPeriod,
-                                               connectionTTL,
-                                               retryInterval,
-                                               retryIntervalMultiplier,
-                                               maxRetryInterval,
-                                               initialConnectAttempts,
-                                               reconnectAttempts,
-                                               callTimeout,
-                                               callFailoverTimeout,
-                                               duplicateDetection,
-                                               forwardWhenNoConsumers,
-                                               maxHops,
-                                               confirmationWindowSize,
-                                               discoveryGroupName,
-                                               clusterNotificationInterval,
-                                               clusterNotificationAttempts,
-                                               scaleDownConnector);
+         config.setDiscoveryGroupName(discoveryGroupName);
       }
 
       mainConfig.getClusterConfigurations().add(config);
@@ -1441,17 +1704,19 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
       String name = node.getAttribute("name");
       String type = getString(node, "type", null, Validators.NOT_NULL_OR_EMPTY);
       String address = getString(node, "address", null, Validators.NOT_NULL_OR_EMPTY);
-      Integer timeout = getInteger(node, "timeout", GroupingHandlerConfiguration.DEFAULT_TIMEOUT, Validators.GT_ZERO);
-      Long groupTimeout = getLong(node, "group-timeout", GroupingHandlerConfiguration.DEFAULT_GROUP_TIMEOUT, Validators.MINUS_ONE_OR_GT_ZERO);
-      Long reaperPeriod = getLong(node, "reaper-period", GroupingHandlerConfiguration.DEFAULT_REAPER_PERIOD, Validators.GT_ZERO);
-      mainConfiguration.setGroupingHandlerConfiguration(new GroupingHandlerConfiguration(new SimpleString(name),
-                                                                                         type.equals(GroupingHandlerConfiguration.TYPE.LOCAL.getType())
-                                                                                            ? GroupingHandlerConfiguration.TYPE.LOCAL
-                                                                                            : GroupingHandlerConfiguration.TYPE.REMOTE,
-                                                                                         new SimpleString(address),
-                                                                                         timeout,
-                                                                                         groupTimeout,
-                                                                                         reaperPeriod));
+      Integer timeout = getInteger(node, "timeout", HornetQDefaultConfiguration.getDefaultGroupingHandlerTimeout(), Validators.GT_ZERO);
+      Long groupTimeout = getLong(node, "group-timeout", HornetQDefaultConfiguration.getDefaultGroupingHandlerGroupTimeout(), Validators.MINUS_ONE_OR_GT_ZERO);
+      Long reaperPeriod = getLong(node, "reaper-period", HornetQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod(), Validators.GT_ZERO);
+      mainConfiguration.setGroupingHandlerConfiguration(new GroupingHandlerConfiguration()
+                                                           .setName(new SimpleString(name))
+                                                           .setType(
+                                                              type.equals(GroupingHandlerConfiguration.TYPE.LOCAL.getType())
+                                                                 ? GroupingHandlerConfiguration.TYPE.LOCAL
+                                                                 : GroupingHandlerConfiguration.TYPE.REMOTE)
+                                                           .setAddress(new SimpleString(address))
+                                                           .setTimeout(timeout)
+                                                           .setGroupTimeout(groupTimeout)
+                                                           .setReaperPeriod(reaperPeriod));
    }
 
    private void parseBridgeConfiguration(final Element brNode, final Configuration mainConfig) throws Exception
@@ -1466,7 +1731,7 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
 
       // Default bridge conf
       int confirmationWindowSize =
-         getInteger(brNode, "confirmation-window-size", FileConfiguration.DEFAULT_CONFIRMATION_WINDOW_SIZE,
+         getInteger(brNode, "confirmation-window-size", HornetQDefaultConfiguration.getDefaultBridgeConfirmationWindowSize(),
                     Validators.GT_ZERO);
 
       long retryInterval = getLong(brNode, "retry-interval", HornetQClient.DEFAULT_RETRY_INTERVAL, Validators.GT_ZERO);
@@ -1561,53 +1826,34 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          }
       }
 
-      BridgeConfiguration config;
+      BridgeConfiguration config = new BridgeConfiguration()
+         .setName(name)
+         .setQueueName(queueName)
+         .setForwardingAddress(forwardingAddress)
+         .setFilterString(filterString)
+         .setTransformerClassName(transformerClassName)
+         .setMinLargeMessageSize(minLargeMessageSize)
+         .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+         .setConnectionTTL(connectionTTL)
+         .setRetryInterval(retryInterval)
+         .setMaxRetryInterval(maxRetryInterval)
+         .setRetryIntervalMultiplier(retryIntervalMultiplier)
+         .setInitialConnectAttempts(initialConnectAttempts)
+         .setReconnectAttempts(reconnectAttempts)
+         .setReconnectAttemptsOnSameNode(reconnectAttemptsSameNode)
+         .setUseDuplicateDetection(useDuplicateDetection)
+         .setConfirmationWindowSize(confirmationWindowSize)
+         .setHA(ha)
+         .setUser(user)
+         .setPassword(password);
 
       if (!staticConnectorNames.isEmpty())
       {
-         config = new BridgeConfiguration(name,
-                                          queueName,
-                                          forwardingAddress,
-                                          filterString,
-                                          transformerClassName,
-                                          minLargeMessageSize,
-                                          clientFailureCheckPeriod,
-                                          connectionTTL,
-                                          retryInterval,
-                                          maxRetryInterval,
-                                          retryIntervalMultiplier,
-                                          initialConnectAttempts,
-                                          reconnectAttempts,
-                                          reconnectAttemptsSameNode,
-                                          useDuplicateDetection,
-                                          confirmationWindowSize,
-                                          staticConnectorNames,
-                                          ha,
-                                          user,
-                                          password);
+         config.setStaticConnectors(staticConnectorNames);
       }
       else
       {
-         config = new BridgeConfiguration(name,
-                                          queueName,
-                                          forwardingAddress,
-                                          filterString,
-                                          transformerClassName,
-                                          minLargeMessageSize,
-                                          clientFailureCheckPeriod,
-                                          connectionTTL,
-                                          retryInterval,
-                                          maxRetryInterval,
-                                          retryIntervalMultiplier,
-                                          initialConnectAttempts,
-                                          reconnectAttempts,
-                                          reconnectAttemptsSameNode,
-                                          useDuplicateDetection,
-                                          confirmationWindowSize,
-                                          discoveryGroupName,
-                                          ha,
-                                          user,
-                                          password);
+         config.setDiscoveryGroupName(discoveryGroupName);
       }
 
       mainConfig.getBridgeConfigurations().add(config);
@@ -1655,13 +1901,14 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          }
       }
 
-      DivertConfiguration config = new DivertConfiguration(name,
-                                                           routingName,
-                                                           address,
-                                                           forwardingAddress,
-                                                           exclusive,
-                                                           filterString,
-                                                           transformerClassName);
+      DivertConfiguration config = new DivertConfiguration()
+         .setName(name)
+         .setRoutingName(routingName)
+         .setAddress(address)
+         .setForwardingAddress(forwardingAddress)
+         .setExclusive(exclusive)
+         .setFilterString(filterString)
+         .setTransformerClassName(transformerClassName);
 
       mainConfig.getDivertConfigurations().add(config);
    }
@@ -1693,6 +1940,9 @@ public final class FileConfigurationParser extends XMLConfigurationUtil
          params.put(key, nValue.getTextContent());
       }
 
-      return new ConnectorServiceConfiguration(clazz, params, name);
+      return new ConnectorServiceConfiguration()
+         .setFactoryClassName(clazz)
+         .setParams(params)
+         .setName(name);
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/management/impl/HornetQServerControlImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/management/impl/HornetQServerControlImpl.java b/hornetq-server/src/main/java/org/hornetq/core/management/impl/HornetQServerControlImpl.java
index ad9cc47..d606178 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/management/impl/HornetQServerControlImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/management/impl/HornetQServerControlImpl.java
@@ -24,25 +24,25 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
 
 import javax.management.ListenerNotFoundException;
 import javax.management.MBeanNotificationInfo;
 import javax.management.MBeanOperationInfo;
+import javax.management.Notification;
 import javax.management.NotificationBroadcasterSupport;
 import javax.management.NotificationEmitter;
 import javax.management.NotificationFilter;
 import javax.management.NotificationListener;
 import javax.transaction.xa.Xid;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.management.AddressControl;
 import org.hornetq.api.core.management.BridgeControl;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.DivertControl;
 import org.hornetq.api.core.management.HornetQServerControl;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.api.core.management.QueueControl;
 import org.hornetq.core.config.BridgeConfiguration;
 import org.hornetq.core.config.Configuration;
@@ -52,18 +52,29 @@ import org.hornetq.core.messagecounter.impl.MessageCounterManagerImpl;
 import org.hornetq.core.persistence.StorageManager;
 import org.hornetq.core.persistence.config.PersistedAddressSetting;
 import org.hornetq.core.persistence.config.PersistedRoles;
+import org.hornetq.core.postoffice.Binding;
 import org.hornetq.core.postoffice.DuplicateIDCache;
 import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.postoffice.impl.LocalQueueBinding;
 import org.hornetq.core.remoting.server.RemotingService;
 import org.hornetq.core.security.CheckType;
 import org.hornetq.core.security.Role;
+import org.hornetq.core.server.Consumer;
 import org.hornetq.core.server.HornetQMessageBundle;
 import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.JournalType;
+import org.hornetq.core.server.Queue;
+import org.hornetq.core.server.ServerConsumer;
 import org.hornetq.core.server.ServerSession;
+import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.server.cluster.ha.LiveOnlyPolicy;
+import org.hornetq.core.server.cluster.ha.ScaleDownPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreSlavePolicy;
 import org.hornetq.core.server.group.GroupingHandler;
 import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
 import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.core.settings.impl.SlowConsumerPolicy;
 import org.hornetq.core.transaction.ResourceManager;
 import org.hornetq.core.transaction.Transaction;
 import org.hornetq.core.transaction.TransactionDetail;
@@ -71,6 +82,7 @@ import org.hornetq.core.transaction.impl.CoreTransactionDetail;
 import org.hornetq.core.transaction.impl.XidImpl;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.utils.SecurityFormatter;
+import org.hornetq.utils.TypedProperties;
 import org.hornetq.utils.json.JSONArray;
 import org.hornetq.utils.json.JSONObject;
 
@@ -79,7 +91,8 @@ import org.hornetq.utils.json.JSONObject;
  *
  *
  */
-public class HornetQServerControlImpl extends AbstractControl implements HornetQServerControl, NotificationEmitter
+public class HornetQServerControlImpl extends AbstractControl implements HornetQServerControl, NotificationEmitter,
+                                                                         org.hornetq.core.server.management.NotificationListener
 {
    // Constants -----------------------------------------------------
 
@@ -99,6 +112,7 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
 
    private final NotificationBroadcasterSupport broadcaster;
 
+   private final AtomicLong notifSeq = new AtomicLong(0);
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
@@ -120,6 +134,7 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       server = messagingServer;
       this.messageCounterManager = messageCounterManager;
       this.broadcaster = broadcaster;
+      server.getManagementService().addNotificationListener(this);
    }
 
    // HornetQServerControlMBean implementation --------------------
@@ -159,7 +174,7 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       clearIO();
       try
       {
-         return configuration.getHAPolicy().isBackup();
+         return server.getHAPolicy().isBackup();
       }
       finally
       {
@@ -174,7 +189,7 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       clearIO();
       try
       {
-         return configuration.getHAPolicy().isSharedStore();
+         return server.getHAPolicy().isSharedStore();
       }
       finally
       {
@@ -284,7 +299,11 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       clearIO();
       try
       {
-         configuration.getHAPolicy().setFailoverOnServerShutdown(failoverOnServerShutdown);
+         HAPolicy haPolicy = server.getHAPolicy();
+         if (haPolicy instanceof SharedStoreSlavePolicy)
+         {
+            ((SharedStoreSlavePolicy) haPolicy).setFailoverOnServerShutdown(failoverOnServerShutdown);
+         }
       }
       finally
       {
@@ -300,7 +319,15 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       clearIO();
       try
       {
-         return configuration.getHAPolicy().isFailoverOnServerShutdown();
+         HAPolicy haPolicy = server.getHAPolicy();
+         if (haPolicy instanceof SharedStoreSlavePolicy)
+         {
+            return ((SharedStoreSlavePolicy) haPolicy).isFailoverOnServerShutdown();
+         }
+         else
+         {
+            return false;
+         }
       }
       finally
       {
@@ -1238,8 +1265,8 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
             String remoteAddress = connection.getRemoteAddress();
             if (remoteAddress.contains(ipAddress))
             {
-               remotingService.removeConnection(connection.getID());
                connection.fail(HornetQMessageBundle.BUNDLE.connectionsClosedByManagement(ipAddress));
+               remotingService.removeConnection(connection.getID());
                closed = true;
             }
          }
@@ -1253,6 +1280,94 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
 
    }
 
+   public synchronized boolean closeConsumerConnectionsForAddress(final String address)
+   {
+      boolean closed = false;
+      checkStarted();
+
+      clearIO();
+      try
+      {
+         for (Binding binding : postOffice.getMatchingBindings(SimpleString.toSimpleString(address)).getBindings())
+         {
+            if (binding instanceof LocalQueueBinding)
+            {
+               Queue queue = ((LocalQueueBinding) binding).getQueue();
+               for (Consumer consumer : queue.getConsumers())
+               {
+                  if (consumer instanceof ServerConsumer)
+                  {
+                     ServerConsumer serverConsumer = (ServerConsumer) consumer;
+                     RemotingConnection connection = null;
+
+                     for (RemotingConnection potentialConnection : remotingService.getConnections())
+                     {
+                        if (potentialConnection.getID().toString().equals(serverConsumer.getConnectionID()))
+                        {
+                           connection = potentialConnection;
+                        }
+                     }
+
+                     if (connection != null)
+                     {
+                        remotingService.removeConnection(connection.getID());
+                        connection.fail(HornetQMessageBundle.BUNDLE.consumerConnectionsClosedByManagement(address));
+                        closed = true;
+                     }
+                  }
+               }
+            }
+         }
+      }
+      catch (Exception e)
+      {
+         HornetQServerLogger.LOGGER.failedToCloseConsumerConnectionsForAddress(address, e);
+      }
+      finally
+      {
+         blockOnIO();
+      }
+      return closed;
+   }
+
+   public synchronized boolean closeConnectionsForUser(final String userName)
+   {
+      boolean closed = false;
+      checkStarted();
+
+      clearIO();
+      try
+      {
+         for (ServerSession serverSession : server.getSessions())
+         {
+            if (serverSession.getUsername() != null && serverSession.getUsername().equals(userName))
+            {
+               RemotingConnection connection = null;
+
+               for (RemotingConnection potentialConnection : remotingService.getConnections())
+               {
+                  if (potentialConnection.getID().toString().equals(serverSession.getConnectionID().toString()))
+                  {
+                     connection = potentialConnection;
+                  }
+               }
+
+               if (connection != null)
+               {
+                  remotingService.removeConnection(connection.getID());
+                  connection.fail(HornetQMessageBundle.BUNDLE.connectionsForUserClosedByManagement(userName));
+                  closed = true;
+               }
+            }
+         }
+      }
+      finally
+      {
+         blockOnIO();
+      }
+      return closed;
+   }
+
    public String[] listConnectionIDs()
    {
       checkStarted();
@@ -1511,6 +1626,11 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
             : addressSettings.getAddressFullMessagePolicy() == AddressFullMessagePolicy.DROP ? "DROP"
             : "FAIL";
       settings.put("addressFullMessagePolicy", policy);
+      settings.put("slowConsumerThreshold", addressSettings.getSlowConsumerThreshold());
+      settings.put("slowConsumerCheckPeriod", addressSettings.getSlowConsumerCheckPeriod());
+      policy = addressSettings.getSlowConsumerPolicy() == SlowConsumerPolicy.NOTIFY ? "NOTIFY"
+         : "KILL";
+      settings.put("slowConsumerPolicy", policy);
 
       JSONObject jsonObject = new JSONObject(settings);
       return jsonObject.toString();
@@ -1531,7 +1651,10 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
                                   final long maxRedeliveryDelay,
                                   final long redistributionDelay,
                                   final boolean sendToDLAOnNoRoute,
-                                  final String addressFullMessagePolicy) throws Exception
+                                  final String addressFullMessagePolicy,
+                                  final long slowConsumerThreshold,
+                                  final long slowConsumerCheckPeriod,
+                                  final String slowConsumerPolicy) throws Exception
    {
       checkStarted();
 
@@ -1580,6 +1703,20 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       {
          addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.FAIL);
       }
+      addressSettings.setSlowConsumerThreshold(slowConsumerThreshold);
+      addressSettings.setSlowConsumerCheckPeriod(slowConsumerCheckPeriod);
+      if (slowConsumerPolicy == null)
+      {
+         addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY);
+      }
+      else if (slowConsumerPolicy.equalsIgnoreCase("NOTIFY"))
+      {
+         addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY);
+      }
+      else if (slowConsumerPolicy.equalsIgnoreCase("KILL"))
+      {
+         addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.KILL);
+      }
       server.getAddressSettingsRepository().addMatch(address, addressSettings);
 
       storageManager.storeAddressSetting(new PersistedAddressSetting(new SimpleString(address), addressSettings));
@@ -1652,13 +1789,14 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       clearIO();
       try
       {
-         DivertConfiguration config = new DivertConfiguration(name,
-               routingName,
-               address,
-               forwardingAddress,
-               exclusive,
-               filterString,
-               transformerClassName);
+         DivertConfiguration config = new DivertConfiguration()
+            .setName(name)
+            .setRoutingName(routingName)
+            .setAddress(address)
+            .setForwardingAddress(forwardingAddress)
+            .setExclusive(exclusive)
+            .setFilterString(filterString)
+            .setTransformerClassName(transformerClassName);
          server.deployDivert(config);
       }
       finally
@@ -1717,7 +1855,7 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
                             final boolean useDuplicateDetection,
                             final int confirmationWindowSize,
                             final long clientFailureCheckPeriod,
-                            final String connectorNames,
+                            final String staticConnectorsOrDiscoveryGroup,
                             boolean useDiscoveryGroup,
                             final boolean ha,
                             final String user,
@@ -1727,57 +1865,34 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
 
       clearIO();
 
-
       try
       {
-         BridgeConfiguration config = null;
+         BridgeConfiguration config = new BridgeConfiguration()
+               .setName(name)
+               .setQueueName(queueName)
+               .setForwardingAddress(forwardingAddress)
+               .setFilterString(filterString)
+               .setTransformerClassName(transformerClassName)
+               .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+               .setRetryInterval(retryInterval)
+               .setRetryIntervalMultiplier(retryIntervalMultiplier)
+               .setInitialConnectAttempts(initialConnectAttempts)
+               .setReconnectAttempts(reconnectAttempts)
+               .setUseDuplicateDetection(useDuplicateDetection)
+               .setConfirmationWindowSize(confirmationWindowSize)
+               .setHA(ha)
+               .setUser(user)
+               .setPassword(password);
+
          if (useDiscoveryGroup)
          {
-            config = new BridgeConfiguration(name,
-                  queueName,
-                  forwardingAddress,
-                  filterString,
-                  transformerClassName,
-                  HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                  clientFailureCheckPeriod,
-                  HornetQClient.DEFAULT_CONNECTION_TTL,
-                  retryInterval,
-                  HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                  retryIntervalMultiplier,
-                  initialConnectAttempts,
-                  reconnectAttempts,
-                  HornetQDefaultConfiguration.getDefaultBridgeConnectSameNode(),
-                  useDuplicateDetection,
-                  confirmationWindowSize,
-                  connectorNames,
-                  ha,
-                  user,
-                  password);
+            config.setDiscoveryGroupName(staticConnectorsOrDiscoveryGroup);
          }
          else
          {
-            List<String> connectors = toList(connectorNames);
-            config = new BridgeConfiguration(name,
-                  queueName,
-                  forwardingAddress,
-                  filterString,
-                  transformerClassName,
-                  HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                  clientFailureCheckPeriod,
-                  HornetQClient.DEFAULT_CONNECTION_TTL,
-                  retryInterval,
-                  HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                  retryIntervalMultiplier,
-                  initialConnectAttempts,
-                  reconnectAttempts,
-                  HornetQDefaultConfiguration.getDefaultBridgeConnectSameNode(),
-                  useDuplicateDetection,
-                  confirmationWindowSize,
-                  connectors,
-                  ha,
-                  user,
-                  password);
+            config.setStaticConnectors(toList(staticConnectorsOrDiscoveryGroup));
          }
+
          server.deployBridge(config);
       }
       finally
@@ -1835,6 +1950,35 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
          blockOnIO();
       }
    }
+
+   @Override
+   public void scaleDown(String connector) throws Exception
+   {
+      checkStarted();
+
+      clearIO();
+      HAPolicy haPolicy = server.getHAPolicy();
+      if (haPolicy instanceof LiveOnlyPolicy)
+      {
+         LiveOnlyPolicy liveOnlyPolicy = (LiveOnlyPolicy) haPolicy;
+
+         if (liveOnlyPolicy.getScaleDownPolicy() == null)
+         {
+            liveOnlyPolicy.setScaleDownPolicy(new ScaleDownPolicy());
+         }
+
+         liveOnlyPolicy.getScaleDownPolicy().setEnabled(true);
+
+         if (connector != null)
+         {
+            liveOnlyPolicy.getScaleDownPolicy().getConnectors().add(0, connector);
+         }
+
+         server.stop(true);
+      }
+
+   }
+
    // NotificationEmitter implementation ----------------------------
 
    public void removeNotificationListener(final NotificationListener listener,
@@ -1882,7 +2026,7 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
 
    public MBeanNotificationInfo[] getNotificationInfo()
    {
-      NotificationType[] values = NotificationType.values();
+      CoreNotificationType[] values = CoreNotificationType.values();
       String[] names = new String[values.length];
       for (int i = 0; i < values.length; i++)
       {
@@ -2028,5 +2172,16 @@ public class HornetQServerControlImpl extends AbstractControl implements HornetQ
       return list;
    }
 
+   @Override
+   public void onNotification(org.hornetq.core.server.management.Notification notification)
+   {
+      if (!(notification.getType() instanceof CoreNotificationType)) return;
+      CoreNotificationType type = (CoreNotificationType) notification.getType();
+      TypedProperties prop = notification.getProperties();
+
+      this.broadcaster.sendNotification(new Notification(type.toString(), this,
+            notifSeq.incrementAndGet(), notification.toString()));
+   }
+
 }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/management/impl/QueueControlImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/management/impl/QueueControlImpl.java b/hornetq-server/src/main/java/org/hornetq/core/management/impl/QueueControlImpl.java
index 7d3102c..8208ad4 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/management/impl/QueueControlImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/management/impl/QueueControlImpl.java
@@ -254,6 +254,21 @@ public class QueueControlImpl extends AbstractControl implements QueueControl
       }
    }
 
+   public long getMessagesAcknowledged()
+   {
+      checkStarted();
+
+      clearIO();
+      try
+      {
+         return queue.getMessagesAcknowledged();
+      }
+      finally
+      {
+         blockOnIO();
+      }
+   }
+
    public long getID()
    {
       checkStarted();
@@ -926,6 +941,22 @@ public class QueueControlImpl extends AbstractControl implements QueueControl
       }
    }
 
+
+   public void flushExecutor()
+   {
+      checkStarted();
+
+      clearIO();
+      try
+      {
+         queue.flushExecutor();
+      }
+      finally
+      {
+         blockOnIO();
+      }
+   }
+
    @Override
    public String listConsumersAsJSON() throws Exception
    {
@@ -987,6 +1018,22 @@ public class QueueControlImpl extends AbstractControl implements QueueControl
 
    }
 
+   public void resetMessagesAcknowledged() throws Exception
+   {
+      checkStarted();
+
+      clearIO();
+      try
+      {
+         queue.resetMessagesAcknowledged();
+      }
+      finally
+      {
+         blockOnIO();
+      }
+
+   }
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/messagecounter/MessageCounter.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/messagecounter/MessageCounter.java b/hornetq-server/src/main/java/org/hornetq/core/messagecounter/MessageCounter.java
index d342bce..96a0851 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/messagecounter/MessageCounter.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/messagecounter/MessageCounter.java
@@ -130,7 +130,7 @@ public class MessageCounter
    {
       public void run()
       {
-         long latestMessagesAdded = serverQueue.getInstantMessagesAdded();
+         long latestMessagesAdded = serverQueue.getMessagesAdded();
 
          long newMessagesAdded = latestMessagesAdded - lastMessagesAdded;
 
@@ -213,7 +213,7 @@ public class MessageCounter
     */
    public long getMessageCount()
    {
-      return serverQueue.getInstantMessageCount();
+      return serverQueue.getMessageCount();
    }
 
    /**
@@ -222,7 +222,7 @@ public class MessageCounter
     */
    public long getMessageCountDelta()
    {
-      long current = serverQueue.getInstantMessageCount();
+      long current = serverQueue.getMessageCount();
       int delta = (int)(current - depthLast);
 
       depthLast = current;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/paging/PagingManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/paging/PagingManager.java b/hornetq-server/src/main/java/org/hornetq/core/paging/PagingManager.java
index def8e4d..7e6b0e1 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/paging/PagingManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/paging/PagingManager.java
@@ -21,16 +21,16 @@ import org.hornetq.core.settings.HierarchicalRepositoryChangeListener;
 /**
  * <PRE>
  *
- * +------------+      1  +-------------+       N +------------+       N +-------+       1 +----------------+
- * | {@link PostOffice} |-------&gt; |{@link PagingManager}|-------&gt; |{@link PagingStore} | ------&gt; | {@link Page}  | ------&gt; | {@link SequentialFile} |
- * +------------+         +-------------+         +------------+         +-------+         +----------------+
- *                               |                       1 ^
- *                               |                         |
- *                               |                         |
- *                               |                         | 1
- *                               |        N +---------+   /
- *                               +--------&gt; | {@link Address} |
- *                                          +---------+
+ * +--------------+      1  +----------------+       N +--------------+       N +--------+       1 +-------------------+
+ * | {@link org.hornetq.core.postoffice.PostOffice} |-------&gt; |{@link PagingManager}|-------&gt; |{@link PagingStore} | ------&gt; | {@link org.hornetq.core.paging.impl.Page}  | ------&gt; | {@link org.hornetq.core.journal.SequentialFile} |
+ * +--------------+         +----------------+         +--------------+         +--------+         +-------------------+
+ *                                                              |                  1 ^
+ *                                                              |                    |
+ *                                                              |                    |
+ *                                                              |                    | 1
+ *                                                              |            N +----------+
+ *                                                              +------------&gt; | {@link org.hornetq.core.postoffice.Address} |
+ *                                                                             +----------+
  * </PRE>
  * @author <a href="mailto:clebert.suconic@jboss.com">Clebert Suconic</a>
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/paging/PagingStore.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/paging/PagingStore.java b/hornetq-server/src/main/java/org/hornetq/core/paging/PagingStore.java
index e286f40..d151d72 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/paging/PagingStore.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/paging/PagingStore.java
@@ -154,7 +154,7 @@ public interface PagingStore extends HornetQComponent
    /**
     * Sends the pages with given IDs to the {@link ReplicationManager}.
     * <p/>
-    * Sending is done here to avoid exposing the internal {@link SequentialFile}s.
+    * Sending is done here to avoid exposing the internal {@link org.hornetq.core.journal.SequentialFile}s.
     *
     * @param replicator
     * @param pageIds

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageCursorProviderImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageCursorProviderImpl.java b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageCursorProviderImpl.java
index bf85d1d..11a5ba4 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageCursorProviderImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageCursorProviderImpl.java
@@ -91,9 +91,9 @@ public class PageCursorProviderImpl implements PageCursorProvider
 
    public synchronized PageSubscription createSubscription(long cursorID, Filter filter, boolean persistent)
    {
-      if (HornetQServerLogger.LOGGER.isDebugEnabled())
+      if (HornetQServerLogger.LOGGER.isTraceEnabled())
       {
-         HornetQServerLogger.LOGGER.debug(this.pagingStore.getAddress() + " creating subscription " + cursorID + " with filter " + filter, new Exception("trace"));
+         HornetQServerLogger.LOGGER.trace(this.pagingStore.getAddress() + " creating subscription " + cursorID + " with filter " + filter, new Exception("trace"));
       }
 
       if (activeCursors.containsKey(cursorID))

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PagePositionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PagePositionImpl.java b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PagePositionImpl.java
index 5b2cedc..12fda59 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PagePositionImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PagePositionImpl.java
@@ -41,14 +41,14 @@ public class PagePositionImpl implements PagePosition
     */
    public PagePositionImpl(long pageNr, int messageNr)
    {
-      super();
+      this();
       this.pageNr = pageNr;
       this.messageNr = messageNr;
    }
 
    public PagePositionImpl()
    {
-
+      super();
    }
 
    /**
@@ -151,4 +151,12 @@ public class PagePositionImpl implements PagePosition
       return "PagePositionImpl [pageNr=" + pageNr + ", messageNr=" + messageNr + ", recordID=" + recordID + "]";
    }
 
+   /**
+    * I needed a finalize method defined here just as a way to get a hook on the PagingLeakTest through ByteMan
+    * There is a rule for finalizing it where I'm establishing a counter, and that rule won't work without this method defined.
+    * So, please don't remove it unless you had to remove that test for any weird reason.. it's here for a purpose!
+    */
+   protected void finalize()
+   {
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionCounterImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionCounterImpl.java b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionCounterImpl.java
index 4100d0d..ddd0880 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionCounterImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionCounterImpl.java
@@ -346,7 +346,7 @@ public class PageSubscriptionCounterImpl implements PageSubscriptionCounter
 
       long newRecordID = -1;
 
-      long txCleanup = storage.generateUniqueID();
+      long txCleanup = storage.generateID();
 
       try
       {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionImpl.java b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionImpl.java
index 24d8bb7..acd56f6 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/paging/cursor/impl/PageSubscriptionImpl.java
@@ -335,6 +335,7 @@ final class PageSubscriptionImpl implements PageSubscription
          }
 
          infoPG.acks.clear();
+         infoPG.removedReferences.clear();
       }
 
       tx.addOperation(new TransactionOperationAbstract()
@@ -672,7 +673,7 @@ final class PageSubscriptionImpl implements PageSubscription
     */
    public void destroy() throws Exception
    {
-      final long tx = store.generateUniqueID();
+      final long tx = store.generateID();
       try
       {
 
@@ -752,7 +753,7 @@ final class PageSubscriptionImpl implements PageSubscription
                HornetQServerLogger.LOGGER.pageNotFound(pos);
                if (txDeleteCursorOnReload == -1)
                {
-                  txDeleteCursorOnReload = store.generateUniqueID();
+                  txDeleteCursorOnReload = store.generateID();
                }
                store.deleteCursorAcknowledgeTransactional(txDeleteCursorOnReload, pos.getRecordID());
             }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/paging/impl/PagingStoreImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/paging/impl/PagingStoreImpl.java b/hornetq-server/src/main/java/org/hornetq/core/paging/impl/PagingStoreImpl.java
index 2c16ef0..df06d41 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/paging/impl/PagingStoreImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/paging/impl/PagingStoreImpl.java
@@ -926,7 +926,7 @@ public class PagingStoreImpl implements PagingStore
 
             currentPage.write(pagedMessage);
 
-            if (tx == null && syncNonTransactional)
+            if (tx == null && syncNonTransactional && message.isDurable())
             {
                sync();
             }
@@ -1197,7 +1197,7 @@ public class PagingStoreImpl implements PagingStore
    }
 
    // To be used on isDropMessagesWhenFull
-   private boolean isFull()
+   public boolean isFull()
    {
       return maxSize > 0 && getAddressSize() > maxSize;
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/persistence/StorageManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/persistence/StorageManager.java b/hornetq-server/src/main/java/org/hornetq/core/persistence/StorageManager.java
index 7173f45..559a3c9 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/persistence/StorageManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/persistence/StorageManager.java
@@ -46,6 +46,7 @@ import org.hornetq.core.server.group.impl.GroupBinding;
 import org.hornetq.core.server.impl.JournalLoader;
 import org.hornetq.core.transaction.ResourceManager;
 import org.hornetq.core.transaction.Transaction;
+import org.hornetq.utils.IDGenerator;
 
 /**
  * A StorageManager
@@ -53,8 +54,17 @@ import org.hornetq.core.transaction.Transaction;
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  * @author <a href="mailto:clebert.suconic@jboss.com">Clebert Suconic</a>
  * @author <a href="mailto:andy.taylor@jboss.org>Andy Taylor</a>
+ *
+ * Note about IDGEnerator
+ *
+ *  I've changed StorageManager to extend IDGenerator, because in some places
+ *  all we needed from the StorageManager was the idGeneration.
+ *  I couldn't just get the IDGenerator from the inner part because the NullPersistent has its own sequence.
+ *  So the best was to add the interface and adjust the callers for the method
+ *
+
  */
-public interface StorageManager extends HornetQComponent
+public interface StorageManager extends IDGenerator, HornetQComponent
 {
 
    /**
@@ -144,10 +154,6 @@ public interface StorageManager extends HornetQComponent
 
    void clearContext();
 
-   long generateUniqueID();
-
-   long getCurrentUniqueID();
-
    /**
     * Confirms that a large message was finished
     */
@@ -336,8 +342,7 @@ public interface StorageManager extends HornetQComponent
    Journal getMessageJournal();
 
    /**
-    * @see JournalStorageManager#startReplication(ReplicationManager, PagingManager, String,
-    * boolean)
+    * @see org.hornetq.core.persistence.impl.journal.JournalStorageManager#startReplication(org.hornetq.core.replication.ReplicationManager, org.hornetq.core.paging.PagingManager, String, boolean)
     */
    void startReplication(ReplicationManager replicationManager, PagingManager pagingManager, String nodeID,
                          boolean autoFailBack) throws Exception;
@@ -397,10 +402,10 @@ public interface StorageManager extends HornetQComponent
    void readUnLock();
 
    /**
-    * Closes the {@link IDGenerator} persisting the current record ID.
+    * Closes the {@link org.hornetq.utils.IDGenerator} persisting the current record ID.
     * <p/>
     * Effectively a "pre-stop" method. Necessary due to the "stop"-order at
-    * {@link HornetQServerImpl}
+    * {@link org.hornetq.core.server.impl.HornetQServerImpl}
     */
    void persistIdGenerator();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/DescribeJournal.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/DescribeJournal.java b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/DescribeJournal.java
index 77f01dc..d00e056 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/DescribeJournal.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/DescribeJournal.java
@@ -14,17 +14,14 @@ package org.hornetq.core.persistence.impl.journal;
 
 import javax.transaction.xa.Xid;
 import java.io.PrintStream;
-import java.util.Arrays;
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQBuffers;
 import org.hornetq.api.core.Message;
-import org.hornetq.api.core.SimpleString;
 import org.hornetq.core.config.impl.ConfigurationImpl;
 import org.hornetq.core.journal.EncodingSupport;
 import org.hornetq.core.journal.PreparedTransactionInfo;
@@ -667,29 +664,8 @@ public final class DescribeJournal
          {
             buffer.append(";userMessageID=" + msg.getUserID().toString());
          }
-         buffer.append(";properties=[");
 
-         Set<SimpleString> properties = msg.getPropertyNames();
-
-         for (SimpleString prop : properties)
-         {
-            Object value = msg.getObjectProperty(prop);
-            if (value instanceof byte[])
-            {
-               buffer.append(prop + "=" + Arrays.toString((byte[])value) + ",");
-
-            }
-            else
-            {
-               buffer.append(prop + "=" + value + ",");
-            }
-         }
-
-         buffer.append("#properties = " + properties.size());
-
-         buffer.append("]");
-
-         buffer.append(" - " + msg.toString());
+         buffer.append(";msg=" + msg.toString());
 
          return buffer.toString();
       }


[21/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAManager.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAManager.java
index ec1892c..ff61df9 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAManager.java
@@ -12,574 +12,20 @@
  */
 package org.hornetq.core.server.cluster.ha;
 
-import org.hornetq.api.core.DiscoveryGroupConfiguration;
-import org.hornetq.api.core.HornetQBuffer;
-import org.hornetq.api.core.HornetQException;
-import org.hornetq.api.core.Pair;
-import org.hornetq.api.core.SimpleString;
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.api.core.client.TopologyMember;
-import org.hornetq.core.client.impl.ServerLocatorInternal;
-import org.hornetq.core.client.impl.Topology;
-import org.hornetq.core.client.impl.TopologyMemberImpl;
-import org.hornetq.core.config.BackupStrategy;
-import org.hornetq.core.config.Configuration;
-import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory;
-import org.hornetq.core.server.ActivationParams;
 import org.hornetq.core.server.HornetQComponent;
-import org.hornetq.core.server.HornetQMessageBundle;
 import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.HornetQServerLogger;
-import org.hornetq.core.server.cluster.ClusterControl;
-import org.hornetq.core.server.cluster.ClusterController;
-import org.hornetq.core.server.cluster.qourum.QuorumVote;
-import org.hornetq.core.server.cluster.qourum.QuorumVoteHandler;
-import org.hornetq.core.server.cluster.qourum.Vote;
-import org.hornetq.spi.core.security.HornetQSecurityManager;
 
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
 
 /*
-* An HAManager takes care of any colocated backups in a VM. These are either pre configured backups or backups requested
-* by other lives. It also takes care of the quorum voting to request backups.
+* An HAManager takes care of any colocated backups in a VM.
 * */
-public class HAManager implements HornetQComponent
+public interface HAManager extends HornetQComponent
 {
-   private static final SimpleString REQUEST_BACKUP_QUORUM_VOTE = new SimpleString("RequestBackupQuorumVote");
-
-   private final HAPolicy haPolicy;
-
-   private final HornetQSecurityManager securityManager;
-
-   private final  HornetQServer server;
-
-   private Set<Configuration> backupServerConfigurations;
-
-   private Map<String, HornetQServer> backupServers = new HashMap<>();
-
-   private boolean started;
-
-   public HAManager(HAPolicy haPolicy, HornetQSecurityManager securityManager, HornetQServer hornetQServer, Set<Configuration> backupServerConfigurations)
-   {
-      this.haPolicy = haPolicy;
-      this.securityManager = securityManager;
-      server = hornetQServer;
-      this.backupServerConfigurations = backupServerConfigurations;
-   }
-
-   /**
-    * starts the HA manager, any pre configured backups are started and if a backup is needed a quorum vote in initiated
-    */
-   public void start()
-   {
-      if (started)
-         return;
-      server.getClusterManager().getQuorumManager().registerQuorumHandler(new RequestBackupQuorumVoteHandler());
-      if (backupServerConfigurations != null)
-      {
-         for (Configuration configuration : backupServerConfigurations)
-         {
-            HornetQServer backup = server.createBackupServer(configuration);
-            backupServers.put(configuration.getName(), backup);
-         }
-      }
-      //start the backups
-      for (HornetQServer hornetQServer : backupServers.values())
-      {
-         try
-         {
-            hornetQServer.start();
-         }
-         catch (Exception e)
-         {
-            e.printStackTrace();
-         }
-      }
-
-      //vote for a backup if required
-      if (haPolicy.isRequestBackup())
-      {
-         server.getClusterManager().getQuorumManager().vote(new RequestBackupQuorumVote());
-      }
-      started = true;
-   }
-
-   /**
-    * stop any backups
-    */
-   public void stop()
-   {
-      for (HornetQServer hornetQServer : backupServers.values())
-      {
-         try
-         {
-            hornetQServer.stop();
-         }
-         catch (Exception e)
-         {
-            e.printStackTrace();
-            //todo
-         }
-      }
-      backupServers.clear();
-      started = false;
-   }
-
-   @Override
-   public boolean isStarted()
-   {
-      return started;
-   }
-
-   public synchronized boolean activateSharedStoreBackup(int backupSize, String journalDirectory, String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory) throws Exception
-   {
-      if (backupServers.size() >= haPolicy.getMaxBackups() || backupSize != backupServers.size())
-      {
-         return false;
-      }
-      Configuration configuration = server.getConfiguration().copy();
-      HornetQServer backup = server.createBackupServer(configuration);
-      try
-      {
-         int portOffset = haPolicy.getBackupPortOffset() * (backupServers.size() + 1);
-         String name = "colocated_backup_" + backupServers.size() + 1;
-         updateSharedStoreConfiguration(configuration, haPolicy.getBackupStrategy(), name, portOffset, haPolicy.getRemoteConnectors(), journalDirectory, bindingsDirectory, largeMessagesDirectory, pagingDirectory);
-         //make sure we don't restart as we are colocated
-         configuration.getHAPolicy().setRestartBackup(false);
-         backupServers.put(configuration.getName(), backup);
-         backup.start();
-      }
-      catch (Exception e)
-      {
-         backup.stop();
-         //todo log a warning
-         return false;
-      }
-      return true;
-   }
-
-   /**
-    * activate a backup server replicating from a specified node.
-    *
-    * @param backupSize the number of backups the requesting server thinks there are. if this is changed then we should
-    * decline and the requesting server can cast a re vote
-    * @param nodeID the id of the node to replicate from
-    * @return true if the server was created and started
-    * @throws Exception
-    */
-   public synchronized boolean activateReplicatedBackup(int backupSize, SimpleString nodeID) throws Exception
-   {
-      if (backupServers.size() >= haPolicy.getMaxBackups() || backupSize != backupServers.size())
-      {
-         return false;
-      }
-      Configuration configuration = server.getConfiguration().copy();
-      HornetQServer backup = server.createBackupServer(configuration);
-      try
-      {
-         TopologyMember member = server.getClusterManager().getDefaultConnection(null).getTopology().getMember(nodeID.toString());
-         int portOffset = haPolicy.getBackupPortOffset() * (backupServers.size() + 1);
-         String name = "colocated_backup_" + backupServers.size() + 1;
-         updateReplicatedConfiguration(configuration, haPolicy.getBackupStrategy(), name, portOffset, haPolicy.getRemoteConnectors());
-         backup.addActivationParam(ActivationParams.REPLICATION_ENDPOINT, member);
-         backupServers.put(configuration.getName(), backup);
-         backup.start();
-      }
-      catch (Exception e)
-      {
-         backup.stop();
-         HornetQServerLogger.LOGGER.activateReplicatedBackupFailed(e);
-         return false;
-      }
-      return true;
-   }
-
    /**
     * return the current backup servers
     *
     * @return the backups
     */
-   public Map<String, HornetQServer> getBackupServers()
-   {
-      return backupServers;
-   }
-
-   /**
-    * send a request to a live server to start a backup for us
-    *
-    * @param connectorPair the connector for the node to request a backup from
-    * @param backupSize the current size of the requested nodes backups
-    * @return true if the request wa successful.
-    * @throws Exception
-    */
-   private boolean requestBackup(Pair<TransportConfiguration, TransportConfiguration> connectorPair, int backupSize) throws Exception
-   {
-      ClusterController clusterController = server.getClusterManager().getClusterController();
-      try
-      (
-            ClusterControl clusterControl = clusterController.connectToNode(connectorPair.getA());
-      )
-      {
-         clusterControl.authorize();
-         if (haPolicy.getPolicyType() == HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE)
-         {
-
-            return clusterControl.requestSharedStoreBackup(backupSize,
-                                                    server.getConfiguration().getJournalDirectory(),
-                                                    server.getConfiguration().getBindingsDirectory(),
-                                                    server.getConfiguration().getLargeMessagesDirectory(),
-                                                    server.getConfiguration().getPagingDirectory());
-         }
-         else
-         {
-            return clusterControl.requestReplicatedBackup(backupSize, server.getNodeID());
-
-         }
-      }
-   }
-
-   /**
-    * update the backups configuration
-    *  @param backupConfiguration the configuration to update
-    * @param backupStrategy the strategy for the backup
-    * @param name the new name of the backup
-    * @param portOffset the offset for the acceptors and any connectors that need changing
-    * @param remoteConnectors the connectors that don't need off setting, typically remote
-    * @param journalDirectory
-    * @param bindingsDirectory
-    * @param largeMessagesDirectory
-    * @param pagingDirectory
-    */
-   private static void updateSharedStoreConfiguration(Configuration backupConfiguration,
-                                                      BackupStrategy backupStrategy,
-                                                      String name,
-                                                      int portOffset,
-                                                      List<String> remoteConnectors,
-                                                      String journalDirectory,
-                                                      String bindingsDirectory,
-                                                      String largeMessagesDirectory,
-                                                      String pagingDirectory)
-   {
-      backupConfiguration.getHAPolicy().setBackupStrategy(backupStrategy);
-      backupConfiguration.setName(name);
-      backupConfiguration.setJournalDirectory(journalDirectory);
-      backupConfiguration.setBindingsDirectory(bindingsDirectory);
-      backupConfiguration.setLargeMessagesDirectory(largeMessagesDirectory);
-      backupConfiguration.setPagingDirectory(pagingDirectory);
-      backupConfiguration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      updateAcceptorsAndConnectors(backupConfiguration, portOffset, remoteConnectors);
-   }
-
-   /**
-    * update the backups configuration
-    *
-    * @param backupConfiguration the configuration to update
-    * @param backupStrategy the strategy for the backup
-    * @param name the new name of the backup
-    * @param portOffset the offset for the acceptors and any connectors that need changing
-    * @param remoteConnectors the connectors that don't need off setting, typically remote
-    */
-   private static void updateReplicatedConfiguration(Configuration backupConfiguration,
-                                                     BackupStrategy backupStrategy,
-                                                     String name,
-                                                     int portOffset,
-                                                     List<String> remoteConnectors)
-   {
-      backupConfiguration.getHAPolicy().setBackupStrategy(backupStrategy);
-      backupConfiguration.setName(name);
-      backupConfiguration.setJournalDirectory(backupConfiguration.getJournalDirectory() + name);
-      backupConfiguration.setPagingDirectory(backupConfiguration.getPagingDirectory() + name);
-      backupConfiguration.setLargeMessagesDirectory(backupConfiguration.getLargeMessagesDirectory() + name);
-      backupConfiguration.setBindingsDirectory(backupConfiguration.getBindingsDirectory() + name);
-      backupConfiguration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-      updateAcceptorsAndConnectors(backupConfiguration, portOffset, remoteConnectors);
-   }
-
-   private static void updateAcceptorsAndConnectors(Configuration backupConfiguration, int portOffset, List<String> remoteConnectors)
-   {
-      //we only do this if we are a full server, if scale down then our acceptors wont be needed and our connectors will
-      // be the same as the parent server
-      if (backupConfiguration.getHAPolicy().getBackupStrategy() == BackupStrategy.FULL)
-      {
-         Set<TransportConfiguration> acceptors = backupConfiguration.getAcceptorConfigurations();
-         for (TransportConfiguration acceptor : acceptors)
-         {
-            updatebackupParams(backupConfiguration.getName(), portOffset, acceptor.getParams());
-         }
-         Map<String, TransportConfiguration> connectorConfigurations = backupConfiguration.getConnectorConfigurations();
-         for (Map.Entry<String, TransportConfiguration> entry : connectorConfigurations.entrySet())
-         {
-            //check to make sure we aren't a remote connector as this shouldn't be changed
-            if (!remoteConnectors.contains(entry.getValue().getName()))
-            {
-               updatebackupParams(backupConfiguration.getName(), portOffset, entry.getValue().getParams());
-            }
-         }
-      }
-      else if (backupConfiguration.getHAPolicy().getBackupStrategy() == BackupStrategy.SCALE_DOWN)
-      {
-         //if we are scaling down then we wont need any acceptors but clear anyway for belts and braces
-         backupConfiguration.getAcceptorConfigurations().clear();
-      }
-   }
-
-   private static void updatebackupParams(String name, int portOffset, Map<String, Object> params)
-   {
-      if (params != null)
-      {
-         Object port = params.get("port");
-         if (port != null)
-         {
-            Integer integer = Integer.valueOf(port.toString());
-            integer += portOffset;
-            params.put("port", integer.toString());
-         }
-         Object serverId = params.get("server-id");
-         if (serverId != null)
-         {
-            params.put("server-id", serverId.toString() + "(" + name + ")");
-         }
-      }
-   }
-
-   public HAPolicy getHAPolicy()
-   {
-      return haPolicy;
-   }
-
-   public ServerLocatorInternal getScaleDownConnector() throws HornetQException
-   {
-      if (!haPolicy.getScaleDownConnectors().isEmpty())
-      {
-         return (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(connectorNameListToArray(haPolicy.getScaleDownConnectors()));
-      }
-      else if (haPolicy.getScaleDownDiscoveryGroup() != null)
-      {
-         DiscoveryGroupConfiguration dg = server.getConfiguration().getDiscoveryGroupConfigurations().get(haPolicy.getScaleDownDiscoveryGroup());
-
-         if (dg == null)
-         {
-            throw HornetQMessageBundle.BUNDLE.noDiscoveryGroupFound(dg);
-         }
-         return  (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(dg);
-      }
-      else
-      {
-         Map<String, TransportConfiguration> connectorConfigurations = server.getConfiguration().getConnectorConfigurations();
-         for (TransportConfiguration transportConfiguration : connectorConfigurations.values())
-         {
-            if (transportConfiguration.getFactoryClassName().equals(InVMConnectorFactory.class.getName()))
-            {
-               return (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(transportConfiguration);
-            }
-         }
-      }
-      throw HornetQMessageBundle.BUNDLE.noConfigurationFoundForScaleDown();
-   }
-
-
-
-   private TransportConfiguration[] connectorNameListToArray(final List<String> connectorNames)
-   {
-      TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class,
-            connectorNames.size());
-      int count = 0;
-      for (String connectorName : connectorNames)
-      {
-         TransportConfiguration connector = server.getConfiguration().getConnectorConfigurations().get(connectorName);
-
-         if (connector == null)
-         {
-            HornetQServerLogger.LOGGER.bridgeNoConnector(connectorName);
-
-            return null;
-         }
-
-         tcConfigs[count++] = connector;
-      }
-
-      return tcConfigs;
-   }
-   /**
-    * A vote handler for incoming backup request votes
-    */
-   private final class RequestBackupQuorumVoteHandler implements QuorumVoteHandler
-   {
-      @Override
-      public Vote vote(Vote vote)
-      {
-         return new RequestBackupVote(backupServers.size(), server.getNodeID().toString(), backupServers.size() < haPolicy.getMaxBackups());
-      }
-
-      @Override
-      public SimpleString getQuorumName()
-      {
-         return REQUEST_BACKUP_QUORUM_VOTE;
-      }
-
-      @Override
-      public Vote decode(HornetQBuffer voteBuffer)
-      {
-         RequestBackupVote requestBackupVote = new RequestBackupVote();
-         requestBackupVote.decode(voteBuffer);
-         return requestBackupVote;
-      }
-   }
-
-   /**
-    * a quorum vote for backup requests
-    */
-   private final class RequestBackupQuorumVote extends QuorumVote<RequestBackupVote, Pair<String, Integer>>
-   {
-      //the available nodes that we can request
-      private final List<Pair<String, Integer>> nodes = new ArrayList<>();
-
-      public RequestBackupQuorumVote()
-      {
-         super(REQUEST_BACKUP_QUORUM_VOTE);
-      }
-
-      @Override
-      public Vote connected()
-      {
-         return new RequestBackupVote();
-      }
-
-      @Override
-      public Vote notConnected()
-      {
-         return new RequestBackupVote();
-      }
-
-      @Override
-      public void vote(RequestBackupVote vote)
-      {
-         //if the returned vote is available add it to the nodes we can request
-         if (vote.backupAvailable)
-         {
-            nodes.add(vote.getVote());
-         }
-      }
-
-      @Override
-      public Pair<String, Integer> getDecision()
-      {
-         //sort the nodes by how many backups they have and choose the first
-         Collections.sort(nodes, new Comparator<Pair<String, Integer>>()
-         {
-            @Override
-            public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2)
-            {
-               return o1.getB().compareTo(o2.getB());
-            }
-         });
-         return nodes.get(0);
-      }
-
-      @Override
-      public void allVotesCast(Topology voteTopology)
-      {
-         //if we have any nodes that we can request then send a request
-         if (nodes.size() > 0)
-         {
-            Pair<String, Integer> decision = getDecision();
-            TopologyMemberImpl member = voteTopology.getMember(decision.getA());
-            try
-            {
-               boolean backupStarted = requestBackup(member.getConnector(), decision.getB().intValue());
-               if (!backupStarted)
-               {
-                  nodes.clear();
-                  server.getScheduledPool().schedule(new Runnable()
-                  {
-                     @Override
-                     public void run()
-                     {
-                        server.getClusterManager().getQuorumManager().vote(new RequestBackupQuorumVote());
-                     }
-                  }, haPolicy.getBackupRequestRetryInterval(), TimeUnit.MILLISECONDS);
-               }
-            }
-            catch (Exception e)
-            {
-               e.printStackTrace();
-               //todo
-            }
-         }
-         else
-         {
-            nodes.clear();
-            server.getScheduledPool().schedule(new Runnable()
-            {
-               @Override
-               public void run()
-               {
-                  server.getClusterManager().getQuorumManager().vote(RequestBackupQuorumVote.this);
-               }
-            }, haPolicy.getBackupRequestRetryInterval(), TimeUnit.MILLISECONDS);
-         }
-      }
-
-      @Override
-      public SimpleString getName()
-      {
-         return REQUEST_BACKUP_QUORUM_VOTE;
-      }
-   }
-
-   class RequestBackupVote extends Vote<Pair<String, Integer>>
-   {
-      private int backupsSize;
-      private String nodeID;
-      private boolean backupAvailable;
-
-      public RequestBackupVote()
-      {
-         backupsSize = -1;
-      }
-
-      public RequestBackupVote(int backupsSize, String nodeID, boolean backupAvailable)
-      {
-         this.backupsSize = backupsSize;
-         this.nodeID = nodeID;
-         this.backupAvailable = backupAvailable;
-      }
-
-      @Override
-      public void encode(HornetQBuffer buff)
-      {
-         buff.writeInt(backupsSize);
-         buff.writeNullableString(nodeID);
-         buff.writeBoolean(backupAvailable);
-      }
-
-      @Override
-      public void decode(HornetQBuffer buff)
-      {
-         backupsSize = buff.readInt();
-         nodeID = buff.readNullableString();
-         backupAvailable = buff.readBoolean();
-      }
-
-      @Override
-      public boolean isRequestServerVote()
-      {
-         return true;
-      }
-
-      @Override
-      public Pair<String, Integer> getVote()
-      {
-         return new Pair<>(nodeID, backupsSize);
-      }
-   }
+   Map<String, HornetQServer> getBackupServers();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicy.java
index ed7c6de..a4003a9 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicy.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicy.java
@@ -12,344 +12,36 @@
  */
 package org.hornetq.core.server.cluster.ha;
 
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-import java.util.Set;
+import java.util.Map;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
-import org.hornetq.core.config.BackupStrategy;
+import org.hornetq.core.server.impl.Activation;
+import org.hornetq.core.server.impl.HornetQServerImpl;
 
 /**
  * Every live server will have an HAPolicy that configures the type of server that it should be either live, backup or
  * colocated (both). It also configures how, if colocated, it should react to sending and receiving requests for backups.
  */
-public class HAPolicy implements Serializable
+public interface HAPolicy<T extends Activation>
 {
-   /**
-    * the policy type for a server
-    */
-   public enum POLICY_TYPE
-   {
-      NONE((byte) 0),
-      REPLICATED((byte) 1),
-      SHARED_STORE((byte) 2),
-      BACKUP_REPLICATED((byte) 3),
-      BACKUP_SHARED_STORE((byte) 4),
-      COLOCATED_REPLICATED((byte) 5),
-      COLOCATED_SHARED_STORE((byte) 6);
+   /*
+   * created the Activation associated with this policy.
+   * */
+   T createActivation(HornetQServerImpl server, boolean wasLive, Map<String, Object> activationParams, HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception;
 
-      private static final Set<POLICY_TYPE> all = EnumSet.allOf(POLICY_TYPE.class);
-      private final byte type;
+   boolean isSharedStore();
 
-      POLICY_TYPE(byte type)
-      {
-         this.type = type;
-      }
+   boolean isBackup();
 
-      public byte getType()
-      {
-         return type;
-      }
+   boolean canScaleDown();
 
-      public static POLICY_TYPE toBackupType(byte b)
-      {
-         for (POLICY_TYPE backupType : all)
-         {
-            if (b == backupType.getType())
-            {
-               return backupType;
-            }
-         }
-         return null;
-      }
-   }
+   /*
+   * todo These 3 methods could probably be moved as they are specific to the activation however they are needed for certain packets.
+   * */
 
-   private POLICY_TYPE policyType = POLICY_TYPE.valueOf(HornetQDefaultConfiguration.getDefaultHapolicyType());
+   String getBackupGroupName();
 
-   private boolean requestBackup = HornetQDefaultConfiguration.isDefaultHapolicyRequestBackup();
+   String getScaleDownGroupName();
 
-   private int backupRequestRetries = HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetries();
+   String getScaleDownClustername();
 
-   private long backupRequestRetryInterval = HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetryInterval();
-
-   private int maxBackups = HornetQDefaultConfiguration.getDefaultHapolicyMaxBackups();
-
-   private int backupPortOffset = HornetQDefaultConfiguration.getDefaultHapolicyBackupPortOffset();
-
-   private BackupStrategy backupStrategy = BackupStrategy.valueOf(HornetQDefaultConfiguration.getDefaultHapolicyBackupStrategy());
-
-   private List<String> scaleDownConnectors = new ArrayList<>();
-
-   private String scaleDownDiscoveryGroup = null;
-
-   private String scaleDownGroupName = null;
-
-   private String backupGroupName = null;
-
-   private List<String> remoteConnectors = new ArrayList<>();
-
-   private boolean checkForLiverServer = HornetQDefaultConfiguration.isDefaultCheckForLiveServer();
-
-   private boolean allowAutoFailBack = HornetQDefaultConfiguration.isDefaultAllowAutoFailback();
-
-   private long failbackDelay = HornetQDefaultConfiguration.getDefaultFailbackDelay();
-
-   private boolean failoverOnServerShutdown = HornetQDefaultConfiguration.isDefaultFailoverOnServerShutdown();
-
-   private String replicationClusterName;
-
-   private String scaleDownClusterName;
-
-   private int maxSavedReplicatedJournalsSize = HornetQDefaultConfiguration.getDefaultMaxSavedReplicatedJournalsSize();
-
-   private boolean scaleDown = HornetQDefaultConfiguration.isDefaultScaleDown();
-
-   private boolean restartBackup = HornetQDefaultConfiguration.isDefaultRestartBackup();
-
-   public POLICY_TYPE getPolicyType()
-   {
-      return policyType;
-   }
-
-   public void setPolicyType(POLICY_TYPE policyType)
-   {
-      this.policyType = policyType;
-   }
-
-   public BackupStrategy getBackupStrategy()
-   {
-      return backupStrategy;
-   }
-
-   public void setBackupStrategy(BackupStrategy backupStrategy)
-   {
-      this.backupStrategy = backupStrategy;
-   }
-
-   /**
-    * Should we scaleDown our messages when the server is shutdown cleanly.
-    *
-    * @return true if server should scaleDown its messages on clean shutdown
-    * @see #setScaleDown(boolean)
-    */
-   public boolean isScaleDown()
-   {
-      return scaleDown;
-   }
-
-   /**
-    * Sets whether to allow the server to scaleDown its messages on server shutdown.
-    */
-   public void setScaleDown(boolean scaleDown)
-   {
-      this.scaleDown = scaleDown;
-   }
-
-   /**
-    * returns the name used to group
-    *
-    * @return the name of the group
-    */
-   public String getScaleDownGroupName()
-   {
-      return scaleDownGroupName;
-   }
-
-   /**
-    * Used to configure groups of live/backup servers.
-    *
-    * @param nodeGroupName the node group name
-    */
-   public void setScaleDownGroupName(String nodeGroupName)
-   {
-      this.scaleDownGroupName = nodeGroupName;
-   }
-
-   public String getBackupGroupName()
-   {
-      return backupGroupName;
-   }
-
-   public void setBackupGroupName(String backupGroupName)
-   {
-      this.backupGroupName = backupGroupName;
-   }
-
-   public List<String> getScaleDownConnectors()
-   {
-      return scaleDownConnectors;
-   }
-
-   public void setScaleDownConnectors(List<String> scaleDownConnectors)
-   {
-      this.scaleDownConnectors = scaleDownConnectors;
-   }
-
-   public void setScaleDownDiscoveryGroup(String scaleDownDiscoveryGroup)
-   {
-      this.scaleDownDiscoveryGroup = scaleDownDiscoveryGroup;
-   }
-
-   public String getScaleDownDiscoveryGroup()
-   {
-      return scaleDownDiscoveryGroup;
-   }
-
-   public boolean isRequestBackup()
-   {
-      return requestBackup;
-   }
-
-   public void setRequestBackup(boolean requestBackup)
-   {
-      this.requestBackup = requestBackup;
-   }
-
-   public int getBackupRequestRetries()
-   {
-      return backupRequestRetries;
-   }
-
-   public void setBackupRequestRetries(int backupRequestRetries)
-   {
-      this.backupRequestRetries = backupRequestRetries;
-   }
-
-   public long getBackupRequestRetryInterval()
-   {
-      return backupRequestRetryInterval;
-   }
-
-   public void setBackupRequestRetryInterval(long backupRequestRetryInterval)
-   {
-      this.backupRequestRetryInterval = backupRequestRetryInterval;
-   }
-
-   public int getMaxBackups()
-   {
-      return maxBackups;
-   }
-
-   public void setMaxBackups(int maxBackups)
-   {
-      this.maxBackups = maxBackups;
-   }
-
-   public int getBackupPortOffset()
-   {
-      return backupPortOffset;
-   }
-
-   public void setBackupPortOffset(int backupPortOffset)
-   {
-      this.backupPortOffset = backupPortOffset;
-   }
-
-   public List<String> getRemoteConnectors()
-   {
-      return remoteConnectors;
-   }
-
-   public void setRemoteConnectors(List<String> remoteConnectors)
-   {
-      this.remoteConnectors = remoteConnectors;
-   }
-
-   public boolean isCheckForLiveServer()
-   {
-      return checkForLiverServer;
-   }
-
-   public void setCheckForLiveServer(boolean checkForLiverServer)
-   {
-      this.checkForLiverServer = checkForLiverServer;
-   }
-
-   public boolean isAllowAutoFailBack()
-   {
-      return allowAutoFailBack;
-   }
-
-   public void setAllowAutoFailBack(boolean allowAutoFailBack)
-   {
-      this.allowAutoFailBack = allowAutoFailBack;
-   }
-
-   public long getFailbackDelay()
-   {
-      return failbackDelay;
-   }
-
-   public void setFailbackDelay(long failbackDelay)
-   {
-      this.failbackDelay = failbackDelay;
-   }
-
-   public boolean isFailoverOnServerShutdown()
-   {
-      return failoverOnServerShutdown;
-   }
-
-   public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
-   {
-      this.failoverOnServerShutdown = failoverOnServerShutdown;
-   }
-
-   public void setReplicationClustername(String clusterName)
-   {
-      this.replicationClusterName = clusterName;
-   }
-
-   public String getReplicationClustername()
-   {
-      return replicationClusterName;
-   }
-
-   public void setScaleDownClustername(String clusterName)
-   {
-      this.scaleDownClusterName = clusterName;
-   }
-
-   public String getScaleDownClustername()
-   {
-      return scaleDownClusterName;
-   }
-
-   public void setMaxSavedReplicatedJournalSize(int maxSavedReplicatedJournalsSize)
-   {
-      this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize;
-   }
-
-   public int getMaxSavedReplicatedJournalsSize()
-   {
-      return maxSavedReplicatedJournalsSize;
-   }
-
-   public boolean isRestartBackup()
-   {
-      return restartBackup;
-   }
-
-   public void setRestartBackup(boolean restartBackup)
-   {
-      this.restartBackup = restartBackup;
-   }
-
-   public boolean isSharedStore()
-   {
-      if (policyType == POLICY_TYPE.BACKUP_SHARED_STORE || policyType == POLICY_TYPE.SHARED_STORE || policyType == POLICY_TYPE.COLOCATED_SHARED_STORE)
-         return true;
-      else
-         return false;
-   }
-
-   public boolean isBackup()
-   {
-      if (policyType == POLICY_TYPE.BACKUP_SHARED_STORE || policyType == POLICY_TYPE.BACKUP_REPLICATED)
-         return true;
-      else
-         return false;
-   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicyTemplate.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicyTemplate.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicyTemplate.java
deleted file mode 100644
index cd9a09d..0000000
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/HAPolicyTemplate.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.core.server.cluster.ha;
-
-
-import org.hornetq.core.config.BackupStrategy;
-
-/**
- * a template for creating policy. this makes it easier in configuration and in embedded code to create a certain type
- * of policy. for instance:
- *
- * <ha-policy template="COLOCATED_REPLICATED"/>
- *
- * or in code
- *
- * HAPolicy policy = HAPolicyTemplate.COLOCATED_REPLICATED.getHaPolicy()
- */
-public enum HAPolicyTemplate
-{
-   NONE(createNonePolicy()),
-   REPLICATED(createReplicatedPolicy()),
-   SHARED_STORE(createSharedStorePolicy()),
-   BACKUP_REPLICATED(createBackupReplicatedPolicy()),
-   BACKUP_SHARED_STORE(createBackupSharedStorePolicy()),
-   COLOCATED_REPLICATED(createColocatedReplicatedPolicy()),
-   COLOCATED_SHARED_STORE(createColocatedSharedStorePolicy());
-
-   private final HAPolicy haPolicy;
-
-   public HAPolicy getHaPolicy()
-   {
-      return haPolicy;
-   }
-
-   HAPolicyTemplate(HAPolicy haPolicy)
-   {
-      this.haPolicy = haPolicy;
-   }
-
-   private static HAPolicy createNonePolicy()
-   {
-      HAPolicy policy = new HAPolicy();
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.NONE);
-      return policy;
-   }
-
-   private static HAPolicy createReplicatedPolicy()
-   {
-      HAPolicy policy = new HAPolicy();
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-      return policy;
-   }
-
-   private static HAPolicy createSharedStorePolicy()
-   {
-      HAPolicy policy = new HAPolicy();
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      return policy;
-   }
-
-   private static HAPolicy createBackupReplicatedPolicy()
-   {
-      HAPolicy policy = new HAPolicy();
-      policy.setMaxBackups(0);
-      policy.setRequestBackup(false);
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-      policy.setBackupStrategy(BackupStrategy.FULL);
-      policy.setRestartBackup(true);
-      return policy;
-   }
-
-   private static HAPolicy createBackupSharedStorePolicy()
-   {
-      HAPolicy policy = new HAPolicy();
-      policy.setMaxBackups(0);
-      policy.setRequestBackup(false);
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      policy.setBackupStrategy(BackupStrategy.FULL);
-      policy.setRestartBackup(true);
-      return policy;
-   }
-
-   private static HAPolicy createColocatedSharedStorePolicy()
-   {
-      HAPolicy policy = new HAPolicy();
-      policy.setBackupPortOffset(100);
-      policy.setBackupRequestRetries(-1);
-      policy.setBackupRequestRetryInterval(5000);
-      policy.setMaxBackups(2);
-      policy.setRequestBackup(true);
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE);
-      policy.setBackupStrategy(BackupStrategy.SCALE_DOWN);
-      return policy;
-   }
-
-   private static HAPolicy createColocatedReplicatedPolicy()
-   {
-      HAPolicy policy = new HAPolicy();
-      policy.setBackupPortOffset(100);
-      policy.setBackupRequestRetries(-1);
-      policy.setBackupRequestRetryInterval(5000);
-      policy.setMaxBackups(2);
-      policy.setRequestBackup(true);
-      policy.setPolicyType(HAPolicy.POLICY_TYPE.COLOCATED_REPLICATED);
-      policy.setBackupStrategy(BackupStrategy.SCALE_DOWN);
-      return policy;
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/LiveOnlyPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/LiveOnlyPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/LiveOnlyPolicy.java
new file mode 100644
index 0000000..499e1b3
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/LiveOnlyPolicy.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.core.server.impl.Activation;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.LiveOnlyActivation;
+
+import java.util.Map;
+
+public class LiveOnlyPolicy implements HAPolicy<Activation>
+{
+   private ScaleDownPolicy scaleDownPolicy;
+
+   public LiveOnlyPolicy()
+   {
+   }
+
+   public LiveOnlyPolicy(ScaleDownPolicy scaleDownPolicy)
+   {
+      this.scaleDownPolicy = scaleDownPolicy;
+   }
+
+   @Override
+   public Activation createActivation(HornetQServerImpl server, boolean wasLive, Map<String, Object> activationParams, HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO)
+   {
+      return new LiveOnlyActivation(server, this);
+   }
+
+   @Override
+   public String getBackupGroupName()
+   {
+      return null;
+   }
+
+   @Override
+   public String getScaleDownGroupName()
+   {
+      return scaleDownPolicy == null ? null : scaleDownPolicy.getGroupName();
+   }
+
+   @Override
+   public String getScaleDownClustername()
+   {
+      return null;
+   }
+
+   @Override
+   public boolean isSharedStore()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean isBackup()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean canScaleDown()
+   {
+      return scaleDownPolicy != null;
+   }
+
+   public ScaleDownPolicy getScaleDownPolicy()
+   {
+      return scaleDownPolicy;
+   }
+
+   public void setScaleDownPolicy(ScaleDownPolicy scaleDownPolicy)
+   {
+      this.scaleDownPolicy = scaleDownPolicy;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicaPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicaPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicaPolicy.java
new file mode 100644
index 0000000..64d591f
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicaPolicy.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.server.impl.Activation;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.SharedNothingBackupActivation;
+
+import java.util.Map;
+
+public class ReplicaPolicy extends BackupPolicy
+{
+   private String clusterName;
+
+   private int maxSavedReplicatedJournalsSize = HornetQDefaultConfiguration.getDefaultMaxSavedReplicatedJournalsSize();
+
+   private String groupName = null;
+
+   private boolean restartBackup = HornetQDefaultConfiguration.isDefaultRestartBackup();
+
+   private ReplicatedPolicy replicatedPolicy;
+
+   public ReplicaPolicy()
+   {
+   }
+
+   public ReplicaPolicy(String clusterName, int maxSavedReplicatedJournalsSize, String groupName, boolean restartBackup, boolean allowFailback, long failbackDelay, ScaleDownPolicy scaleDownPolicy)
+   {
+      this.clusterName = clusterName;
+      this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize;
+      this.groupName = groupName;
+      this.restartBackup = restartBackup;
+      this.scaleDownPolicy = scaleDownPolicy;
+      //todo check default settings
+      replicatedPolicy = new ReplicatedPolicy(false, allowFailback, failbackDelay, groupName, clusterName, this);
+   }
+
+   public ReplicaPolicy(String clusterName, int maxSavedReplicatedJournalsSize, String groupName, ReplicatedPolicy replicatedPolicy)
+   {
+      this.clusterName = clusterName;
+      this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize;
+      this.groupName = groupName;
+      this.replicatedPolicy = replicatedPolicy;
+   }
+
+   public String getClusterName()
+   {
+      return clusterName;
+   }
+
+   public void setClusterName(String clusterName)
+   {
+      this.clusterName = clusterName;
+   }
+
+   public int getMaxSavedReplicatedJournalsSize()
+   {
+      return maxSavedReplicatedJournalsSize;
+   }
+
+   public void setMaxSavedReplicatedJournalsSize(int maxSavedReplicatedJournalsSize)
+   {
+      this.maxSavedReplicatedJournalsSize = maxSavedReplicatedJournalsSize;
+   }
+
+   public ReplicatedPolicy getReplicatedPolicy()
+   {
+      return replicatedPolicy;
+   }
+
+   public void setReplicatedPolicy(ReplicatedPolicy replicatedPolicy)
+   {
+      this.replicatedPolicy = replicatedPolicy;
+   }
+
+   /*
+   * these 2 methods are the same, leaving both as the second is correct but the first is needed until more refactoring is done
+   * */
+   public String getBackupGroupName()
+   {
+      return groupName;
+   }
+
+   public String getGroupName()
+   {
+      return groupName;
+   }
+
+   public void setGroupName(String groupName)
+   {
+      this.groupName = groupName;
+   }
+
+   public boolean isRestartBackup()
+   {
+      return restartBackup;
+   }
+
+   public void setRestartBackup(boolean restartBackup)
+   {
+      this.restartBackup = restartBackup;
+   }
+
+   @Override
+   public boolean isSharedStore()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean canScaleDown()
+   {
+      return scaleDownPolicy != null;
+   }
+
+   @Override
+   public Activation createActivation(HornetQServerImpl server, boolean wasLive,
+                                      Map<String, Object> activationParams,
+                                      HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception
+   {
+      SharedNothingBackupActivation backupActivation = new SharedNothingBackupActivation(server, wasLive, activationParams, shutdownOnCriticalIO, this);
+      backupActivation.init();
+      return backupActivation;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicatedPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicatedPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicatedPolicy.java
new file mode 100644
index 0000000..cfb4439
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ReplicatedPolicy.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.LiveActivation;
+import org.hornetq.core.server.impl.SharedNothingLiveActivation;
+
+import java.util.Map;
+
+public class ReplicatedPolicy implements HAPolicy<LiveActivation>
+{
+   private boolean checkForLiveServer = HornetQDefaultConfiguration.isDefaultCheckForLiveServer();
+
+   private String groupName = null;
+
+   private String clusterName;
+
+   /*
+   * these are only set by the ReplicaPolicy after failover to decide if the live server can failback, these should not
+   * be exposed in configuration.
+   * */
+   private boolean allowAutoFailBack = HornetQDefaultConfiguration.isDefaultAllowAutoFailback();
+
+   private long failbackDelay = HornetQDefaultConfiguration.getDefaultFailbackDelay();
+
+   /*
+   * this is used as the policy when the server is started after a failover
+   * */
+   private ReplicaPolicy replicaPolicy;
+
+
+   public ReplicatedPolicy()
+   {
+   }
+
+   public ReplicatedPolicy(boolean checkForLiveServer, String groupName, String clusterName)
+   {
+      this.checkForLiveServer = checkForLiveServer;
+      this.groupName = groupName;
+      this.clusterName = clusterName;
+      /*
+      * we create this with sensible defaults in case we start after a failover
+      * */
+      replicaPolicy = new ReplicaPolicy(clusterName, -1, groupName, this);
+   }
+
+   public ReplicatedPolicy(boolean checkForLiveServer, boolean allowAutoFailBack, long failbackDelay, String groupName, String clusterName, ReplicaPolicy replicaPolicy)
+   {
+      this.checkForLiveServer = checkForLiveServer;
+      this.clusterName = clusterName;
+      this.groupName = groupName;
+      this.allowAutoFailBack = allowAutoFailBack;
+      this.failbackDelay = failbackDelay;
+      this.replicaPolicy = replicaPolicy;
+   }
+
+   public boolean isCheckForLiveServer()
+   {
+      return checkForLiveServer;
+   }
+
+   public void setCheckForLiveServer(boolean checkForLiveServer)
+   {
+      this.checkForLiveServer = checkForLiveServer;
+   }
+
+   public boolean isAllowAutoFailBack()
+   {
+      return allowAutoFailBack;
+   }
+
+   public long getFailbackDelay()
+   {
+      return failbackDelay;
+   }
+
+   public void setFailbackDelay(long failbackDelay)
+   {
+      this.failbackDelay = failbackDelay;
+   }
+
+   public String getClusterName()
+   {
+      return clusterName;
+   }
+
+   public void setClusterName(String clusterName)
+   {
+      this.clusterName = clusterName;
+   }
+
+   public ReplicaPolicy getReplicaPolicy()
+   {
+      return replicaPolicy;
+   }
+
+   public void setReplicaPolicy(ReplicaPolicy replicaPolicy)
+   {
+      this.replicaPolicy = replicaPolicy;
+   }
+
+   /*
+   * these 2 methods are the same, leaving both as the second is correct but the first is needed until more refactoring is done
+   * */
+   public String getBackupGroupName()
+   {
+      return groupName;
+   }
+
+   public String getGroupName()
+   {
+      return groupName;
+   }
+
+   @Override
+   public String getScaleDownGroupName()
+   {
+      return null;
+   }
+
+   public void setGroupName(String groupName)
+   {
+      this.groupName = groupName;
+   }
+
+   @Override
+   public boolean isSharedStore()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean isBackup()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean canScaleDown()
+   {
+      return false;
+   }
+
+   @Override
+   public String getScaleDownClustername()
+   {
+      return null;
+   }
+
+   @Override
+   public LiveActivation createActivation(HornetQServerImpl server, boolean wasLive, Map<String, Object> activationParams, HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO)
+   {
+      return new SharedNothingLiveActivation(server, this);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ScaleDownPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ScaleDownPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ScaleDownPolicy.java
new file mode 100644
index 0000000..a5fee77
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ScaleDownPolicy.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.core.DiscoveryGroupConfiguration;
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.core.client.impl.ServerLocatorInternal;
+import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory;
+import org.hornetq.core.server.HornetQMessageBundle;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServerLogger;
+
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class ScaleDownPolicy
+{
+   private List<String> connectors = new ArrayList<>();
+
+   private String discoveryGroup = null;
+
+   private String groupName = null;
+
+   private String clusterName;
+
+   private boolean enabled;
+
+   public ScaleDownPolicy()
+   {
+   }
+
+   public ScaleDownPolicy(List<String> connectors, String groupName, String clusterName, boolean enabled)
+   {
+      this.connectors = connectors;
+      this.groupName = groupName;
+      this.clusterName = clusterName;
+      this.enabled = enabled;
+   }
+
+   public ScaleDownPolicy(String discoveryGroup, String groupName, String clusterName, boolean enabled)
+   {
+      this.discoveryGroup = discoveryGroup;
+      this.groupName = groupName;
+      this.clusterName = clusterName;
+      this.enabled = enabled;
+   }
+
+
+   public List<String> getConnectors()
+   {
+      return connectors;
+   }
+
+   public void setConnectors(List<String> connectors)
+   {
+      this.connectors = connectors;
+   }
+
+   public String getDiscoveryGroup()
+   {
+      return discoveryGroup;
+   }
+
+   public void setDiscoveryGroup(String discoveryGroup)
+   {
+      this.discoveryGroup = discoveryGroup;
+   }
+
+   public String getGroupName()
+   {
+      return groupName;
+   }
+
+   public void setGroupName(String groupName)
+   {
+      this.groupName = groupName;
+   }
+
+   public String getClusterName()
+   {
+      return clusterName;
+   }
+
+   public void setClusterName(String clusterName)
+   {
+      this.clusterName = clusterName;
+   }
+
+   public boolean isEnabled()
+   {
+      return enabled;
+   }
+
+   public void setEnabled(boolean enabled)
+   {
+      this.enabled = enabled;
+   }
+
+   public static ServerLocatorInternal getScaleDownConnector(ScaleDownPolicy scaleDownPolicy, HornetQServer hornetQServer) throws HornetQException
+   {
+      if (!scaleDownPolicy.getConnectors().isEmpty())
+      {
+         return (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(connectorNameListToArray(scaleDownPolicy.getConnectors(), hornetQServer));
+      }
+      else if (scaleDownPolicy.getDiscoveryGroup() != null)
+      {
+         DiscoveryGroupConfiguration dg = hornetQServer.getConfiguration().getDiscoveryGroupConfigurations().get(scaleDownPolicy.getDiscoveryGroup());
+
+         if (dg == null)
+         {
+            throw HornetQMessageBundle.BUNDLE.noDiscoveryGroupFound(dg);
+         }
+         return  (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(dg);
+      }
+      else
+      {
+         Map<String, TransportConfiguration> connectorConfigurations = hornetQServer.getConfiguration().getConnectorConfigurations();
+         for (TransportConfiguration transportConfiguration : connectorConfigurations.values())
+         {
+            if (transportConfiguration.getFactoryClassName().equals(InVMConnectorFactory.class.getName()))
+            {
+               return (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(transportConfiguration);
+            }
+         }
+      }
+      throw HornetQMessageBundle.BUNDLE.noConfigurationFoundForScaleDown();
+   }
+
+   private static TransportConfiguration[] connectorNameListToArray(final List<String> connectorNames, HornetQServer hornetQServer)
+   {
+      TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class,
+            connectorNames.size());
+      int count = 0;
+      for (String connectorName : connectorNames)
+      {
+         TransportConfiguration connector = hornetQServer.getConfiguration().getConnectorConfigurations().get(connectorName);
+
+         if (connector == null)
+         {
+            HornetQServerLogger.LOGGER.bridgeNoConnector(connectorName);
+
+            return null;
+         }
+
+         tcConfigs[count++] = connector;
+      }
+
+      return tcConfigs;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreMasterPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreMasterPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreMasterPolicy.java
new file mode 100644
index 0000000..5aa848f
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreMasterPolicy.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.LiveActivation;
+import org.hornetq.core.server.impl.SharedStoreLiveActivation;
+
+import java.util.Map;
+
+public class SharedStoreMasterPolicy implements HAPolicy<LiveActivation>
+{
+   private long failbackDelay = HornetQDefaultConfiguration.getDefaultFailbackDelay();
+
+   private boolean failoverOnServerShutdown = HornetQDefaultConfiguration.isDefaultFailoverOnServerShutdown();
+
+   private SharedStoreSlavePolicy sharedStoreSlavePolicy;
+
+   public SharedStoreMasterPolicy()
+   {
+   }
+
+   public SharedStoreMasterPolicy(long failbackDelay, boolean failoverOnServerShutdown)
+   {
+      this.failbackDelay = failbackDelay;
+      this.failoverOnServerShutdown = failoverOnServerShutdown;
+   }
+
+   public long getFailbackDelay()
+   {
+      return failbackDelay;
+   }
+
+   public void setFailbackDelay(long failbackDelay)
+   {
+      this.failbackDelay = failbackDelay;
+   }
+
+   public boolean isFailoverOnServerShutdown()
+   {
+      return failoverOnServerShutdown;
+   }
+
+   public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
+   {
+      this.failoverOnServerShutdown = failoverOnServerShutdown;
+   }
+
+   public SharedStoreSlavePolicy getSharedStoreSlavePolicy()
+   {
+      return sharedStoreSlavePolicy;
+   }
+
+   public void setSharedStoreSlavePolicy(SharedStoreSlavePolicy sharedStoreSlavePolicy)
+   {
+      this.sharedStoreSlavePolicy = sharedStoreSlavePolicy;
+   }
+
+   @Override
+   public boolean isSharedStore()
+   {
+      return true;
+   }
+
+   @Override
+   public boolean isBackup()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean canScaleDown()
+   {
+      return false;
+   }
+
+   @Override
+   public LiveActivation createActivation(HornetQServerImpl server, boolean wasLive, Map<String, Object> activationParams, HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO)
+   {
+      return  new SharedStoreLiveActivation(server, this);
+   }
+
+   @Override
+   public String getBackupGroupName()
+   {
+      return null;
+   }
+
+   @Override
+   public String getScaleDownGroupName()
+   {
+      return null;
+   }
+
+   @Override
+   public String getScaleDownClustername()
+   {
+      return null;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreSlavePolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreSlavePolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreSlavePolicy.java
new file mode 100644
index 0000000..df6890f
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/SharedStoreSlavePolicy.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.server.impl.Activation;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.SharedStoreBackupActivation;
+
+import java.util.Map;
+
+public class SharedStoreSlavePolicy extends BackupPolicy
+{
+   private long failbackDelay = HornetQDefaultConfiguration.getDefaultFailbackDelay();
+
+   private boolean failoverOnServerShutdown = HornetQDefaultConfiguration.isDefaultFailoverOnServerShutdown();
+
+   private boolean allowAutoFailBack = HornetQDefaultConfiguration.isDefaultAllowAutoFailback();
+
+   //this is how we act once we have failed over
+   private SharedStoreMasterPolicy sharedStoreMasterPolicy;
+
+   public SharedStoreSlavePolicy()
+   {
+   }
+
+   public SharedStoreSlavePolicy(long failbackDelay, boolean failoverOnServerShutdown, boolean restartBackup, boolean allowAutoFailBack, ScaleDownPolicy scaleDownPolicy)
+   {
+      this.failbackDelay = failbackDelay;
+      this.failoverOnServerShutdown = failoverOnServerShutdown;
+      this.restartBackup = restartBackup;
+      this.allowAutoFailBack = allowAutoFailBack;
+      this.scaleDownPolicy = scaleDownPolicy;
+      sharedStoreMasterPolicy = new SharedStoreMasterPolicy(failbackDelay, failoverOnServerShutdown);
+   }
+
+   public long getFailbackDelay()
+   {
+      return failbackDelay;
+   }
+
+   public void setFailbackDelay(long failbackDelay)
+   {
+      this.failbackDelay = failbackDelay;
+   }
+
+   public boolean isFailoverOnServerShutdown()
+   {
+      return failoverOnServerShutdown;
+   }
+
+   public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
+   {
+      this.failoverOnServerShutdown = failoverOnServerShutdown;
+   }
+
+   public SharedStoreMasterPolicy getSharedStoreMasterPolicy()
+   {
+      return sharedStoreMasterPolicy;
+   }
+
+   public void setSharedStoreMasterPolicy(SharedStoreMasterPolicy sharedStoreMasterPolicy)
+   {
+      this.sharedStoreMasterPolicy = sharedStoreMasterPolicy;
+   }
+
+   @Override
+   public boolean isSharedStore()
+   {
+      return true;
+   }
+
+   @Override
+   public boolean canScaleDown()
+   {
+      return scaleDownPolicy != null;
+   }
+
+   public boolean isAllowAutoFailBack()
+   {
+      return allowAutoFailBack;
+   }
+
+   public void setAllowAutoFailBack(boolean allowAutoFailBack)
+   {
+      this.allowAutoFailBack = allowAutoFailBack;
+   }
+
+   @Override
+   public Activation createActivation(HornetQServerImpl server, boolean wasLive, Map<String, Object> activationParams, HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO)
+   {
+      return new SharedStoreBackupActivation(server, this);
+   }
+
+   @Override
+   public String getBackupGroupName()
+   {
+      return null;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/StandaloneHAManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/StandaloneHAManager.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/StandaloneHAManager.java
new file mode 100644
index 0000000..52934cd
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/StandaloneHAManager.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.core.server.HornetQServer;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/*
+* this implementation doesn't really do anything at the minute but this may change so Im leaving it here, Andy...
+* */
+public class StandaloneHAManager implements HAManager
+{
+   Map<String, HornetQServer> servers = new HashMap<>();
+
+   boolean isStarted = false;
+
+   @Override
+   public Map<String, HornetQServer> getBackupServers()
+   {
+      return servers;
+   }
+
+   @Override
+   public void start() throws Exception
+   {
+      if (isStarted)
+         return;
+      isStarted = true;
+   }
+
+   @Override
+   public void stop() throws Exception
+   {
+      if (!isStarted)
+         return;
+      isStarted = false;
+   }
+
+   @Override
+   public boolean isStarted()
+   {
+      return isStarted;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BridgeImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BridgeImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BridgeImpl.java
index 5e8fc75..4b49bbf 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BridgeImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BridgeImpl.java
@@ -33,7 +33,7 @@ import org.hornetq.api.core.client.ClusterTopologyListener;
 import org.hornetq.api.core.client.SendAcknowledgementHandler;
 import org.hornetq.api.core.client.SessionFailureListener;
 import org.hornetq.api.core.client.TopologyMember;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ClientSessionInternal;
@@ -262,7 +262,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled
       {
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), name);
-         Notification notification = new Notification(nodeUUID.toString(), NotificationType.BRIDGE_STARTED, props);
+         Notification notification = new Notification(nodeUUID.toString(), CoreNotificationType.BRIDGE_STARTED, props);
          notificationService.sendNotification(notification);
       }
    }
@@ -388,7 +388,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled
       {
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), name);
-         Notification notification = new Notification(nodeUUID.toString(), NotificationType.BRIDGE_STOPPED, props);
+         Notification notification = new Notification(nodeUUID.toString(), CoreNotificationType.BRIDGE_STOPPED, props);
          try
          {
             notificationService.sendNotification(notification);
@@ -413,7 +413,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled
       {
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), name);
-         Notification notification = new Notification(nodeUUID.toString(), NotificationType.BRIDGE_STOPPED, props);
+         Notification notification = new Notification(nodeUUID.toString(), CoreNotificationType.BRIDGE_STOPPED, props);
          try
          {
             notificationService.sendNotification(notification);
@@ -672,6 +672,12 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled
             }
          }
       }
+      else if (scaleDownTargetNodeID != null)
+      {
+         // the disconnected node is scaling down to me, no need to reconnect to it
+         HornetQServerLogger.LOGGER.debug("Received scaleDownTargetNodeID: " + scaleDownTargetNodeID + "; cancelling reconnect.");
+         fail(true);
+      }
       else
       {
          HornetQServerLogger.LOGGER.debug("Received invalid scaleDownTargetNodeID: " + scaleDownTargetNodeID);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BroadcastGroupImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BroadcastGroupImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BroadcastGroupImpl.java
index ab50cf8..28ce428 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BroadcastGroupImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/BroadcastGroupImpl.java
@@ -24,7 +24,7 @@ import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQBuffers;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.NodeManager;
 import org.hornetq.core.server.cluster.BroadcastGroup;
@@ -112,7 +112,7 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable
       {
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name));
-         Notification notification = new Notification(nodeManager.getNodeId().toString(), NotificationType.BROADCAST_GROUP_STARTED, props);
+         Notification notification = new Notification(nodeManager.getNodeId().toString(), CoreNotificationType.BROADCAST_GROUP_STARTED, props);
          notificationService.sendNotification(notification);
       }
 
@@ -146,7 +146,7 @@ public class BroadcastGroupImpl implements BroadcastGroup, Runnable
       {
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name));
-         Notification notification = new Notification(nodeManager.getNodeId().toString(), NotificationType.BROADCAST_GROUP_STOPPED, props);
+         Notification notification = new Notification(nodeManager.getNodeId().toString(), CoreNotificationType.BROADCAST_GROUP_STOPPED, props);
          try
          {
             notificationService.sendNotification(notification);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionBridge.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionBridge.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionBridge.java
index 80545e3..5b5eed1 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionBridge.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionBridge.java
@@ -12,7 +12,9 @@
  */
 package org.hornetq.core.server.cluster.impl;
 
+import java.util.ArrayList;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Set;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
@@ -24,8 +26,8 @@ import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientConsumer;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientProducer;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.api.core.management.ResourceNames;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
@@ -38,6 +40,7 @@ import org.hornetq.core.server.Queue;
 import org.hornetq.core.server.ServerMessage;
 import org.hornetq.core.server.cluster.ClusterConnection;
 import org.hornetq.core.server.cluster.ClusterManager;
+import org.hornetq.core.server.cluster.HornetQServerSideProtocolManagerFactory;
 import org.hornetq.core.server.cluster.MessageFlowRecord;
 import org.hornetq.core.server.cluster.Transformer;
 import org.hornetq.utils.UUID;
@@ -50,6 +53,7 @@ import org.hornetq.utils.UUIDGenerator;
  *
  * @author tim
  * @author Clebert Suconic
+ * @author <a href="mtaylor@redhat,com">Martyn Taylor</a>
  */
 public class ClusterConnectionBridge extends BridgeImpl
 {
@@ -135,9 +139,9 @@ public class ClusterConnectionBridge extends BridgeImpl
       // we need to disable DLQ check on the clustered bridges
       queue.setInternalQueue(true);
 
-      if (HornetQServerLogger.LOGGER.isDebugEnabled())
+      if (HornetQServerLogger.LOGGER.isTraceEnabled())
       {
-         HornetQServerLogger.LOGGER.debug("Setting up bridge between " + clusterConnection.getConnector() + " and " + targetLocator,
+         HornetQServerLogger.LOGGER.trace("Setting up bridge between " + clusterConnection.getConnector() + " and " + targetLocator,
                                           new Exception("trace"));
       }
    }
@@ -145,6 +149,7 @@ public class ClusterConnectionBridge extends BridgeImpl
    @Override
    protected ClientSessionFactoryInternal createSessionFactory() throws Exception
    {
+      serverLocator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
       ClientSessionFactoryInternal factory = (ClientSessionFactoryInternal) serverLocator.createSessionFactory(targetNodeID);
       setSessionFactory(factory);
 
@@ -247,28 +252,26 @@ public class ClusterConnectionBridge extends BridgeImpl
                                                    " AND " +
                                                    ManagementHelper.HDR_NOTIFICATION_TYPE +
                                                    " IN ('" +
-                                                   NotificationType.BINDING_ADDED +
+                                                   CoreNotificationType.BINDING_ADDED +
                                                    "','" +
-                                                   NotificationType.BINDING_REMOVED +
+                                                   CoreNotificationType.BINDING_REMOVED +
                                                    "','" +
-                                                   NotificationType.CONSUMER_CREATED +
+                                                   CoreNotificationType.CONSUMER_CREATED +
                                                    "','" +
-                                                   NotificationType.CONSUMER_CLOSED +
+                                                   CoreNotificationType.CONSUMER_CLOSED +
                                                    "','" +
-                                                   NotificationType.PROPOSAL +
+                                                   CoreNotificationType.PROPOSAL +
                                                    "','" +
-                                                   NotificationType.PROPOSAL_RESPONSE +
+                                                   CoreNotificationType.PROPOSAL_RESPONSE +
                                                    "','" +
-                                                   NotificationType.UNPROPOSAL +
+                                                   CoreNotificationType.UNPROPOSAL +
                                                    "') AND " +
                                                    ManagementHelper.HDR_DISTANCE +
                                                    "<" +
                                                    flowRecord.getMaxHops() +
                                                    " AND (" +
-                                                   ManagementHelper.HDR_ADDRESS +
-                                                   " LIKE '" +
-                                                   flowRecord.getAddress() +
-                                                   "%')");
+                                                   createSelectorFromAddress(flowRecord.getAddress()) +
+                                                   ")");
 
          session.createTemporaryQueue(managementNotificationAddress, notifQueueName, filter);
 
@@ -279,8 +282,10 @@ public class ClusterConnectionBridge extends BridgeImpl
          session.start();
 
          ClientMessage message = session.createMessage(false);
-
-         HornetQServerLogger.LOGGER.debug("Requesting sendQueueInfoToQueue through " + this, new Exception("trace"));
+         if (HornetQServerLogger.LOGGER.isTraceEnabled())
+         {
+            HornetQServerLogger.LOGGER.trace("Requesting sendQueueInfoToQueue through " + this, new Exception("trace"));
+         }
          ManagementHelper.putOperationInvocation(message,
                                                  ResourceNames.CORE_SERVER,
                                                  "sendQueueInfoToQueue",
@@ -298,6 +303,79 @@ public class ClusterConnectionBridge extends BridgeImpl
       }
    }
 
+   /**
+    * Takes in a string of an address filter or comma separated list and generates an appropriate JMS selector for
+    * filtering queues.
+    * @param address
+    */
+   public static String createSelectorFromAddress(String address)
+   {
+      StringBuilder stringBuilder = new StringBuilder();
+
+      // Support standard address (not a list) case.
+      if (!address.contains(","))
+      {
+         if (address.startsWith("!"))
+         {
+            stringBuilder.append(ManagementHelper.HDR_ADDRESS + " NOT LIKE '" + address.substring(1, address.length()) + "%'");
+         }
+         else
+         {
+            stringBuilder.append(ManagementHelper.HDR_ADDRESS +  " LIKE '" + address + "%'");
+         }
+         return stringBuilder.toString();
+      }
+
+      // For comma separated lists build a JMS selector statement based on the list items
+      return buildSelectorFromArray(address.split(","));
+   }
+
+   public static String buildSelectorFromArray(String[] list)
+   {
+      List<String> includes = new ArrayList<String>();
+      List<String> excludes = new ArrayList<String>();
+
+      // Split the list into addresses to match and addresses to exclude.
+      for (int i = 0; i < list.length; i++)
+      {
+         if (list[i].startsWith("!"))
+         {
+            excludes.add(list[i].substring(1, list[i].length()));
+         }
+         else
+         {
+            includes.add(list[i]);
+         }
+      }
+
+      // Build the address matching part of the selector
+      StringBuilder builder = new StringBuilder("(");
+      if (includes.size() > 0)
+      {
+         if (excludes.size() > 0) builder.append("(");
+         for (int i = 0; i < includes.size(); i++)
+         {
+            builder.append("(" + ManagementHelper.HDR_ADDRESS + " LIKE '" + includes.get(i) + "%')");
+            if (i < includes.size() - 1) builder.append(" OR ");
+         }
+         if (excludes.size() > 0) builder.append(")");
+      }
+
+      // Build the address exclusion part of the selector
+      if (excludes.size() > 0)
+      {
+         if (includes.size() > 0) builder.append(" AND (");
+         for (int i = 0; i < excludes.size(); i++)
+         {
+            builder.append("(" + ManagementHelper.HDR_ADDRESS + " NOT LIKE '" + excludes.get(i) + "%')");
+            if (i < excludes.size() - 1) builder.append(" AND ");
+         }
+         if (includes.size() > 0) builder.append(")");
+      }
+      builder.append(")");
+      return builder.toString();
+   }
+
    @Override
    protected void afterConnect() throws Exception
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionImpl.java
index 60f1058..3cec130 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/impl/ClusterConnectionImpl.java
@@ -33,8 +33,8 @@ import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClusterTopologyListener;
 import org.hornetq.api.core.client.TopologyMember;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.client.impl.AfterConnectInternalListener;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorImpl;
@@ -45,7 +45,6 @@ import org.hornetq.core.postoffice.Binding;
 import org.hornetq.core.postoffice.Bindings;
 import org.hornetq.core.postoffice.PostOffice;
 import org.hornetq.core.postoffice.impl.PostOfficeImpl;
-import org.hornetq.core.protocol.ServerPacketDecoder;
 import org.hornetq.core.server.HornetQMessageBundle;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
@@ -56,6 +55,7 @@ import org.hornetq.core.server.cluster.ClusterConnection;
 import org.hornetq.core.server.cluster.ClusterControl;
 import org.hornetq.core.server.cluster.ClusterManager;
 import org.hornetq.core.server.cluster.ClusterManager.IncomingInterceptorLookingForExceptionMessage;
+import org.hornetq.core.server.cluster.HornetQServerSideProtocolManagerFactory;
 import org.hornetq.core.server.cluster.MessageFlowRecord;
 import org.hornetq.core.server.cluster.RemoteQueueBinding;
 import org.hornetq.core.server.group.impl.Proposal;
@@ -67,9 +67,6 @@ import org.hornetq.utils.ExecutorFactory;
 import org.hornetq.utils.FutureLatch;
 import org.hornetq.utils.TypedProperties;
 
-import static org.hornetq.api.core.management.NotificationType.CONSUMER_CLOSED;
-import static org.hornetq.api.core.management.NotificationType.CONSUMER_CREATED;
-
 /**
  * A ClusterConnectionImpl
  *
@@ -437,7 +434,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), name);
          Notification notification = new Notification(nodeManager.getNodeId().toString(),
-                                                      NotificationType.CLUSTER_CONNECTION_STOPPED,
+                                                      CoreNotificationType.CLUSTER_CONNECTION_STOPPED,
                                                       props);
          managementService.sendNotification(notification);
       }
@@ -652,7 +649,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
 
          serverLocator.setAfterConnectionInternalListener(this);
 
-         serverLocator.setPacketDecoder(ServerPacketDecoder.INSTANCE);
+         serverLocator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
 
          serverLocator.start(server.getExecutorFactory().getExecutor());
       }
@@ -662,7 +659,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), name);
          Notification notification = new Notification(nodeManager.getNodeId().toString(),
-                                                      NotificationType.CLUSTER_CONNECTION_STARTED,
+                                                      CoreNotificationType.CLUSTER_CONNECTION_STARTED,
                                                       props);
          HornetQServerLogger.LOGGER.debug("sending notification: " + notification);
          managementService.sendNotification(notification);
@@ -845,7 +842,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
 
       targetLocator.setAfterConnectionInternalListener(this);
 
-      targetLocator.setPacketDecoder(ServerPacketDecoder.INSTANCE);
+      serverLocator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
 
       targetLocator.setNodeID(nodeId);
 
@@ -1133,7 +1130,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
          // a list of integers
          SimpleString type = message.getSimpleStringProperty(ManagementHelper.HDR_NOTIFICATION_TYPE);
 
-         NotificationType ntype = NotificationType.valueOf(type.toString());
+         CoreNotificationType ntype = CoreNotificationType.valueOf(type.toString());
 
          switch (ntype)
          {
@@ -1366,7 +1363,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
             return;
          }
 
-         RemoteQueueBinding binding = new RemoteQueueBindingImpl(server.getStorageManager().generateUniqueID(),
+         RemoteQueueBinding binding = new RemoteQueueBindingImpl(server.getStorageManager().generateID(),
                                                                  queueAddress,
                                                                  clusterName,
                                                                  routingName,
@@ -1503,7 +1500,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
             props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filterString);
          }
 
-         Notification notification = new Notification(null, CONSUMER_CREATED, props);
+         Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CREATED, props);
 
          managementService.sendNotification(notification);
       }
@@ -1560,7 +1557,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
          {
             props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, filterString);
          }
-         Notification notification = new Notification(null, CONSUMER_CLOSED, props);
+         Notification notification = new Notification(null, CoreNotificationType.CONSUMER_CLOSED, props);
 
          managementService.sendNotification(notification);
       }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/qourum/Quorum.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/qourum/Quorum.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/qourum/Quorum.java
index 88441a4..e5956bd 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/qourum/Quorum.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/qourum/Quorum.java
@@ -15,7 +15,7 @@ package org.hornetq.core.server.cluster.qourum;
 import org.hornetq.core.client.impl.Topology;
 
 /**
- * A quorum can be registered with the @link QuorumManager to receive notifications about the state of a cluster.
+ * A quorum can be registered with the {@link QuorumManager} to receive notifications about the state of a cluster.
  * It can then use the {@link QuorumManager} for the quorum within a cluster to vote on a specific outcome.
  * */
 public interface Quorum


[43/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/Interceptor.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/Interceptor.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/Interceptor.java
index 6f56d00..8b23cea 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/Interceptor.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/Interceptor.java
@@ -20,7 +20,7 @@ import org.hornetq.spi.core.protocol.RemotingConnection;
  * <p>
  * To add an interceptor to HornetQ server, you have to modify the server configuration file
  * {@literal hornetq-configuration.xml}.<br>
- * To add it to a client, use {@link ServerLocator#addIncomingInterceptor(Interceptor)}
+ * To add it to a client, use {@link org.hornetq.api.core.client.ServerLocator#addIncomingInterceptor(Interceptor)}
  *
  * @author clebert.suconic@jboss.com
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/JGroupsBroadcastGroupConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/JGroupsBroadcastGroupConfiguration.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/JGroupsBroadcastGroupConfiguration.java
index 208c7b7..6c55c38 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/JGroupsBroadcastGroupConfiguration.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/JGroupsBroadcastGroupConfiguration.java
@@ -24,6 +24,7 @@ import java.util.concurrent.TimeUnit;
 import org.jgroups.JChannel;
 import org.jgroups.Message;
 import org.jgroups.ReceiverAdapter;
+import org.jgroups.conf.PlainConfigurator;
 
 /**
  * The configuration for creating broadcasting/discovery groups using JGroups channels
@@ -55,6 +56,8 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
    {
       factory = new BroadcastEndpointFactory()
       {
+         private static final long serialVersionUID = 1047956472941098435L;
+
          @Override
          public BroadcastEndpoint createBroadcastEndpoint() throws Exception
          {
@@ -69,6 +72,8 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
    {
       factory = new BroadcastEndpointFactory()
       {
+         private static final long serialVersionUID = 5110372849181145377L;
+
          @Override
          public BroadcastEndpoint createBroadcastEndpoint() throws Exception
          {
@@ -182,12 +187,23 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
          broadcastOpened = true;
       }
 
-      private void initChannel(final String fileName, final String channelName) throws Exception
+      private void initChannel(final String jgroupsConfig, final String channelName) throws Exception
       {
-         URL configURL = Thread.currentThread().getContextClassLoader().getResource(fileName);
+         PlainConfigurator configurator = new PlainConfigurator(jgroupsConfig);
+         try
+         {
+            this.channel = JChannelManager.getJChannel(channelName, configurator);
+            return;
+         }
+         catch (Exception e)
+         {
+            this.channel = null;
+         }
+         URL configURL = Thread.currentThread().getContextClassLoader().getResource(jgroupsConfig);
+
          if (configURL == null)
          {
-            throw new RuntimeException("couldn't find JGroups configuration " + fileName);
+            throw new RuntimeException("couldn't find JGroups configuration " + jgroupsConfig);
          }
          this.channel = JChannelManager.getJChannel(channelName, configURL);
       }
@@ -242,45 +258,6 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
       }
 
       /**
-       * This is used for identifying a unique JChannel instance.
-       * Because we have two ways to get a JChannel (by configuration
-       * or by passing in a JChannel instance), the key needs to take
-       * this into consideration when doing comparison.
-       *
-       * @param <T> : either being a JChannel or a URL representing the JGroups
-       *            configuration file.
-       */
-      private static class ChannelKey<T>
-      {
-         private final String name;
-         private final T channelSource;
-
-         public ChannelKey(String name, T t)
-         {
-            this.name = name;
-            this.channelSource = t;
-         }
-
-         @Override
-         public int hashCode()
-         {
-            return name.hashCode();
-         }
-
-         @Override
-         public boolean equals(Object t)
-         {
-            if (t == null || (!(t instanceof ChannelKey)))
-            {
-               return false;
-            }
-
-            ChannelKey<?> key = (ChannelKey<?>) t;
-            return (name.equals(key.name) && channelSource.equals(key.channelSource));
-         }
-      }
-
-      /**
        * This class wraps a JChannel with a reference counter. The reference counter
        * controls the life of the JChannel. When reference count is zero, the channel
        * will be disconnected.
@@ -292,7 +269,6 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
          int refCount = 1;
          JChannel channel;
          String channelName;
-         T source;
          List<JGroupsReceiver> receivers = new ArrayList<JGroupsReceiver>();
 
          public JChannelWrapper(String channelName, T t) throws Exception
@@ -307,11 +283,14 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
             {
                this.channel = (JChannel) t;
             }
+            else if (t instanceof PlainConfigurator)
+            {
+               this.channel = new JChannel((PlainConfigurator)t);
+            }
             else
             {
                throw new IllegalArgumentException("Unsupported type " + t);
             }
-            this.source = t;
          }
 
          public synchronized void close()
@@ -319,7 +298,7 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
             refCount--;
             if (refCount == 0)
             {
-               JChannelManager.closeChannel(new ChannelKey<T>(this.channelName, source), this.channelName, channel);
+               JChannelManager.closeChannel(this.channelName, channel);
             }
          }
 
@@ -387,31 +366,30 @@ public final class JGroupsBroadcastGroupConfiguration implements BroadcastEndpoi
        */
       private static class JChannelManager
       {
-         private static Map<ChannelKey<?>, JChannelWrapper<?>> channels;
+         private static Map<String, JChannelWrapper<?>> channels;
 
          public static synchronized <T> JChannelWrapper<?> getJChannel(String channelName, T t) throws Exception
          {
             if (channels == null)
             {
-               channels = new HashMap<ChannelKey<?>, JChannelWrapper<?>>();
+               channels = new HashMap<String, JChannelWrapper<?>>();
             }
-            ChannelKey<T> key = new ChannelKey<T>(channelName, t);
-            JChannelWrapper<?> wrapper = channels.get(key);
+            JChannelWrapper<?> wrapper = channels.get(channelName);
             if (wrapper == null)
             {
                wrapper = new JChannelWrapper<T>(channelName, t);
-               channels.put(key, wrapper);
+               channels.put(channelName, wrapper);
                return wrapper;
             }
             return wrapper.addRef();
          }
 
-         public static synchronized void closeChannel(ChannelKey<?> key, String channelName, JChannel channel)
+         public static synchronized void closeChannel(String channelName, JChannel channel)
          {
             channel.setReceiver(null);
             channel.disconnect();
             channel.close();
-            JChannelWrapper<?> wrapper = channels.remove(key);
+            JChannelWrapper<?> wrapper = channels.remove(channelName);
             if (wrapper == null)
             {
                throw new IllegalStateException("Did not find channel " + channelName);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/Message.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/Message.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/Message.java
index 52867f8..2f93e25 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/Message.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/Message.java
@@ -44,7 +44,7 @@ import org.hornetq.utils.UUID;
  * </pre>
  * <p>
  * If conversion is not allowed (for example calling {@code getFloatProperty} on a property set a
- * {@code boolean}), a {@link PropertyConversionException} will be thrown.
+ * {@code boolean}), a {@link HornetQPropertyConversionException} will be thrown.
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  * @author <a href="mailto:clebert.suconic@jboss.com">ClebertSuconic</a>
@@ -104,7 +104,7 @@ public interface Message
     *
     * @param userID
     */
-   void setUserID(UUID userID);
+   Message setUserID(UUID userID);
 
    /**
     * Returns the address this message is sent to.
@@ -135,7 +135,7 @@ public interface Message
     *
     * @param durable {@code true} to flag this message as durable, {@code false} else
     */
-   void setDurable(boolean durable);
+   Message setDurable(boolean durable);
 
    /**
     * Returns the expiration time of this message.
@@ -152,7 +152,7 @@ public interface Message
     *
     * @param expiration expiration time
     */
-   void setExpiration(long expiration);
+   Message setExpiration(long expiration);
 
    /**
     * Returns the message timestamp.
@@ -167,7 +167,7 @@ public interface Message
     *
     * @param timestamp timestamp
     */
-   void setTimestamp(long timestamp);
+   Message setTimestamp(long timestamp);
 
    /**
     * Returns the message priority.
@@ -183,7 +183,7 @@ public interface Message
     *
     * @param priority the new message priority
     */
-   void setPriority(byte priority);
+   Message setPriority(byte priority);
 
    /**
     * Returns the size of the <em>encoded</em> message.
@@ -201,6 +201,16 @@ public interface Message
    HornetQBuffer getBodyBuffer();
 
    /**
+    * Writes the input byte array to the message body HornetQBuffer
+    */
+   Message writeBodyBufferBytes(byte[] bytes);
+
+   /**
+    * Writes the input String to the message body HornetQBuffer
+    */
+   Message writeBodyBufferString(String string);
+
+   /**
     * Returns a <em>copy</em> of the message body as a HornetQBuffer. Any modification
     * of this buffer should not impact the underlying buffer.
     */

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfiguration.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfiguration.java
index 86d2c4f..2f06fb8 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfiguration.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfiguration.java
@@ -17,6 +17,7 @@ import java.util.HashMap;
 import java.util.Map;
 
 import org.hornetq.core.client.HornetQClientMessageBundle;
+import org.hornetq.core.remoting.impl.TransportConfigurationUtil;
 import org.hornetq.core.remoting.impl.netty.TransportConstants;
 import org.hornetq.utils.UUIDGenerator;
 
@@ -81,6 +82,7 @@ public class TransportConfiguration implements Serializable
     */
    public TransportConfiguration()
    {
+      this.params = new HashMap<>();
    }
 
    /**
@@ -95,7 +97,14 @@ public class TransportConfiguration implements Serializable
    {
       factoryClassName = className;
 
-      this.params = params;
+      if (params == null || params.isEmpty())
+      {
+         this.params = TransportConfigurationUtil.getDefaults(className);
+      }
+      else
+      {
+         this.params = params;
+      }
 
       this.name = name;
    }
@@ -402,4 +411,4 @@ public class TransportConfiguration implements Serializable
    {
       return str.replace('.', '-');
    }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfigurationHelper.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfigurationHelper.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfigurationHelper.java
new file mode 100644
index 0000000..9a9565b
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/TransportConfigurationHelper.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.api.core;
+
+import java.util.Map;
+
+/**
+ * Helper interface for specifying default parameters on Transport Configurations.
+ *
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
+ */
+public interface TransportConfigurationHelper
+{
+   Map<String, Object> getDefaults();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/UDPBroadcastGroupConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/UDPBroadcastGroupConfiguration.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/UDPBroadcastGroupConfiguration.java
index 8ddd627..73deb9a 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/UDPBroadcastGroupConfiguration.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/UDPBroadcastGroupConfiguration.java
@@ -20,7 +20,6 @@ import java.net.Inet4Address;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.MulticastSocket;
-import java.net.UnknownHostException;
 import java.util.concurrent.TimeUnit;
 
 import org.hornetq.core.client.HornetQClientLogger;
@@ -37,23 +36,16 @@ public final class UDPBroadcastGroupConfiguration implements BroadcastEndpointFa
 {
    private static final long serialVersionUID = 1052413739064253955L;
 
-   private final transient String localBindAddress;
+   private transient String localBindAddress = null;
 
-   private final transient int localBindPort;
+   private transient int localBindPort = -1;
 
-   private final String groupAddress;
+   private String groupAddress = null;
 
-   private final int groupPort;
+   private int groupPort = -1;
 
-   public UDPBroadcastGroupConfiguration(final String groupAddress,
-                                         final int groupPort,
-                                         final String localBindAddress,
-                                         final int localBindPort)
+   public UDPBroadcastGroupConfiguration()
    {
-      this.groupAddress = groupAddress;
-      this.groupPort = groupPort;
-      this.localBindAddress = localBindAddress;
-      this.localBindPort = localBindPort;
    }
 
    public BroadcastEndpointFactory createBroadcastEndpointFactory()
@@ -63,10 +55,11 @@ public final class UDPBroadcastGroupConfiguration implements BroadcastEndpointFa
          @Override
          public BroadcastEndpoint createBroadcastEndpoint() throws Exception
          {
-            return new UDPBroadcastEndpoint(groupAddress != null ? InetAddress.getByName(groupAddress) : null,
-                                            groupPort,
-                                            localBindAddress != null ? InetAddress.getByName(localBindAddress) : null,
-                                            localBindPort);
+            return new UDPBroadcastEndpoint()
+               .setGroupAddress(groupAddress != null ? InetAddress.getByName(groupAddress) : null)
+               .setGroupPort(groupPort)
+               .setLocalBindAddress(localBindAddress != null ? InetAddress.getByName(localBindAddress) : null)
+               .setLocalBindPort(localBindPort);
          }
       };
    }
@@ -76,21 +69,45 @@ public final class UDPBroadcastGroupConfiguration implements BroadcastEndpointFa
       return groupAddress;
    }
 
+   public UDPBroadcastGroupConfiguration setGroupAddress(String groupAddress)
+   {
+      this.groupAddress = groupAddress;
+      return this;
+   }
+
    public int getGroupPort()
    {
       return groupPort;
    }
 
+   public UDPBroadcastGroupConfiguration setGroupPort(int groupPort)
+   {
+      this.groupPort = groupPort;
+      return this;
+   }
+
    public int getLocalBindPort()
    {
       return localBindPort;
    }
 
+   public UDPBroadcastGroupConfiguration setLocalBindPort(int localBindPort)
+   {
+      this.localBindPort = localBindPort;
+      return this;
+   }
+
    public String getLocalBindAddress()
    {
       return localBindAddress;
    }
 
+   public UDPBroadcastGroupConfiguration setLocalBindAddress(String localBindAddress)
+   {
+      this.localBindAddress = localBindAddress;
+      return this;
+   }
+
    /**
     * <p> This is the member discovery implementation using direct UDP. It was extracted as a refactoring from
     * {@link org.hornetq.core.cluster.DiscoveryGroup}</p>
@@ -103,13 +120,13 @@ public final class UDPBroadcastGroupConfiguration implements BroadcastEndpointFa
    {
       private static final int SOCKET_TIMEOUT = 500;
 
-      private final InetAddress localAddress;
+      private InetAddress localAddress;
 
-      private final int localBindPort;
+      private int localBindPort;
 
-      private final InetAddress groupAddress;
+      private InetAddress groupAddress;
 
-      private final int groupPort;
+      private int groupPort;
 
       private DatagramSocket broadcastingSocket;
 
@@ -117,15 +134,32 @@ public final class UDPBroadcastGroupConfiguration implements BroadcastEndpointFa
 
       private volatile boolean open;
 
-      public UDPBroadcastEndpoint(final InetAddress groupAddress,
-                                  final int groupPort,
-                                  final InetAddress localBindAddress,
-                                  final int localBindPort) throws UnknownHostException
+      public UDPBroadcastEndpoint()
+      {
+      }
+
+      public UDPBroadcastEndpoint setGroupAddress(InetAddress groupAddress)
       {
          this.groupAddress = groupAddress;
+         return this;
+      }
+
+      public UDPBroadcastEndpoint setGroupPort(int groupPort)
+      {
          this.groupPort = groupPort;
-         this.localAddress = localBindAddress;
+         return this;
+      }
+
+      public UDPBroadcastEndpoint setLocalBindAddress(InetAddress localAddress)
+      {
+         this.localAddress = localAddress;
+         return this;
+      }
+
+      public UDPBroadcastEndpoint setLocalBindPort(int localBindPort)
+      {
          this.localBindPort = localBindPort;
+         return this;
       }
 
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientConsumer.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientConsumer.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientConsumer.java
index 3f60863..06e3f56 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientConsumer.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientConsumer.java
@@ -13,6 +13,7 @@
 package org.hornetq.api.core.client;
 
 import org.hornetq.api.core.HornetQException;
+import org.hornetq.spi.core.remoting.ConsumerContext;
 
 /**
  * A ClientConsumer receives messages from HornetQ queues.
@@ -38,7 +39,7 @@ public interface ClientConsumer extends AutoCloseable
     * HornetQ implements this as a long but this could be protocol dependent.
     * @return
     */
-   Object getId();
+   ConsumerContext getConsumerContext();
 
    /**
     * Receives a message from a queue.
@@ -95,7 +96,7 @@ public interface ClientConsumer extends AutoCloseable
     * @param handler a MessageHandler
     * @throws HornetQException if an exception occurs while setting the MessageHandler
     */
-   void setMessageHandler(MessageHandler handler) throws HornetQException;
+   ClientConsumer setMessageHandler(MessageHandler handler) throws HornetQException;
 
    /**
     * Closes the consumer.

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientMessage.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientMessage.java
index 7903e0e..1a23af3 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientMessage.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientMessage.java
@@ -17,6 +17,7 @@ import java.io.OutputStream;
 
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Message;
+import org.hornetq.api.core.SimpleString;
 
 /**
  *
@@ -38,8 +39,9 @@ public interface ClientMessage extends Message
     * <p>
     * This method is not meant to be called by HornetQ clients.
     * @param deliveryCount message delivery count
+    * @return this ClientMessage
     */
-   void setDeliveryCount(int deliveryCount);
+   ClientMessage setDeliveryCount(int deliveryCount);
 
    /**
     * Acknowledges reception of this message.
@@ -50,7 +52,7 @@ public interface ClientMessage extends Message
     * @throws HornetQException if an error occurred while acknowledging the message.
     * @see ClientSession#isAutoCommitAcks()
     */
-   void acknowledge() throws HornetQException;
+   ClientMessage acknowledge() throws HornetQException;
 
    /**
     * Acknowledges reception of a single message.
@@ -61,7 +63,7 @@ public interface ClientMessage extends Message
     * @throws HornetQException if an error occurred while acknowledging the message.
     * @see ClientSession#isAutoCommitAcks()
     */
-   void individualAcknowledge() throws HornetQException;
+   ClientMessage individualAcknowledge() throws HornetQException;
 
    /**
     * This can be optionally used to verify if the entire message has been received.
@@ -84,8 +86,9 @@ public interface ClientMessage extends Message
     * This method is used when consuming large messages
     *
     * @throws HornetQException
+    * @return this ClientMessage
     */
-   void setOutputStream(OutputStream out) throws HornetQException;
+   ClientMessage setOutputStream(OutputStream out) throws HornetQException;
 
    /**
     * Saves the content of the message to the OutputStream.
@@ -111,7 +114,119 @@ public interface ClientMessage extends Message
     * Sets the body's IntputStream.
     * <br>
     * This method is used when sending large messages
+    * @return this ClientMessage
     */
-   void setBodyInputStream(InputStream bodyInputStream);
+   ClientMessage setBodyInputStream(InputStream bodyInputStream);
+
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putBooleanProperty(SimpleString key, boolean value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putBooleanProperty(String key, boolean value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putByteProperty(SimpleString key, byte value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putByteProperty(String key, byte value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putBytesProperty(SimpleString key, byte[] value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putBytesProperty(String key, byte[] value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putShortProperty(SimpleString key, short value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putShortProperty(String key, short value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putCharProperty(SimpleString key, char value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putCharProperty(String key, char value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putIntProperty(SimpleString key, int value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putIntProperty(String key, int value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putLongProperty(SimpleString key, long value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putLongProperty(String key, long value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putFloatProperty(SimpleString key, float value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putFloatProperty(String key, float value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putDoubleProperty(SimpleString key, double value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putDoubleProperty(String key, double value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putStringProperty(SimpleString key, SimpleString value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage putStringProperty(String key, String value);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage writeBodyBufferBytes(byte[] bytes);
+
+   /**
+    * Overridden from {@link org.hornetq.api.core.Message} to enable fluent API
+    */
+   ClientMessage writeBodyBufferString(String string);
 
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSession.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSession.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSession.java
index cb56d0a..b55c9e1 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSession.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSession.java
@@ -113,7 +113,7 @@ public interface ClientSession extends XAResource, AutoCloseable
     *
     * @throws HornetQException if an exception occurs while starting the session
     */
-   void start() throws HornetQException;
+   ClientSession start() throws HornetQException;
 
    /**
     * Stops the session.
@@ -642,8 +642,9 @@ public interface ClientSession extends XAResource, AutoCloseable
     * Sets a <code>SendAcknowledgementHandler</code> for this session.
     *
     * @param handler a SendAcknowledgementHandler
+    * @return this ClientSession
     */
-   void setSendAcknowledgementHandler(SendAcknowledgementHandler handler);
+   ClientSession setSendAcknowledgementHandler(SendAcknowledgementHandler handler);
 
    /**
     * Attach any metadata to the session.

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSessionFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSessionFactory.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSessionFactory.java
index f6936b5..4c2d98c 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSessionFactory.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ClientSessionFactory.java
@@ -144,8 +144,9 @@ public interface ClientSessionFactory extends AutoCloseable
     * Adds a FailoverEventListener to the session which is notified if a failover event  occurs on the session.
     *
     * @param listener the listener to add
+    * @return this ClientSessionFactory
     */
-   void addFailoverListener(FailoverEventListener listener);
+   ClientSessionFactory addFailoverListener(FailoverEventListener listener);
 
    /**
     * Removes a FailoverEventListener to the session.

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ServerLocator.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ServerLocator.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ServerLocator.java
index 01a830a..eb2efa8 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ServerLocator.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/client/ServerLocator.java
@@ -16,6 +16,7 @@ import org.hornetq.api.core.DiscoveryGroupConfiguration;
 import org.hornetq.api.core.Interceptor;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.client.impl.Topology;
+import org.hornetq.spi.core.remoting.ClientProtocolManagerFactory;
 
 /**
  * The serverLocator locates a server, but beyond that it locates a server based on a list.
@@ -24,7 +25,7 @@ import org.hornetq.core.client.impl.Topology;
  * HA, the locator will always get an updated list of members to the server, the server will send
  * the updated list to the client.
  * <p>
- * If you use UDP or JGroups (exclusively JGropus or UDP), the initial discovery is done by the
+ * If you use UDP or JGroups (exclusively JGroups or UDP), the initial discovery is done by the
  * grouping finder, after the initial connection is made the server will always send updates to the
  * client. But the listeners will listen for updates on grouping.
  *
@@ -114,8 +115,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be -1 (to disable) or greater than 0.
     *
     * @param clientFailureCheckPeriod the period to check failure
+    * @return this ServerLocator
     */
-   void setClientFailureCheckPeriod(long clientFailureCheckPeriod);
+   ServerLocator setClientFailureCheckPeriod(long clientFailureCheckPeriod);
 
    /**
     * When <code>true</code>, consumers created through this factory will create temporary files to
@@ -134,8 +136,9 @@ public interface ServerLocator extends AutoCloseable
     * Sets whether large messages received by consumers created through this factory will be cached in temporary files or not.
     *
     * @param cached <code>true</code> to cache large messages in temporary files, <code>false</code> else
+    * @return this ServerLocator
     */
-   void setCacheLargeMessagesClient(boolean cached);
+   ServerLocator setCacheLargeMessagesClient(boolean cached);
 
    /**
     * Returns the connection <em>time-to-live</em>.
@@ -154,14 +157,15 @@ public interface ServerLocator extends AutoCloseable
     * Value must be -1 (to disable) or greater or equals to 0.
     *
     * @param connectionTTL period in milliseconds
+    * @return this ServerLocator
     */
-   void setConnectionTTL(long connectionTTL);
+   ServerLocator setConnectionTTL(long connectionTTL);
 
    /**
     * Returns the blocking calls timeout.
     * <p>
     * If client's blocking calls to the server take more than this timeout, the call will throw a
-    * {@link HornetQException} with the code {@link HornetQExceptionType#CONNECTION_TIMEDOUT}. Value
+    * {@link org.hornetq.api.core.HornetQException} with the code {@link org.hornetq.api.core.HornetQExceptionType#CONNECTION_TIMEDOUT}. Value
     * is in milliseconds, default value is {@link HornetQClient#DEFAULT_CALL_TIMEOUT}.
     *
     * @return the blocking calls timeout
@@ -174,8 +178,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be greater or equals to 0
     *
     * @param callTimeout blocking call timeout in milliseconds
+    * @return this ServerLocator
     */
-   void setCallTimeout(long callTimeout);
+   ServerLocator setCallTimeout(long callTimeout);
 
 
    /**
@@ -197,8 +202,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be greater or equals to -1, -1 means forever
     *
     * @param callFailoverTimeout blocking call timeout in milliseconds
+    * @return this ServerLocator
     */
-   void setCallFailoverTimeout(long callFailoverTimeout);
+   ServerLocator setCallFailoverTimeout(long callFailoverTimeout);
 
    /**
     * Returns the large message size threshold.
@@ -216,8 +222,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be greater than 0.
     *
     * @param minLargeMessageSize large message size threshold in bytes
+    * @return this ServerLocator
     */
-   void setMinLargeMessageSize(int minLargeMessageSize);
+   ServerLocator setMinLargeMessageSize(int minLargeMessageSize);
 
    /**
     * Returns the window size for flow control of the consumers created through this factory.
@@ -235,8 +242,9 @@ public interface ServerLocator extends AutoCloseable
     * (to set the maximum size of the buffer)
     *
     * @param consumerWindowSize window size (in bytes) used for consumer flow control
+    * @return this ServerLocator
     */
-   void setConsumerWindowSize(int consumerWindowSize);
+   ServerLocator setConsumerWindowSize(int consumerWindowSize);
 
    /**
     * Returns the maximum rate of message consumption for consumers created through this factory.
@@ -256,8 +264,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must -1 (to disable) or a positive integer corresponding to the maximum desired message consumption rate specified in units of messages per second.
     *
     * @param consumerMaxRate maximum rate of message consumption (in messages per seconds)
+    * @return this ServerLocator
     */
-   void setConsumerMaxRate(int consumerMaxRate);
+   ServerLocator setConsumerMaxRate(int consumerMaxRate);
 
    /**
     * Returns the size for the confirmation window of clients using this factory.
@@ -275,8 +284,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be -1 (to disable the window) or greater than 0.
     *
     * @param confirmationWindowSize size of the confirmation window (in bytes)
+    * @return this ServerLocator
     */
-   void setConfirmationWindowSize(int confirmationWindowSize);
+   ServerLocator setConfirmationWindowSize(int confirmationWindowSize);
 
    /**
     * Returns the window size for flow control of the producers created through this factory.
@@ -294,8 +304,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be -1 (to disable flow control) or greater than 0.
     *
     * @param producerWindowSize window size (in bytest) for flow control of the producers created through this factory.
+    * @return this ServerLocator
     */
-   void setProducerWindowSize(int producerWindowSize);
+   ServerLocator setProducerWindowSize(int producerWindowSize);
 
    /**
     * Returns the maximum rate of message production for producers created through this factory.
@@ -315,8 +326,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must -1 (to disable) or a positive integer corresponding to the maximum desired message production rate specified in units of messages per second.
     *
     * @param producerMaxRate maximum rate of message production (in messages per seconds)
+    * @return this ServerLocator
     */
-   void setProducerMaxRate(int producerMaxRate);
+   ServerLocator setProducerMaxRate(int producerMaxRate);
 
    /**
     * Returns whether consumers created through this factory will block while
@@ -336,8 +348,9 @@ public interface ServerLocator extends AutoCloseable
     * @param blockOnAcknowledge <code>true</code> to block when sending message
     *                           acknowledgments or <code>false</code> to send them
     *                           asynchronously
+    * @return this ServerLocator
     */
-   void setBlockOnAcknowledge(boolean blockOnAcknowledge);
+   ServerLocator setBlockOnAcknowledge(boolean blockOnAcknowledge);
 
    /**
     * Returns whether producers created through this factory will block while sending <em>durable</em> messages or do it asynchronously.
@@ -355,8 +368,9 @@ public interface ServerLocator extends AutoCloseable
     * Sets whether producers created through this factory will block while sending <em>durable</em> messages or do it asynchronously.
     *
     * @param blockOnDurableSend <code>true</code> to block when sending durable messages or <code>false</code> to send them asynchronously
+    * @return this ServerLocator
     */
-   void setBlockOnDurableSend(boolean blockOnDurableSend);
+   ServerLocator setBlockOnDurableSend(boolean blockOnDurableSend);
 
    /**
     * Returns whether producers created through this factory will block while sending <em>non-durable</em> messages or do it asynchronously.
@@ -374,8 +388,9 @@ public interface ServerLocator extends AutoCloseable
     * Sets whether producers created through this factory will block while sending <em>non-durable</em> messages or do it asynchronously.
     *
     * @param blockOnNonDurableSend <code>true</code> to block when sending non-durable messages or <code>false</code> to send them asynchronously
+    * @return this ServerLocator
     */
-   void setBlockOnNonDurableSend(boolean blockOnNonDurableSend);
+   ServerLocator setBlockOnNonDurableSend(boolean blockOnNonDurableSend);
 
    /**
     * Returns whether producers created through this factory will automatically
@@ -394,8 +409,9 @@ public interface ServerLocator extends AutoCloseable
     * assign a group ID to the messages they sent.
     *
     * @param autoGroup <code>true</code> to automatically assign a group ID to each messages sent through this factory, <code>false</code> else
+    * @return this ServerLocator
     */
-   void setAutoGroup(boolean autoGroup);
+   ServerLocator setAutoGroup(boolean autoGroup);
 
    /**
     * Returns the group ID that will be eventually set on each message for the property {@link org.hornetq.api.core.Message#HDR_GROUP_ID}.
@@ -410,8 +426,9 @@ public interface ServerLocator extends AutoCloseable
     * Sets the group ID that will be  set on each message sent through this factory.
     *
     * @param groupID the group ID to use
+    * @return this ServerLocator
     */
-   void setGroupID(String groupID);
+   ServerLocator setGroupID(String groupID);
 
    /**
     * Returns whether messages will pre-acknowledged on the server before they are sent to the consumers or not.
@@ -427,8 +444,9 @@ public interface ServerLocator extends AutoCloseable
     *
     * @param preAcknowledge <code>true</code> to enable pre-acknowledgment,
     *                       <code>false</code> else
+    * @return this ServerLocator
     */
-   void setPreAcknowledge(boolean preAcknowledge);
+   ServerLocator setPreAcknowledge(boolean preAcknowledge);
 
    /**
     * Returns the acknowledgments batch size.
@@ -445,8 +463,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be equal or greater than 0.
     *
     * @param ackBatchSize acknowledgments batch size
+    * @return this ServerLocator
     */
-   void setAckBatchSize(int ackBatchSize);
+   ServerLocator setAckBatchSize(int ackBatchSize);
 
    /**
     * Returns an array of TransportConfigurations representing the static list of live servers used
@@ -476,8 +495,9 @@ public interface ServerLocator extends AutoCloseable
     * or its own pools.
     *
     * @param useGlobalPools <code>true</code> to let this factory uses global thread pools, <code>false</code> else
+    * @return this ServerLocator
     */
-   void setUseGlobalPools(boolean useGlobalPools);
+   ServerLocator setUseGlobalPools(boolean useGlobalPools);
 
    /**
     * Returns the maximum size of the scheduled thread pool.
@@ -495,8 +515,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be greater than 0.
     *
     * @param scheduledThreadPoolMaxSize maximum size of the scheduled thread pool.
+    * @return this ServerLocator
     */
-   void setScheduledThreadPoolMaxSize(int scheduledThreadPoolMaxSize);
+   ServerLocator setScheduledThreadPoolMaxSize(int scheduledThreadPoolMaxSize);
 
    /**
     * Returns the maximum size of the thread pool.
@@ -514,8 +535,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be -1 (for unlimited thread pool) or greater than 0.
     *
     * @param threadPoolMaxSize maximum size of the thread pool.
+    * @return this ServerLocator
     */
-   void setThreadPoolMaxSize(int threadPoolMaxSize);
+   ServerLocator setThreadPoolMaxSize(int threadPoolMaxSize);
 
    /**
     * Returns the time to retry connections created by this factory after failure.
@@ -532,8 +554,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be greater than 0.
     *
     * @param retryInterval time (in milliseconds) to retry connections created by this factory after failure
+    * @return this ServerLocator
     */
-   void setRetryInterval(long retryInterval);
+   ServerLocator setRetryInterval(long retryInterval);
 
    /**
     * Returns the multiplier to apply to successive retry intervals.
@@ -550,8 +573,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be positive.
     *
     * @param retryIntervalMultiplier multiplier to apply to successive retry intervals
+    * @return this ServerLocator
     */
-   void setRetryIntervalMultiplier(double retryIntervalMultiplier);
+   ServerLocator setRetryIntervalMultiplier(double retryIntervalMultiplier);
 
    /**
     * Returns the maximum retry interval (in the case a retry interval multiplier has been specified).
@@ -569,8 +593,9 @@ public interface ServerLocator extends AutoCloseable
     *
     * @param maxRetryInterval maximum retry interval to apply in the case a retry interval multiplier
     *                         has been specified
+    * @return this ServerLocator
     */
-   void setMaxRetryInterval(long maxRetryInterval);
+   ServerLocator setMaxRetryInterval(long maxRetryInterval);
 
    /**
     * Returns the maximum number of attempts to retry connection in case of failure.
@@ -587,8 +612,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be -1 (to retry infinitely), 0 (to never retry connection) or greater than 0.
     *
     * @param reconnectAttempts maximum number of attempts to retry connection in case of failure
+    * @return this ServerLocator
     */
-   void setReconnectAttempts(int reconnectAttempts);
+   ServerLocator setReconnectAttempts(int reconnectAttempts);
 
    /**
     * Sets the maximum number of attempts to establish an initial connection.
@@ -596,8 +622,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be -1 (to retry infinitely), 0 (to never retry connection) or greater than 0.
     *
     * @param reconnectAttempts maximum number of attempts for the initial connection
+    * @return this ServerLocator
     */
-   void setInitialConnectAttempts(int reconnectAttempts);
+   ServerLocator setInitialConnectAttempts(int reconnectAttempts);
 
    /**
     * @return the number of attempts to be made for first initial connection.
@@ -616,8 +643,9 @@ public interface ServerLocator extends AutoCloseable
     * Sets the value for FailoverOnInitialReconnection
     *
     * @param failover
+    * @return this ServerLocator
     */
-   void setFailoverOnInitialConnection(boolean failover);
+   ServerLocator setFailoverOnInitialConnection(boolean failover);
 
    /**
     * Returns the class name of the connection load balancing policy.
@@ -631,11 +659,12 @@ public interface ServerLocator extends AutoCloseable
    /**
     * Sets the class name of the connection load balancing policy.
     * <p>
-    * Value must be the name of a class implementing {@link ConnectionLoadBalancingPolicy}.
+    * Value must be the name of a class implementing {@link org.hornetq.api.core.client.loadbalance.ConnectionLoadBalancingPolicy}.
     *
     * @param loadBalancingPolicyClassName class name of the connection load balancing policy
+    * @return this ServerLocator
     */
-   void setConnectionLoadBalancingPolicyClassName(String loadBalancingPolicyClassName);
+   ServerLocator setConnectionLoadBalancingPolicyClassName(String loadBalancingPolicyClassName);
 
    /**
     * Returns the initial size of messages created through this factory.
@@ -652,8 +681,9 @@ public interface ServerLocator extends AutoCloseable
     * Value must be greater than 0.
     *
     * @param size initial size of messages created through this factory.
+    * @return this ServerLocator
     */
-   void setInitialMessagePacketSize(int size);
+   ServerLocator setInitialMessagePacketSize(int size);
 
    /**
     * Adds an interceptor which will be executed <em>after packets are received from the server</em>. Invoking this
@@ -671,15 +701,17 @@ public interface ServerLocator extends AutoCloseable
     * Adds an interceptor which will be executed <em>after packets are received from the server</em>.
     *
     * @param interceptor an Interceptor
+    * @return this ServerLocator
     */
-   void addIncomingInterceptor(Interceptor interceptor);
+   ServerLocator addIncomingInterceptor(Interceptor interceptor);
 
    /**
     * Adds an interceptor which will be executed <em>before packets are sent to the server</em>.
     *
     * @param interceptor an Interceptor
+    * @return this ServerLocator
     */
-   void addOutgoingInterceptor(Interceptor interceptor);
+   ServerLocator addOutgoingInterceptor(Interceptor interceptor);
 
    /**
     * Removes an interceptor. Invoking this method is the same as invoking
@@ -741,12 +773,18 @@ public interface ServerLocator extends AutoCloseable
     * Sets whether to compress or not large messages.
     *
     * @param compressLargeMessages
+    * @return this ServerLocator
     */
-   void setCompressLargeMessage(boolean compressLargeMessages);
+   ServerLocator setCompressLargeMessage(boolean compressLargeMessages);
 
    // XXX No javadocs
-   void addClusterTopologyListener(ClusterTopologyListener listener);
+   ServerLocator addClusterTopologyListener(ClusterTopologyListener listener);
 
    // XXX No javadocs
    void removeClusterTopologyListener(ClusterTopologyListener listener);
+
+   ClientProtocolManagerFactory getProtocolManagerFactory();
+
+   void setProtocolManagerFactory(ClientProtocolManagerFactory protocolManager);
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/management/AddressSettingsInfo.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/AddressSettingsInfo.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/AddressSettingsInfo.java
index 13cf953..cd06495 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/AddressSettingsInfo.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/AddressSettingsInfo.java
@@ -50,6 +50,12 @@ public final class AddressSettingsInfo
 
    private final boolean sendToDLAOnNoRoute;
 
+   private final long slowConsumerThreshold;
+
+   private final long slowConsumerCheckPeriod;
+
+   private final String slowConsumerPolicy;
+
    // Static --------------------------------------------------------
 
    public static AddressSettingsInfo from(final String jsonString) throws Exception
@@ -67,7 +73,10 @@ public final class AddressSettingsInfo
                                      object.getString("expiryAddress"),
                                      object.getBoolean("lastValueQueue"),
                                      object.getLong("redistributionDelay"),
-                                     object.getBoolean("sendToDLAOnNoRoute"));
+                                     object.getBoolean("sendToDLAOnNoRoute"),
+                                     object.getLong("slowConsumerThreshold"),
+                                     object.getLong("slowConsumerCheckPeriod"),
+                                     object.getString("slowConsumerPolicy"));
    }
 
    // Constructors --------------------------------------------------
@@ -84,7 +93,10 @@ public final class AddressSettingsInfo
                               String expiryAddress,
                               boolean lastValueQueue,
                               long redistributionDelay,
-                              boolean sendToDLAOnNoRoute)
+                              boolean sendToDLAOnNoRoute,
+                              long slowConsumerThreshold,
+                              long slowConsumerCheckPeriod,
+                              String slowConsumerPolicy)
    {
       this.addressFullMessagePolicy = addressFullMessagePolicy;
       this.maxSizeBytes = maxSizeBytes;
@@ -99,6 +111,9 @@ public final class AddressSettingsInfo
       this.lastValueQueue = lastValueQueue;
       this.redistributionDelay = redistributionDelay;
       this.sendToDLAOnNoRoute = sendToDLAOnNoRoute;
+      this.slowConsumerThreshold = slowConsumerThreshold;
+      this.slowConsumerCheckPeriod = slowConsumerCheckPeriod;
+      this.slowConsumerPolicy = slowConsumerPolicy;
    }
 
    // Public --------------------------------------------------------
@@ -172,5 +187,20 @@ public final class AddressSettingsInfo
    {
       return maxRedeliveryDelay;
    }
+
+   public long getSlowConsumerThreshold()
+   {
+      return slowConsumerThreshold;
+   }
+
+   public long getSlowConsumerCheckPeriod()
+   {
+      return slowConsumerCheckPeriod;
+   }
+
+   public String getSlowConsumerPolicy()
+   {
+      return slowConsumerPolicy;
+   }
 }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/management/CoreNotificationType.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/CoreNotificationType.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/CoreNotificationType.java
new file mode 100644
index 0000000..d792a9a
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/CoreNotificationType.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.api.core.management;
+
+/**
+ * This enum defines all core notification types
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ */
+public enum CoreNotificationType implements NotificationType
+{
+   BINDING_ADDED(0),
+   BINDING_REMOVED(1),
+   CONSUMER_CREATED(2),
+   CONSUMER_CLOSED(3),
+   SECURITY_AUTHENTICATION_VIOLATION(6),
+   SECURITY_PERMISSION_VIOLATION(7),
+   DISCOVERY_GROUP_STARTED(8),
+   DISCOVERY_GROUP_STOPPED(9),
+   BROADCAST_GROUP_STARTED(10),
+   BROADCAST_GROUP_STOPPED(11),
+   BRIDGE_STARTED(12),
+   BRIDGE_STOPPED(13),
+   CLUSTER_CONNECTION_STARTED(14),
+   CLUSTER_CONNECTION_STOPPED(15),
+   ACCEPTOR_STARTED(16),
+   ACCEPTOR_STOPPED(17),
+   PROPOSAL(18),
+   PROPOSAL_RESPONSE(19),
+   UNPROPOSAL(20),
+   CONSUMER_SLOW(21);
+
+   private final int value;
+
+   private CoreNotificationType(final int value)
+   {
+      this.value = value;
+   }
+
+   public int getType()
+   {
+      return value;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/management/HornetQServerControl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/HornetQServerControl.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/HornetQServerControl.java
index 0d7deca..ca566f7 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/HornetQServerControl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/HornetQServerControl.java
@@ -38,7 +38,7 @@ public interface HornetQServerControl
     * Returns the list of interceptors used by this server. Invoking this method is the same as invoking
     * <code>getIncomingInterceptorClassNames().</code>
     *
-    * @see Interceptor
+    * @see org.hornetq.api.core.Interceptor
     * @deprecated As of HornetQ 2.3.0.Final, replaced by
     * {@link #getIncomingInterceptorClassNames()} and
     * {@link #getOutgoingInterceptorClassNames()}
@@ -49,14 +49,14 @@ public interface HornetQServerControl
    /**
     * Returns the list of interceptors used by this server for incoming messages.
     *
-    * @see Interceptor
+    * @see org.hornetq.api.core.Interceptor
     */
    String[] getIncomingInterceptorClassNames();
 
    /**
     * Returns the list of interceptors used by this server for outgoing messages.
     *
-    * @see Interceptor
+    * @see org.hornetq.api.core.Interceptor
     */
    String[] getOutgoingInterceptorClassNames();
 
@@ -490,6 +490,18 @@ public interface HornetQServerControl
    boolean closeConnectionsForAddress(@Parameter(desc = "an IP address", name = "ipAddress") String ipAddress) throws Exception;
 
    /**
+    * Closes all the connections of clients connected to this server which matches the specified IP address.
+    */
+   @Operation(desc = "Closes all the consumer connections for the given HornetQ address", impact = MBeanOperationInfo.INFO)
+   boolean closeConsumerConnectionsForAddress(@Parameter(desc = "a HornetQ address", name = "address") String address) throws Exception;
+
+   /**
+    * Closes all the connections of sessions with a matching user name.
+    */
+   @Operation(desc = "Closes all the connections for sessions with the given user name", impact = MBeanOperationInfo.INFO)
+   boolean closeConnectionsForUser(@Parameter(desc = "a user name", name = "userName") String address) throws Exception;
+
+   /**
     * Lists all the IDs of the connections connected to this server.
     */
    @Operation(desc = "List all the connection IDs", impact = MBeanOperationInfo.INFO)
@@ -546,7 +558,10 @@ public interface HornetQServerControl
                            @Parameter(desc = "the maximum redelivery delay", name = "maxRedeliveryDelay") long maxRedeliveryDelay,
                            @Parameter(desc = "the redistribution delay", name = "redistributionDelay") long redistributionDelay,
                            @Parameter(desc = "do we send to the DLA when there is no where to route the message", name = "sendToDLAOnNoRoute") boolean sendToDLAOnNoRoute,
-                           @Parameter(desc = "the ploicy to use when the address is full", name = "addressFullMessagePolicy") String addressFullMessagePolicy) throws Exception;
+                           @Parameter(desc = "the policy to use when the address is full", name = "addressFullMessagePolicy") String addressFullMessagePolicy,
+                           @Parameter(desc = "when a consumer falls below this threshold in terms of messages consumed per second it will be considered 'slow'", name = "slowConsumerThreshold") long slowConsumerThreshold,
+                           @Parameter(desc = "how often (in seconds) to check for slow consumers", name = "slowConsumerCheckPeriod") long slowConsumerCheckPeriod,
+                           @Parameter(desc = "the policy to use when a slow consumer is detected", name = "slowConsumerPolicy") String slowConsumerPolicy) throws Exception;
 
    void removeAddressSettings(String addressMatch) throws Exception;
 
@@ -599,5 +614,8 @@ public interface HornetQServerControl
    void forceFailover() throws Exception;
 
    void updateDuplicateIdCache(String address, Object[] ids) throws Exception;
+
+   @Operation(desc = "force the server to stop and to scale down to another server", impact = MBeanOperationInfo.UNKNOWN)
+   void scaleDown(@Parameter(name = "name", desc = "The connector to use to scale down, if not provided the first appropriate connector will be used")String connector) throws Exception;
 }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ManagementHelper.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ManagementHelper.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ManagementHelper.java
index ffda2df..bacae4d 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ManagementHelper.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ManagementHelper.java
@@ -75,6 +75,10 @@ public final class ManagementHelper
 
    public static final SimpleString HDR_PROPOSAL_ALT_VALUE = new SimpleString("_JBM_ProposalAltValue");
 
+   public static final SimpleString HDR_CONSUMER_NAME = new SimpleString("_HQ_ConsumerName");
+
+   public static final SimpleString HDR_CONNECTION_NAME = new SimpleString("_HQ_ConnectionName");
+
    // Attributes ----------------------------------------------------
 
    // Static --------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/management/NotificationType.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/NotificationType.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/NotificationType.java
index 2ec5dd3..ecabae7 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/NotificationType.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/NotificationType.java
@@ -24,37 +24,7 @@ package org.hornetq.api.core.management;
  * @see the HornetQ user manual section on "Management Notifications"
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  */
-public enum NotificationType
+public interface NotificationType
 {
-   BINDING_ADDED(0),
-   BINDING_REMOVED(1),
-   CONSUMER_CREATED(2),
-   CONSUMER_CLOSED(3),
-   SECURITY_AUTHENTICATION_VIOLATION(6),
-   SECURITY_PERMISSION_VIOLATION(7),
-   DISCOVERY_GROUP_STARTED(8),
-   DISCOVERY_GROUP_STOPPED(9),
-   BROADCAST_GROUP_STARTED(10),
-   BROADCAST_GROUP_STOPPED(11),
-   BRIDGE_STARTED(12),
-   BRIDGE_STOPPED(13),
-   CLUSTER_CONNECTION_STARTED(14),
-   CLUSTER_CONNECTION_STOPPED(15),
-   ACCEPTOR_STARTED(16),
-   ACCEPTOR_STOPPED(17),
-   PROPOSAL(18),
-   PROPOSAL_RESPONSE(19),
-   UNPROPOSAL(20);
-
-   private final int value;
-
-   private NotificationType(final int value)
-   {
-      this.value = value;
-   }
-
-   public int intValue()
-   {
-      return value;
-   }
+   int getType();
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ObjectNameBuilder.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ObjectNameBuilder.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ObjectNameBuilder.java
index 0c43dad..4994902 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ObjectNameBuilder.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/ObjectNameBuilder.java
@@ -23,6 +23,7 @@ import org.hornetq.api.core.SimpleString;
  */
 public final class ObjectNameBuilder
 {
+
    // Constants -----------------------------------------------------
 
    /**
@@ -30,14 +31,13 @@ public final class ObjectNameBuilder
     */
    public static final ObjectNameBuilder DEFAULT = new ObjectNameBuilder(HornetQDefaultConfiguration.getDefaultJmxDomain());
 
-   static final String DEFAULT_SUBSYSTEM = "messaging";
-   static final String DEFAULT_SERVER = "default";
+   static final String JMS_MODULE = "JMS";
+
+   static final String CORE_MODULE = "Core";
 
    // Attributes ----------------------------------------------------
 
    private final String domain;
-   private final String subsystem;
-   private final String serverName;
 
    // Static --------------------------------------------------------
 
@@ -58,8 +58,6 @@ public final class ObjectNameBuilder
    private ObjectNameBuilder(final String domain)
    {
       this.domain = domain;
-      this.subsystem = DEFAULT_SUBSYSTEM;
-      this.serverName = DEFAULT_SERVER;
    }
 
    // Public --------------------------------------------------------
@@ -69,9 +67,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getHornetQServerObjectName() throws Exception
    {
-      String value = String.format("%s:subsystem=%s,hornetq-server=%s",
-            domain, subsystem, serverName);
-      return ObjectName.getInstance(value);
+      return ObjectName.getInstance(domain + ":module=Core,type=Server");
    }
 
    /**
@@ -81,7 +77,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getAddressObjectName(final SimpleString address) throws Exception
    {
-      return createObjectName("core-address", address.toString());
+      return createObjectName(ObjectNameBuilder.CORE_MODULE, "Address", address.toString());
    }
 
    /**
@@ -91,11 +87,12 @@ public final class ObjectNameBuilder
     */
    public ObjectName getQueueObjectName(final SimpleString address, final SimpleString name) throws Exception
    {
-      ObjectProperty[] props = new ObjectProperty[] {
-         new ObjectProperty("address", address.toString()),
-         new ObjectProperty("runtime-queue", name.toString())
-      };
-      return this.createObjectName(props);
+      return ObjectName.getInstance(String.format("%s:module=%s,type=%s,address=%s,name=%s",
+                                                  domain,
+                                                  ObjectNameBuilder.CORE_MODULE,
+                                                  "Queue",
+                                                  ObjectName.quote(address.toString()),
+                                                  ObjectName.quote(name.toString())));
    }
 
    /**
@@ -105,7 +102,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getDivertObjectName(final String name) throws Exception
    {
-      return createObjectName("divert", name.toString());
+      return createObjectName(ObjectNameBuilder.CORE_MODULE, "Divert", name.toString());
    }
 
    /**
@@ -115,7 +112,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getAcceptorObjectName(final String name) throws Exception
    {
-      return createObjectName("remote-acceptor", name);
+      return createObjectName(ObjectNameBuilder.CORE_MODULE, "Acceptor", name);
    }
 
    /**
@@ -125,7 +122,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getBroadcastGroupObjectName(final String name) throws Exception
    {
-      return createObjectName("broadcast-group", name);
+      return createObjectName(ObjectNameBuilder.CORE_MODULE, "BroadcastGroup", name);
    }
 
    /**
@@ -135,7 +132,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getBridgeObjectName(final String name) throws Exception
    {
-      return createObjectName("bridge", name);
+      return createObjectName(ObjectNameBuilder.CORE_MODULE, "Bridge", name);
    }
 
    /**
@@ -145,7 +142,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getClusterConnectionObjectName(final String name) throws Exception
    {
-      return createObjectName("cluster-connection", name);
+      return createObjectName(ObjectNameBuilder.CORE_MODULE, "ClusterConnection", name);
    }
 
    /**
@@ -155,7 +152,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getDiscoveryGroupObjectName(final String name) throws Exception
    {
-      return createObjectName("discovery-group", name);
+      return createObjectName(ObjectNameBuilder.CORE_MODULE, "DiscoveryGroup", name);
    }
 
    /**
@@ -164,9 +161,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getJMSServerObjectName() throws Exception
    {
-      String value = String.format("%s:subsystem=%s,hornetq-server=%s",
-            domain, subsystem, serverName);
-      return ObjectName.getInstance(value);
+      return ObjectName.getInstance(domain + ":module=JMS,type=Server");
    }
 
    /**
@@ -175,7 +170,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getJMSQueueObjectName(final String name) throws Exception
    {
-      return createObjectName("jms-queue", name);
+      return createObjectName(ObjectNameBuilder.JMS_MODULE, "Queue", name);
    }
 
    /**
@@ -185,7 +180,7 @@ public final class ObjectNameBuilder
     */
    public ObjectName getJMSTopicObjectName(final String name) throws Exception
    {
-      return createObjectName("jms-topic", name);
+      return createObjectName(ObjectNameBuilder.JMS_MODULE, "Topic", name);
    }
 
    /**
@@ -194,38 +189,15 @@ public final class ObjectNameBuilder
     */
    public ObjectName getConnectionFactoryObjectName(final String name) throws Exception
    {
-      return createObjectName("connection-factory", name);
+      return createObjectName(ObjectNameBuilder.JMS_MODULE, "ConnectionFactory", name);
    }
 
-   private ObjectName createObjectName(String beanType, String beanName) throws Exception
+   private ObjectName createObjectName(final String module, final String type, final String name) throws Exception
    {
-      return this.createObjectName(new ObjectProperty[] {new ObjectProperty(beanType, beanName)});
-   }
-
-   private ObjectName createObjectName(ObjectProperty[] props) throws Exception
-   {
-      String baseValue = String.format("%s:subsystem=%s,hornetq-server=%s",
-                                   domain, subsystem, serverName);
-      StringBuilder builder = new StringBuilder(baseValue);
-      for (ObjectProperty p : props)
-      {
-         builder.append(",");
-         builder.append(p.key);
-         builder.append("=");
-         builder.append(ObjectName.quote(p.val));
-      }
-      return ObjectName.getInstance(builder.toString());
-   }
-
-   private static class ObjectProperty
-   {
-      String key;
-      String val;
-
-      public ObjectProperty(String k, String v)
-      {
-         this.key = k;
-         this.val = v;
-      }
+      return ObjectName.getInstance(String.format("%s:module=%s,type=%s,name=%s",
+                                                  domain,
+                                                  module,
+                                                  type,
+                                                  ObjectName.quote(name)));
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/management/QueueControl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/QueueControl.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/QueueControl.java
index f2c6895..d63ea15 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/management/QueueControl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/management/QueueControl.java
@@ -81,6 +81,11 @@ public interface QueueControl
    long getMessagesAdded();
 
    /**
+    * Returns the number of messages added to this queue since it was created.
+    */
+   long getMessagesAcknowledged();
+
+   /**
     * Returns the first message on the queue as JSON
     */
    String getFirstMessageAsJSON() throws Exception;
@@ -356,4 +361,19 @@ public interface QueueControl
     */
    @Operation(desc = "Resets the MessagesAdded property", impact = MBeanOperationInfo.ACTION)
    void resetMessagesAdded() throws Exception;
+
+   /**
+    * Resets the MessagesAdded property
+    */
+   @Operation(desc = "Resets the MessagesAcknowledged property", impact = MBeanOperationInfo.ACTION)
+   void resetMessagesAcknowledged() throws Exception;
+
+   /**
+    * it will flush one cycle on internal executors, so you would be sure that any pending tasks are done before you call
+    * any other measure.
+    * It is useful if you need the exact number of counts on a message
+    * @throws Exception
+    */
+   void flushExecutor();
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/buffers/impl/ResetLimitWrappedHornetQBuffer.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/buffers/impl/ResetLimitWrappedHornetQBuffer.java b/hornetq-core-client/src/main/java/org/hornetq/core/buffers/impl/ResetLimitWrappedHornetQBuffer.java
index a279096..9eae62e 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/buffers/impl/ResetLimitWrappedHornetQBuffer.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/buffers/impl/ResetLimitWrappedHornetQBuffer.java
@@ -28,7 +28,17 @@ public final class ResetLimitWrappedHornetQBuffer extends ChannelBufferWrapper
 {
    private final int limit;
 
-   private final MessageInternal message;
+   private MessageInternal message;
+
+   /**
+    * We need to turn of notifications of body changes on reset on the server side when dealing with AMQP conversions,
+    * for that reason this method will set the message to null here
+    * @param message
+    */
+   public void setMessage(MessageInternal message)
+   {
+      this.message = message;
+   }
 
    public ResetLimitWrappedHornetQBuffer(final int limit, final HornetQBuffer buffer, final MessageInternal message)
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientLogger.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientLogger.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientLogger.java
index a1f053a..ca990e6 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientLogger.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientLogger.java
@@ -408,4 +408,8 @@ public interface HornetQClientLogger extends BasicLogger
    @LogMessage(level = Logger.Level.ERROR)
    @Message(id = 214023, value = "HTTP Handshake failed, the received accept value %s does not match the expected response %s")
    void httpHandshakeFailed(String response, String expectedResponse);
+
+   @LogMessage(level = Logger.Level.ERROR)
+   @Message(id = 214024, value = "HTTP upgrade not supported by remote acceptor")
+   void httpUpgradeNotSupportedByRemoteAcceptor();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientMessageBundle.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientMessageBundle.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientMessageBundle.java
index 77bada8..e426a63 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientMessageBundle.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/HornetQClientMessageBundle.java
@@ -102,7 +102,7 @@ public interface HornetQClientMessageBundle
 
    @Message(id = 119016, value =  "Connection failure detected. Unblocking a blocking call that will never get a resp" +
          "onse", format = Message.Format.MESSAGE_FORMAT)
-   HornetQUnBlockedException unblockingACall();
+   HornetQUnBlockedException unblockingACall(@Cause Throwable t);
 
    @Message(id = 119017, value =  "Consumer is closed", format = Message.Format.MESSAGE_FORMAT)
    HornetQObjectClosedException consumerClosed();
@@ -241,4 +241,7 @@ public interface HornetQClientMessageBundle
          , format = Message.Format.MESSAGE_FORMAT)
    HornetQLargeMessageInterruptedException largeMessageInterrupted();
 
+   @Message(id = 119061, value =  "error decoding AMQP frame", format = Message.Format.MESSAGE_FORMAT)
+   String decodeError();
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerImpl.java
index ac719a8..7933245 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerImpl.java
@@ -32,6 +32,7 @@ import org.hornetq.api.core.client.MessageHandler;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.client.HornetQClientMessageBundle;
+import org.hornetq.spi.core.remoting.ConsumerContext;
 import org.hornetq.spi.core.remoting.SessionContext;
 import org.hornetq.utils.FutureLatch;
 import org.hornetq.utils.PriorityLinkedList;
@@ -67,7 +68,7 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
 
    private final SessionContext sessionContext;
 
-   private final long id;
+   private final ConsumerContext consumerContext;
 
    private final SimpleString filterString;
 
@@ -137,7 +138,7 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
    // ---------------------------------------------------------------------------------
 
    public ClientConsumerImpl(final ClientSessionInternal session,
-                             final long id,
+                             final ConsumerContext consumerContext,
                              final SimpleString queueName,
                              final SimpleString filterString,
                              final boolean browseOnly,
@@ -150,7 +151,7 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
                              final ClientSession.QueueQuery queueInfo,
                              final ClassLoader contextClassLoader)
    {
-      this.id = id;
+      this.consumerContext = consumerContext;
 
       this.queueName = queueName;
 
@@ -180,9 +181,9 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
    // ClientConsumer implementation
    // -----------------------------------------------------------------
 
-   public Object getId()
+   public ConsumerContext getConsumerContext()
    {
-      return id;
+      return consumerContext;
    }
 
    private ClientMessage receive(final long timeout, final boolean forcingDelivery) throws HornetQException
@@ -421,7 +422,7 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
 
    // Must be synchronized since messages may be arriving while handler is being set and might otherwise end
    // up not queueing enough executors - so messages get stranded
-   public synchronized void setMessageHandler(final MessageHandler theHandler) throws HornetQException
+   public synchronized ClientConsumerImpl setMessageHandler(final MessageHandler theHandler) throws HornetQException
    {
       checkClosed();
 
@@ -449,6 +450,8 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
       {
          waitForOnMessageToComplete(true);
       }
+
+      return this;
    }
 
    public void close() throws HornetQException
@@ -457,29 +460,28 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
    }
 
    /**
-    * To be used by MDBs
+    * To be used by MDBs to stop any more handling of messages.
     *
     * @throws HornetQException
+    * @param future the future to run once the onMessage Thread has completed
     */
-   public void interruptHandlers() throws HornetQException
+   public Thread prepareForClose(final FutureLatch future) throws HornetQException
    {
       closing = true;
 
       resetLargeMessageController();
 
-      Thread onThread = onMessageThread;
-      if (onThread != null)
+      //execute the future after the last onMessage call
+      sessionExecutor.execute(new Runnable()
       {
-         try
-         {
-            // just trying to interrupt any ongoing messages
-            onThread.interrupt();
-         }
-         catch (Throwable ignored)
+         @Override
+         public void run()
          {
-            // security exception probably.. we just ignore it, not big deal!
+            future.run();
          }
-      }
+      });
+
+      return onMessageThread;
    }
 
    public void cleanUp()
@@ -558,11 +560,6 @@ public final class ClientConsumerImpl implements ClientConsumerInternal
       return queueInfo;
    }
 
-   public long getID()
-   {
-      return id;
-   }
-
    public SimpleString getFilterString()
    {
       return filterString;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerInternal.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerInternal.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerInternal.java
index c0b4c1e..5b198f5 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerInternal.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientConsumerInternal.java
@@ -17,6 +17,7 @@ import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.ClientConsumer;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.utils.FutureLatch;
 
 /**
  * A ClientConsumerInternal
@@ -25,8 +26,6 @@ import org.hornetq.api.core.client.ClientSession;
  */
 public interface ClientConsumerInternal extends ClientConsumer
 {
-   long getID();
-
    SimpleString getQueueName();
 
    SimpleString getFilterString();
@@ -47,8 +46,9 @@ public interface ClientConsumerInternal extends ClientConsumer
     * To be called by things like MDBs during shutdown of the server
     *
     * @throws HornetQException
+    * @param future
     */
-   void interruptHandlers() throws HornetQException;
+   Thread prepareForClose(FutureLatch future) throws HornetQException;
 
    void clearAtFailover();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientLargeMessageImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientLargeMessageImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientLargeMessageImpl.java
index 65adfbc..09a7503 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientLargeMessageImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientLargeMessageImpl.java
@@ -131,7 +131,7 @@ public final class ClientLargeMessageImpl extends ClientMessageImpl implements C
    }
 
    @Override
-   public void setOutputStream(final OutputStream out) throws HornetQException
+   public ClientLargeMessageImpl setOutputStream(final OutputStream out) throws HornetQException
    {
       if (bodyBuffer != null)
       {
@@ -141,6 +141,8 @@ public final class ClientLargeMessageImpl extends ClientMessageImpl implements C
       {
          largeMessageController.setOutputStream(out);
       }
+
+      return this;
    }
 
    @Override


[35/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInternalErrorException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInternalErrorException.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInternalErrorException.java
deleted file mode 100644
index 61ae1d4..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInternalErrorException.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton.exceptions;
-
-import org.apache.qpid.proton.amqp.transport.AmqpError;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         6/6/13
- */
-public class HornetQAMQPInternalErrorException extends HornetQAMQPException
-{
-   public HornetQAMQPInternalErrorException(String message)
-   {
-      super(AmqpError.INTERNAL_ERROR, message);
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInvalidFieldException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInvalidFieldException.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInvalidFieldException.java
deleted file mode 100644
index 006687a..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPInvalidFieldException.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton.exceptions;
-
-import org.apache.qpid.proton.amqp.transport.AmqpError;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         6/6/13
- */
-public class HornetQAMQPInvalidFieldException extends HornetQAMQPException
-{
-   public HornetQAMQPInvalidFieldException(String message)
-   {
-      super(AmqpError.INVALID_FIELD, message);
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPNotImplementedException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPNotImplementedException.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPNotImplementedException.java
deleted file mode 100644
index 782afb1..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPNotImplementedException.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton.exceptions;
-
-import org.apache.qpid.proton.amqp.transport.AmqpError;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         6/19/13
- */
-public class HornetQAMQPNotImplementedException extends HornetQAMQPException
-{
-   public HornetQAMQPNotImplementedException(String message)
-   {
-      super(AmqpError.NOT_IMPLEMENTED, message);
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/HornetQProtonConnectionCallback.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/HornetQProtonConnectionCallback.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/HornetQProtonConnectionCallback.java
new file mode 100644
index 0000000..43e1d2b
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/HornetQProtonConnectionCallback.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton.plug;
+
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import org.hornetq.core.buffers.impl.ChannelBufferWrapper;
+import org.hornetq.core.protocol.proton.HornetQProtonRemotingConnection;
+import org.hornetq.core.protocol.proton.ProtonProtocolManager;
+import org.hornetq.core.protocol.proton.sasl.HornetQPlainSASL;
+import org.hornetq.spi.core.remoting.Connection;
+import org.hornetq.utils.ReusableLatch;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPConnectionContext;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.ServerSASL;
+import org.proton.plug.sasl.AnonymousServerSASL;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class HornetQProtonConnectionCallback implements AMQPConnectionCallback
+{
+   private final ProtonProtocolManager manager;
+
+   private final Connection connection;
+
+   protected HornetQProtonRemotingConnection protonConnectionDelegate;
+
+   protected AMQPConnectionContext amqpConnection;
+
+   private final ReusableLatch latch = new ReusableLatch(0);
+
+   public HornetQProtonConnectionCallback(ProtonProtocolManager manager, Connection connection)
+   {
+      this.manager = manager;
+      this.connection = connection;
+   }
+
+   @Override
+   public ServerSASL[] getSASLMechnisms()
+   {
+      return new ServerSASL[]{new AnonymousServerSASL(), new HornetQPlainSASL(manager.getServer().getSecurityStore(), manager.getServer().getSecurityManager())};
+   }
+
+   @Override
+   public void close()
+   {
+
+   }
+
+   @Override
+   public void setConnection(AMQPConnectionContext connection)
+   {
+      this.amqpConnection = connection;
+   }
+
+   @Override
+   public AMQPConnectionContext getConnection()
+   {
+      return amqpConnection;
+   }
+
+   public HornetQProtonRemotingConnection getProtonConnectionDelegate()
+   {
+      return protonConnectionDelegate;
+   }
+
+   public void setProtonConnectionDelegate(HornetQProtonRemotingConnection protonConnectionDelegate)
+   {
+      this.protonConnectionDelegate = protonConnectionDelegate;
+   }
+
+   public void onTransport(ByteBuf byteBuf, AMQPConnectionContext amqpConnection)
+   {
+      final int size = byteBuf.writerIndex();
+
+      latch.countUp();
+      connection.write(new ChannelBufferWrapper(byteBuf, true), false, false, new ChannelFutureListener()
+      {
+         @Override
+         public void operationComplete(ChannelFuture future) throws Exception
+         {
+            latch.countDown();
+         }
+      });
+
+      if (amqpConnection.isSyncOnFlush())
+      {
+         try
+         {
+            latch.await(5, TimeUnit.SECONDS);
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+         }
+      }
+
+      amqpConnection.outputDone(size);
+   }
+
+
+   @Override
+   public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection)
+   {
+      return new ProtonSessionIntegrationCallback(this, manager, connection);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java
new file mode 100644
index 0000000..cbb2c77
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/ProtonSessionIntegrationCallback.java
@@ -0,0 +1,341 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton.plug;
+
+
+import io.netty.buffer.ByteBuf;
+import org.apache.qpid.proton.amqp.Binary;
+import org.apache.qpid.proton.amqp.transport.AmqpError;
+import org.apache.qpid.proton.amqp.transport.ErrorCondition;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Link;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.jms.EncodedMessage;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.core.journal.IOAsyncTask;
+import org.hornetq.core.protocol.proton.ProtonProtocolManager;
+import org.hornetq.core.server.QueueQueryResult;
+import org.hornetq.core.server.ServerConsumer;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.ServerSession;
+import org.hornetq.spi.core.protocol.SessionCallback;
+import org.hornetq.spi.core.remoting.ReadyListener;
+import org.hornetq.utils.ByteUtil;
+import org.hornetq.utils.IDGenerator;
+import org.hornetq.utils.SimpleIDGenerator;
+import org.hornetq.utils.UUIDGenerator;
+import org.proton.plug.AMQPConnectionContext;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.AMQPSessionContext;
+import org.proton.plug.SASLResult;
+import org.proton.plug.context.ProtonPlugSender;
+import org.proton.plug.sasl.PlainSASLResult;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonSessionIntegrationCallback implements AMQPSessionCallback, SessionCallback
+{
+   protected final IDGenerator consumerIDGenerator = new SimpleIDGenerator(0);
+
+   private final HornetQProtonConnectionCallback protonSPI;
+
+   private final ProtonProtocolManager manager;
+
+   private final AMQPConnectionContext connection;
+
+   private ServerSession serverSession;
+
+   private AMQPSessionContext protonSession;
+
+   public ProtonSessionIntegrationCallback(HornetQProtonConnectionCallback protonSPI, ProtonProtocolManager manager, AMQPConnectionContext connection)
+   {
+      this.protonSPI = protonSPI;
+      this.manager = manager;
+      this.connection = connection;
+   }
+
+   @Override
+   public void onFlowConsumer(Object consumer, int credits)
+   {
+      // We have our own flow control on AMQP, so we set hornetq's flow control to 0
+      ((ServerConsumer) consumer).receiveCredits(-1);
+   }
+
+   @Override
+   public void init(AMQPSessionContext protonSession, SASLResult saslResult) throws Exception
+   {
+
+      this.protonSession = protonSession;
+
+      String name = UUIDGenerator.getInstance().generateStringUUID();
+
+      String user = null;
+      String passcode = null;
+      if (saslResult != null)
+      {
+         user = saslResult.getUser();
+         if (saslResult instanceof PlainSASLResult)
+         {
+            passcode = ((PlainSASLResult)saslResult).getPassword();
+         }
+      }
+
+      serverSession = manager.getServer().createSession(name,
+                                                        user,
+                                                        passcode,
+                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
+                                                        protonSPI.getProtonConnectionDelegate(), // RemotingConnection remotingConnection,
+                                                        false, // boolean autoCommitSends
+                                                        false, // boolean autoCommitAcks,
+                                                        false, // boolean preAcknowledge,
+                                                        true, //boolean xa,
+                                                        (String) null,
+                                                        this,
+                                                        null);
+   }
+
+   @Override
+   public void start()
+   {
+
+   }
+
+   @Override
+   public Object createSender(ProtonPlugSender protonSender, String queue, String filer, boolean browserOnly) throws Exception
+   {
+      long consumerID = consumerIDGenerator.generateID();
+
+      ServerConsumer consumer = serverSession.createConsumer(consumerID, SimpleString.toSimpleString(queue), SimpleString.toSimpleString(filer), browserOnly);
+
+      // AMQP handles its own flow control for when it's started
+      consumer.setStarted(true);
+
+      consumer.setProtocolContext(protonSender);
+
+      return consumer;
+   }
+
+   @Override
+   public void startSender(Object brokerConsumer) throws Exception
+   {
+      ServerConsumer serverConsumer = (ServerConsumer) brokerConsumer;
+      // flow control is done at proton
+      serverConsumer.receiveCredits(-1);
+   }
+
+   @Override
+   public void createTemporaryQueue(String queueName) throws Exception
+   {
+      serverSession.createQueue(SimpleString.toSimpleString(queueName), SimpleString.toSimpleString(queueName), null, true, false);
+   }
+
+   @Override
+   public boolean queueQuery(String queueName) throws Exception
+   {
+      QueueQueryResult queueQuery = serverSession.executeQueueQuery(SimpleString.toSimpleString(queueName));
+      return queueQuery.isExists();
+   }
+
+   @Override
+   public void closeSender(Object brokerConsumer) throws Exception
+   {
+      ((ServerConsumer) brokerConsumer).close(false);
+   }
+
+   @Override
+   public ProtonJMessage encodeMessage(Object message, int deliveryCount) throws Exception
+   {
+      return (ProtonJMessage) manager.getConverter().outbound((ServerMessage) message, deliveryCount);
+   }
+
+   @Override
+   public Binary getCurrentTXID()
+   {
+      return new Binary(ByteUtil.longToBytes(serverSession.getCurrentTransaction().getID()));
+   }
+
+   @Override
+   public String tempQueueName()
+   {
+      return UUIDGenerator.getInstance().generateStringUUID();
+   }
+
+   @Override
+   public void commitCurrentTX() throws Exception
+   {
+      serverSession.commit();
+   }
+
+   @Override
+   public void rollbackCurrentTX() throws Exception
+   {
+      serverSession.rollback(false);
+   }
+
+   @Override
+   public void close() throws Exception
+   {
+      serverSession.close(false);
+   }
+
+   @Override
+   public void ack(Object brokerConsumer, Object message) throws Exception
+   {
+      ((ServerConsumer)brokerConsumer).individualAcknowledge(null, ((ServerMessage)message).getMessageID());
+   }
+
+   @Override
+   public void cancel(Object brokerConsumer, Object message, boolean updateCounts) throws Exception
+   {
+      ((ServerConsumer)brokerConsumer).individualCancel(((ServerMessage)message).getMessageID(), updateCounts);
+   }
+
+   @Override
+   public void resumeDelivery(Object consumer)
+   {
+      ((ServerConsumer) consumer).receiveCredits(-1);
+   }
+
+   @Override
+   public void serverSend(final Receiver receiver, final Delivery delivery, String address, int messageFormat, ByteBuf messageEncoded) throws Exception
+   {
+      EncodedMessage encodedMessage = new EncodedMessage(messageFormat, messageEncoded.array(), messageEncoded.arrayOffset(), messageEncoded.writerIndex());
+
+      ServerMessage message = manager.getConverter().inbound(encodedMessage);
+      //use the address on the receiver if not null, if null let's hope it was set correctly on the message
+      if (address != null)
+      {
+         message.setAddress(new SimpleString(address));
+      }
+
+      serverSession.send(message, false);
+
+      manager.getServer().getStorageManager().afterCompleteOperations(new IOAsyncTask()
+      {
+         @Override
+         public void done()
+         {
+            synchronized (connection.getLock())
+            {
+               delivery.settle();
+               connection.flush();
+            }
+         }
+
+         @Override
+         public void onError(int errorCode, String errorMessage)
+         {
+            synchronized (connection.getLock())
+            {
+               receiver.setCondition(new ErrorCondition(AmqpError.ILLEGAL_STATE, errorCode + ":" + errorMessage));
+               connection.flush();
+            }
+         }
+      });
+   }
+
+
+   @Override
+   public void sendProducerCreditsMessage(int credits, SimpleString address)
+   {
+   }
+
+   @Override
+   public void sendProducerCreditsFailMessage(int credits, SimpleString address)
+   {
+   }
+
+   @Override
+   public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount)
+   {
+
+      ProtonPlugSender plugSender = (ProtonPlugSender) consumer.getProtocolContext();
+
+      try
+      {
+         return plugSender.deliverMessage(message, deliveryCount);
+      }
+      catch (Exception e)
+      {
+         synchronized (connection.getLock())
+         {
+            plugSender.getSender().setCondition(new ErrorCondition(AmqpError.INTERNAL_ERROR, e.getMessage()));
+            connection.flush();
+         }
+         throw new IllegalStateException("Can't deliver message " + e, e);
+      }
+
+   }
+
+   @Override
+   public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount)
+   {
+      return 0;
+   }
+
+   @Override
+   public int sendLargeMessageContinuation(ServerConsumer consumer, byte[] body, boolean continues, boolean requiresResponse)
+   {
+      return 0;
+   }
+
+   @Override
+   public void closed()
+   {
+   }
+
+   @Override
+   public void addReadyListener(ReadyListener listener)
+   {
+
+   }
+
+   @Override
+   public void removeReadyListener(ReadyListener listener)
+   {
+
+   }
+
+   @Override
+   public void disconnect(ServerConsumer consumer, String queueName)
+   {
+      synchronized (connection.getLock())
+      {
+         ((Link) consumer.getProtocolContext()).close();
+         connection.flush();
+      }
+   }
+
+
+   @Override
+   public boolean hasCredits(ServerConsumer consumer)
+   {
+      ProtonPlugSender plugSender = (ProtonPlugSender) consumer.getProtocolContext();
+
+      if (plugSender != null && plugSender.getSender().getCredit() > 0)
+      {
+         return true;
+      }
+      else
+      {
+         return false;
+      }
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/package-info.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/package-info.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/package-info.java
new file mode 100644
index 0000000..5612b2a
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/plug/package-info.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+/**
+ * This package contains classes for integration with the ProtonPlug
+ * @author Clebert Suconic
+ */
+package org.hornetq.core.protocol.proton.plug;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/sasl/HornetQPlainSASL.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/sasl/HornetQPlainSASL.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/sasl/HornetQPlainSASL.java
new file mode 100644
index 0000000..43e7f29
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/sasl/HornetQPlainSASL.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton.sasl;
+
+import org.hornetq.core.security.SecurityStore;
+import org.hornetq.spi.core.security.HornetQSecurityManager;
+import org.proton.plug.sasl.ServerSASLPlain;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class HornetQPlainSASL extends ServerSASLPlain
+{
+
+   private final HornetQSecurityManager securityManager;
+
+   private final SecurityStore securityStore;
+
+
+   public HornetQPlainSASL(SecurityStore securityStore, HornetQSecurityManager securityManager)
+   {
+      this.securityManager = securityManager;
+      this.securityStore = securityStore;
+   }
+
+   @Override
+   protected boolean authenticate(String user, String password)
+   {
+      if (securityStore.isSecurityEnabled())
+      {
+         return securityManager.validateUser(user, password);
+      }
+      else
+      {
+         return true;
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/test/java/org/hornetq/core/protocol/proton/TestConversions.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/test/java/org/hornetq/core/protocol/proton/TestConversions.java b/hornetq-protocols/hornetq-amqp-protocol/src/test/java/org/hornetq/core/protocol/proton/TestConversions.java
new file mode 100644
index 0000000..029a763
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/test/java/org/hornetq/core/protocol/proton/TestConversions.java
@@ -0,0 +1,841 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.PooledByteBufAllocator;
+import org.apache.qpid.proton.amqp.Binary;
+import org.apache.qpid.proton.amqp.messaging.AmqpSequence;
+import org.apache.qpid.proton.amqp.messaging.AmqpValue;
+import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
+import org.apache.qpid.proton.amqp.messaging.Data;
+import org.apache.qpid.proton.jms.EncodedMessage;
+import org.apache.qpid.proton.message.Message;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.apache.qpid.proton.message.impl.MessageImpl;
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.journal.EncodingSupport;
+import org.hornetq.core.protocol.proton.converter.ProtonMessageConverter;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSBytesMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSMapMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSStreamMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSTextMessage;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.utils.SimpleIDGenerator;
+import org.junit.Assert;
+import org.junit.Test;
+import org.proton.plug.util.NettyWritable;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class TestConversions extends Assert
+{
+
+   @Test
+   public void testSimpleConversionBytes() throws Exception
+   {
+      Map<String, Object> mapprop = createPropertiesMap();
+      ApplicationProperties properties = new ApplicationProperties(mapprop);
+      MessageImpl message = (MessageImpl) Message.Factory.create();
+      message.setApplicationProperties(properties);
+
+      byte[] bodyBytes = new byte[4];
+
+      for (int i = 0; i < bodyBytes.length; i++)
+      {
+         bodyBytes[i] = (byte) 0xff;
+      }
+
+      message.setBody(new Data(new Binary(bodyBytes)));
+
+
+      EncodedMessage encodedMessage = encodeMessage(message);
+
+
+      ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0));
+      ServerJMSBytesMessage serverMessage = (ServerJMSBytesMessage)converter.inboundJMSType(encodedMessage);
+
+      verifyProperties(serverMessage);
+
+
+      assertEquals(bodyBytes.length, serverMessage.getBodyLength());
+
+      byte[] newBodyBytes = new byte[4];
+
+      serverMessage.readBytes(newBodyBytes);
+
+
+      Assert.assertArrayEquals(bodyBytes, newBodyBytes);
+
+
+      Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0);
+
+      System.out.println("output = " + obj);
+
+   }
+
+   private void verifyProperties(javax.jms.Message message) throws Exception
+   {
+      assertEquals(true, message.getBooleanProperty("true"));
+      assertEquals(false, message.getBooleanProperty("false"));
+      assertEquals("bar", message.getStringProperty("foo"));
+   }
+
+   private Map<String, Object> createPropertiesMap()
+   {
+      Map<String, Object> mapprop = new HashMap<>();
+
+      mapprop.put("true", Boolean.TRUE);
+      mapprop.put("false", Boolean.FALSE);
+      mapprop.put("foo", "bar");
+      return mapprop;
+   }
+
+   @Test
+   public void testSimpleConversionMap() throws Exception
+   {
+      Map<String, Object> mapprop = createPropertiesMap();
+      ApplicationProperties properties = new ApplicationProperties(mapprop);
+      MessageImpl message = (MessageImpl) Message.Factory.create();
+      message.setApplicationProperties(properties);
+
+      Map<String, Object> mapValues = new HashMap<>();
+      mapValues.put("somestr", "value");
+      mapValues.put("someint", Integer.valueOf(1));
+
+      message.setBody(new AmqpValue(mapValues));
+
+      EncodedMessage encodedMessage = encodeMessage(message);
+
+      ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0));
+      ServerJMSMapMessage serverMessage = (ServerJMSMapMessage)converter.inboundJMSType(encodedMessage);
+
+      verifyProperties(serverMessage);
+
+      Assert.assertEquals(1, serverMessage.getInt("someint"));
+      Assert.assertEquals("value", serverMessage.getString("somestr"));
+
+      Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0);
+
+      reEncodeMsg(obj);
+
+
+      MessageImpl outMessage = (MessageImpl) obj;
+      AmqpValue value = (AmqpValue)outMessage.getBody();
+      Map mapoutput = (Map)value.getValue();
+
+      assertEquals(Integer.valueOf(1), (Integer) mapoutput.get("someint"));
+
+
+      System.out.println("output = " + obj);
+
+   }
+
+
+   @Test
+   public void testSimpleConversionStream() throws Exception
+   {
+      Map<String, Object> mapprop = createPropertiesMap();
+      ApplicationProperties properties = new ApplicationProperties(mapprop);
+      MessageImpl message = (MessageImpl) Message.Factory.create();
+      message.setApplicationProperties(properties);
+
+      List<Object> objects = new LinkedList<>();
+      objects.add(new Integer(10));
+      objects.add("10");
+
+      message.setBody(new AmqpSequence(objects));
+
+      EncodedMessage encodedMessage = encodeMessage(message);
+
+      ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0));
+      ServerJMSStreamMessage serverMessage = (ServerJMSStreamMessage)converter.inboundJMSType(encodedMessage);
+
+      simulatePersistence(serverMessage);
+
+      verifyProperties(serverMessage);
+
+      serverMessage.reset();
+
+      assertEquals(10, serverMessage.readInt());
+      assertEquals("10", serverMessage.readString());
+
+      Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0);
+
+      reEncodeMsg(obj);
+
+      MessageImpl outMessage = (MessageImpl)obj;
+      List list = ((AmqpSequence)outMessage.getBody()).getValue();
+      Assert.assertEquals(Integer.valueOf(10), list.get(0));
+      Assert.assertEquals("10", list.get(1));
+
+   }
+
+   @Test
+   public void testSimpleConversionText() throws Exception
+   {
+      Map<String, Object> mapprop = createPropertiesMap();
+      ApplicationProperties properties = new ApplicationProperties(mapprop);
+      MessageImpl message = (MessageImpl) Message.Factory.create();
+      message.setApplicationProperties(properties);
+
+      String text = "someText";
+      message.setBody(new AmqpValue(text));
+
+      EncodedMessage encodedMessage = encodeMessage(message);
+
+      ProtonMessageConverter converter = new ProtonMessageConverter(new SimpleIDGenerator(0));
+      ServerJMSTextMessage serverMessage = (ServerJMSTextMessage)converter.inboundJMSType(encodedMessage);
+
+      simulatePersistence(serverMessage);
+
+
+      verifyProperties(serverMessage);
+
+      Assert.assertEquals(text, serverMessage.getText());
+
+
+      Object obj = converter.outbound((ServerMessage)serverMessage.getInnerMessage(), 0);
+
+
+      reEncodeMsg(obj);
+
+      MessageImpl outMessage = (MessageImpl) obj;
+      AmqpValue value = (AmqpValue)outMessage.getBody();
+      String textValue = (String)value.getValue();
+
+      Assert.assertEquals(text, textValue);
+
+      System.out.println("output = " + obj);
+
+   }
+
+   private void simulatePersistence(ServerJMSMessage serverMessage)
+   {
+      serverMessage.getInnerMessage().setAddress(new SimpleString("jms.queue.SomeAddress"));
+      // This is just to simulate what would happen during the persistence of the message
+      // We need to still be able to recover the message when we read it back
+      ((EncodingSupport)serverMessage.getInnerMessage()).encode(new EmptyBuffer());
+   }
+
+   private ProtonJMessage reEncodeMsg(Object obj)
+   {
+      ProtonJMessage objOut = (ProtonJMessage)obj;
+
+      ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
+
+      objOut.encode(new NettyWritable(nettyBuffer));
+      return objOut;
+   }
+
+
+   private EncodedMessage encodeMessage(MessageImpl message)
+   {
+      ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024 * 1024);
+      message.encode(new NettyWritable(buf));
+      byte[] bytesConvert = new byte[buf.writerIndex()];
+      buf.readBytes(bytesConvert);
+      return new EncodedMessage(0, bytesConvert, 0, bytesConvert.length);
+   }
+
+
+   class EmptyBuffer implements HornetQBuffer
+   {
+      @Override
+      public ByteBuf byteBuf()
+      {
+         return null;
+      }
+
+      @Override
+      public int capacity()
+      {
+         return 0;
+      }
+
+      @Override
+      public int readerIndex()
+      {
+         return 0;
+      }
+
+      @Override
+      public void readerIndex(int readerIndex)
+      {
+
+      }
+
+      @Override
+      public int writerIndex()
+      {
+         return 0;
+      }
+
+      @Override
+      public void writerIndex(int writerIndex)
+      {
+
+      }
+
+      @Override
+      public void setIndex(int readerIndex, int writerIndex)
+      {
+
+      }
+
+      @Override
+      public int readableBytes()
+      {
+         return 0;
+      }
+
+      @Override
+      public int writableBytes()
+      {
+         return 0;
+      }
+
+      @Override
+      public boolean readable()
+      {
+         return false;
+      }
+
+      @Override
+      public boolean writable()
+      {
+         return false;
+      }
+
+      @Override
+      public void clear()
+      {
+
+      }
+
+      @Override
+      public void markReaderIndex()
+      {
+
+      }
+
+      @Override
+      public void resetReaderIndex()
+      {
+
+      }
+
+      @Override
+      public void markWriterIndex()
+      {
+
+      }
+
+      @Override
+      public void resetWriterIndex()
+      {
+
+      }
+
+      @Override
+      public void discardReadBytes()
+      {
+
+      }
+
+      @Override
+      public byte getByte(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public short getUnsignedByte(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public short getShort(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public int getUnsignedShort(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public int getInt(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public long getUnsignedInt(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public long getLong(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public void getBytes(int index, HornetQBuffer dst)
+      {
+
+      }
+
+      @Override
+      public void getBytes(int index, HornetQBuffer dst, int length)
+      {
+
+      }
+
+      @Override
+      public void getBytes(int index, HornetQBuffer dst, int dstIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void getBytes(int index, byte[] dst)
+      {
+
+      }
+
+      @Override
+      public void getBytes(int index, byte[] dst, int dstIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void getBytes(int index, ByteBuffer dst)
+      {
+
+      }
+
+      @Override
+      public char getChar(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public float getFloat(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public double getDouble(int index)
+      {
+         return 0;
+      }
+
+      @Override
+      public void setByte(int index, byte value)
+      {
+
+      }
+
+      @Override
+      public void setShort(int index, short value)
+      {
+
+      }
+
+      @Override
+      public void setInt(int index, int value)
+      {
+
+      }
+
+      @Override
+      public void setLong(int index, long value)
+      {
+
+      }
+
+      @Override
+      public void setBytes(int index, HornetQBuffer src)
+      {
+
+      }
+
+      @Override
+      public void setBytes(int index, HornetQBuffer src, int length)
+      {
+
+      }
+
+      @Override
+      public void setBytes(int index, HornetQBuffer src, int srcIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void setBytes(int index, byte[] src)
+      {
+
+      }
+
+      @Override
+      public void setBytes(int index, byte[] src, int srcIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void setBytes(int index, ByteBuffer src)
+      {
+
+      }
+
+      @Override
+      public void setChar(int index, char value)
+      {
+
+      }
+
+      @Override
+      public void setFloat(int index, float value)
+      {
+
+      }
+
+      @Override
+      public void setDouble(int index, double value)
+      {
+
+      }
+
+      @Override
+      public byte readByte()
+      {
+         return 0;
+      }
+
+      @Override
+      public short readUnsignedByte()
+      {
+         return 0;
+      }
+
+      @Override
+      public short readShort()
+      {
+         return 0;
+      }
+
+      @Override
+      public int readUnsignedShort()
+      {
+         return 0;
+      }
+
+      @Override
+      public int readInt()
+      {
+         return 0;
+      }
+
+      @Override
+      public long readUnsignedInt()
+      {
+         return 0;
+      }
+
+      @Override
+      public long readLong()
+      {
+         return 0;
+      }
+
+      @Override
+      public char readChar()
+      {
+         return 0;
+      }
+
+      @Override
+      public float readFloat()
+      {
+         return 0;
+      }
+
+      @Override
+      public double readDouble()
+      {
+         return 0;
+      }
+
+      @Override
+      public boolean readBoolean()
+      {
+         return false;
+      }
+
+      @Override
+      public SimpleString readNullableSimpleString()
+      {
+         return null;
+      }
+
+      @Override
+      public String readNullableString()
+      {
+         return null;
+      }
+
+      @Override
+      public SimpleString readSimpleString()
+      {
+         return null;
+      }
+
+      @Override
+      public String readString()
+      {
+         return null;
+      }
+
+      @Override
+      public String readUTF()
+      {
+         return null;
+      }
+
+      @Override
+      public HornetQBuffer readBytes(int length)
+      {
+         return null;
+      }
+
+      @Override
+      public HornetQBuffer readSlice(int length)
+      {
+         return null;
+      }
+
+      @Override
+      public void readBytes(HornetQBuffer dst)
+      {
+
+      }
+
+      @Override
+      public void readBytes(HornetQBuffer dst, int length)
+      {
+
+      }
+
+      @Override
+      public void readBytes(HornetQBuffer dst, int dstIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void readBytes(byte[] dst)
+      {
+
+      }
+
+      @Override
+      public void readBytes(byte[] dst, int dstIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void readBytes(ByteBuffer dst)
+      {
+
+      }
+
+      @Override
+      public void skipBytes(int length)
+      {
+
+      }
+
+      @Override
+      public void writeByte(byte value)
+      {
+
+      }
+
+      @Override
+      public void writeShort(short value)
+      {
+
+      }
+
+      @Override
+      public void writeInt(int value)
+      {
+
+      }
+
+      @Override
+      public void writeLong(long value)
+      {
+
+      }
+
+      @Override
+      public void writeChar(char chr)
+      {
+
+      }
+
+      @Override
+      public void writeFloat(float value)
+      {
+
+      }
+
+      @Override
+      public void writeDouble(double value)
+      {
+
+      }
+
+      @Override
+      public void writeBoolean(boolean val)
+      {
+
+      }
+
+      @Override
+      public void writeNullableSimpleString(SimpleString val)
+      {
+
+      }
+
+      @Override
+      public void writeNullableString(String val)
+      {
+
+      }
+
+      @Override
+      public void writeSimpleString(SimpleString val)
+      {
+
+      }
+
+      @Override
+      public void writeString(String val)
+      {
+
+      }
+
+      @Override
+      public void writeUTF(String utf)
+      {
+
+      }
+
+      @Override
+      public void writeBytes(HornetQBuffer src, int length)
+      {
+
+      }
+
+      @Override
+      public void writeBytes(HornetQBuffer src, int srcIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void writeBytes(byte[] src)
+      {
+
+      }
+
+      @Override
+      public void writeBytes(byte[] src, int srcIndex, int length)
+      {
+
+      }
+
+      @Override
+      public void writeBytes(ByteBuffer src)
+      {
+
+      }
+
+      @Override
+      public HornetQBuffer copy()
+      {
+         return null;
+      }
+
+      @Override
+      public HornetQBuffer copy(int index, int length)
+      {
+         return null;
+      }
+
+      @Override
+      public HornetQBuffer slice()
+      {
+         return null;
+      }
+
+      @Override
+      public HornetQBuffer slice(int index, int length)
+      {
+         return null;
+      }
+
+      @Override
+      public HornetQBuffer duplicate()
+      {
+         return null;
+      }
+
+      @Override
+      public ByteBuffer toByteBuffer()
+      {
+         return null;
+      }
+
+      @Override
+      public ByteBuffer toByteBuffer(int index, int length)
+      {
+         return null;
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/pom.xml b/hornetq-protocols/hornetq-openwire-protocol/pom.xml
new file mode 100644
index 0000000..447ceb0
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/pom.xml
@@ -0,0 +1,49 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+   <parent>
+      <artifactId>hornetq-protocols</artifactId>
+      <groupId>org.hornetq</groupId>
+      <version>2.5.0-SNAPSHOT</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+
+   <artifactId>hornetq-openwire-protocol</artifactId>
+
+   <properties>
+      <hornetq.basedir>${project.parent.parent.basedir}</hornetq.basedir>
+   </properties>
+
+   <dependencies>
+      <dependency>
+         <groupId>org.jboss.logging</groupId>
+         <artifactId>jboss-logging-processor</artifactId>
+      </dependency>
+
+      <!--
+          JBoss Logging
+      -->
+      <dependency>
+         <groupId>org.jboss.logging</groupId>
+         <artifactId>jboss-logging</artifactId>
+      </dependency>
+      <dependency>
+         <groupId>org.apache.activemq</groupId>
+         <artifactId>activemq-client</artifactId>
+      </dependency>
+      <dependency>
+        <groupId>org.slf4j</groupId>
+        <artifactId>slf4j-api</artifactId>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-server</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-jms-client</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+   </dependencies>
+
+</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQConnectorImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQConnectorImpl.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQConnectorImpl.java
new file mode 100644
index 0000000..3732a54
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQConnectorImpl.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import org.apache.activemq.command.BrokerInfo;
+import org.apache.activemq.command.ConnectionControl;
+import org.hornetq.core.protocol.openwire.amq.AMQConnector;
+import org.hornetq.core.protocol.openwire.amq.AMQConnectorStatistics;
+import org.hornetq.spi.core.remoting.Acceptor;
+
+public class AMQConnectorImpl implements AMQConnector
+{
+   private Acceptor acceptor;
+
+   public AMQConnectorImpl(Acceptor acceptorUsed)
+   {
+      this.acceptor = acceptorUsed;
+   }
+
+   @Override
+   public BrokerInfo getBrokerInfo()
+   {
+      // TODO Auto-generated method stub
+      return null;
+   }
+
+   @Override
+   public AMQConnectorStatistics getStatistics()
+   {
+      // TODO Auto-generated method stub
+      return null;
+   }
+
+   @Override
+   public boolean isUpdateClusterClients()
+   {
+      // TODO Auto-generated method stub
+      return false;
+   }
+
+   @Override
+   public boolean isRebalanceClusterClients()
+   {
+      // TODO Auto-generated method stub
+      return false;
+   }
+
+   @Override
+   public void updateClientClusterInfo()
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public boolean isUpdateClusterClientsOnRemove()
+   {
+      // TODO Auto-generated method stub
+      return false;
+   }
+
+   @Override
+   public int connectionCount()
+   {
+      // TODO Auto-generated method stub
+      return 0;
+   }
+
+   @Override
+   public boolean isAllowLinkStealing()
+   {
+      // TODO Auto-generated method stub
+      return false;
+   }
+
+   @Override
+   public ConnectionControl getConnectionControl()
+   {
+      return new ConnectionControl();
+   }
+
+   @Override
+   public void onStarted(OpenWireConnection connection)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public void onStopped(OpenWireConnection connection)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   public int getMaximumConsumersAllowedPerConnection()
+   {
+      return 1000000;//this belongs to configuration, now hardcoded
+   }
+
+   public int getMaximumProducersAllowedPerConnection()
+   {
+      return 1000000;//this belongs to configuration, now hardcoded
+   }
+
+   public boolean isAuditNetworkProducers()
+   {
+      return false;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQTransactionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQTransactionImpl.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQTransactionImpl.java
new file mode 100644
index 0000000..d0d5a30
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/AMQTransactionImpl.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.server.Queue;
+import org.hornetq.core.server.impl.RefsOperation;
+import org.hornetq.core.transaction.Transaction;
+import org.hornetq.core.transaction.impl.TransactionImpl;
+
+import javax.transaction.xa.Xid;
+
+public class AMQTransactionImpl extends TransactionImpl
+{
+   private boolean rollbackForClose = false;
+
+   public AMQTransactionImpl(StorageManager storageManager, int timeoutSeconds)
+   {
+      super(storageManager, timeoutSeconds);
+   }
+
+   public AMQTransactionImpl(StorageManager storageManager)
+   {
+      super(storageManager);
+   }
+
+   public AMQTransactionImpl(Xid xid, StorageManager storageManager, int timeoutSeconds)
+   {
+      super(xid, storageManager, timeoutSeconds);
+   }
+
+   public AMQTransactionImpl(long id, Xid xid, StorageManager storageManager)
+   {
+      super(id, xid, storageManager);
+   }
+
+   @Override
+   public RefsOperation createRefsOperation(Queue queue)
+   {
+      return new AMQrefsOperation(queue, storageManager);
+   }
+
+   public class AMQrefsOperation extends RefsOperation
+   {
+      public AMQrefsOperation(Queue queue, StorageManager storageManager)
+      {
+         super(queue, storageManager);
+      }
+
+      @Override
+      public void afterRollback(Transaction tx)
+      {
+         if (rollbackForClose)
+         {
+            super.afterRollback(tx);
+         }
+      }
+   }
+
+   public void setRollbackForClose()
+   {
+      this.rollbackForClose = true;
+   }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/BrokerState.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/BrokerState.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/BrokerState.java
new file mode 100644
index 0000000..fb67b1d
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/BrokerState.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+/**
+ * The class holds related states of an activemq broker.
+ * @author howard
+ *
+ */
+public class BrokerState
+{
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/DataInputWrapper.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/DataInputWrapper.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/DataInputWrapper.java
new file mode 100644
index 0000000..911f034
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/DataInputWrapper.java
@@ -0,0 +1,257 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import java.io.DataInput;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.utils.UTF8Util;
+import org.hornetq.utils.UTF8Util.StringUtilBuffer;
+
+public class DataInputWrapper implements DataInput
+{
+   private static final int DEFAULT_CAPACITY = 1024 * 1024;
+   private static final NotEnoughBytesException exception = new NotEnoughBytesException();
+   private ByteBuffer internalBuffer;
+
+   public DataInputWrapper()
+   {
+      this(DEFAULT_CAPACITY);
+   }
+
+   public DataInputWrapper(int capacity)
+   {
+      this.internalBuffer = ByteBuffer.allocateDirect(capacity);
+      this.internalBuffer.mark();
+      this.internalBuffer.limit(0);
+   }
+
+   public void receiveData(byte[] data)
+   {
+      int newSize = data.length;
+      int freeSpace = internalBuffer.capacity() - internalBuffer.limit();
+      if (freeSpace < newSize)
+      {
+         internalBuffer.reset();
+         internalBuffer.compact();
+         if (internalBuffer.remaining() < newSize)
+         {
+            //need to enlarge
+         }
+         //make sure mark is at zero and position is at effective limit
+         int pos = internalBuffer.position();
+         internalBuffer.position(0);
+         internalBuffer.mark();
+         internalBuffer.position(pos);
+      }
+      else
+      {
+         internalBuffer.position(internalBuffer.limit());
+         internalBuffer.limit(internalBuffer.capacity());
+      }
+      internalBuffer.put(data);
+      internalBuffer.limit(internalBuffer.position());
+      internalBuffer.reset();
+   }
+
+   public void receiveData(HornetQBuffer buffer)
+   {
+      int newSize = buffer.readableBytes();
+      byte[] newData = new byte[newSize];
+      buffer.readBytes(newData);
+      this.receiveData(newData);
+   }
+
+   //invoke after each successful unmarshall
+   public void mark()
+   {
+      this.internalBuffer.mark();
+   }
+
+   @Override
+   public void readFully(byte[] b) throws IOException
+   {
+      readFully(b, 0, b.length);
+   }
+
+   private void checkSize(int n) throws NotEnoughBytesException
+   {
+      if (internalBuffer.remaining() < n)
+      {
+         throw exception;
+      }
+   }
+
+   @Override
+   public void readFully(byte[] b, int off, int len) throws IOException
+   {
+      checkSize(len);
+      internalBuffer.get(b, off, len);
+   }
+
+   @Override
+   public int skipBytes(int n) throws IOException
+   {
+      checkSize(n);
+      int pos = internalBuffer.position();
+      internalBuffer.position(pos + n);
+      return n;
+   }
+
+   @Override
+   public boolean readBoolean() throws IOException
+   {
+      checkSize(1);
+      byte b = internalBuffer.get();
+      return b != 0;
+   }
+
+   @Override
+   public byte readByte() throws IOException
+   {
+      checkSize(1);
+      return this.internalBuffer.get();
+   }
+
+   @Override
+   public int readUnsignedByte() throws IOException
+   {
+      checkSize(1);
+      return 0xFF & this.internalBuffer.get();
+   }
+
+   @Override
+   public short readShort() throws IOException
+   {
+      checkSize(2);
+      return this.internalBuffer.getShort();
+   }
+
+   @Override
+   public int readUnsignedShort() throws IOException
+   {
+      checkSize(2);
+      return 0xFFFF & this.internalBuffer.getShort();
+   }
+
+   @Override
+   public char readChar() throws IOException
+   {
+      checkSize(2);
+      return this.internalBuffer.getChar();
+   }
+
+   @Override
+   public int readInt() throws IOException
+   {
+      checkSize(4);
+      return this.internalBuffer.getInt();
+   }
+
+   @Override
+   public long readLong() throws IOException
+   {
+      checkSize(8);
+      return this.internalBuffer.getLong();
+   }
+
+   @Override
+   public float readFloat() throws IOException
+   {
+      checkSize(4);
+      return this.internalBuffer.getFloat();
+   }
+
+   @Override
+   public double readDouble() throws IOException
+   {
+      checkSize(8);
+      return this.internalBuffer.getDouble();
+   }
+
+   @Override
+   public String readLine() throws IOException
+   {
+      StringBuilder sb = new StringBuilder("");
+      char c = this.readChar();
+      while (c != '\n')
+      {
+         sb.append(c);
+         c = this.readChar();
+      }
+      return sb.toString();
+   }
+
+   @Override
+   public String readUTF() throws IOException
+   {
+      StringUtilBuffer buffer = UTF8Util.getThreadLocalBuffer();
+
+      final int size = this.readUnsignedShort();
+
+      if (size > buffer.byteBuffer.length)
+      {
+         buffer.resizeByteBuffer(size);
+      }
+
+      if (size > buffer.charBuffer.length)
+      {
+         buffer.resizeCharBuffer(size);
+      }
+
+      int count = 0;
+      int byte1, byte2, byte3;
+      int charCount = 0;
+
+      this.readFully(buffer.byteBuffer, 0, size);
+
+      while (count < size)
+      {
+         byte1 = buffer.byteBuffer[count++];
+
+         if (byte1 > 0 && byte1 <= 0x7F)
+         {
+            buffer.charBuffer[charCount++] = (char)byte1;
+         }
+         else
+         {
+            int c = byte1 & 0xff;
+            switch (c >> 4)
+            {
+               case 0xc:
+               case 0xd:
+                  byte2 = buffer.byteBuffer[count++];
+                  buffer.charBuffer[charCount++] = (char)((c & 0x1F) << 6 | byte2 & 0x3F);
+                  break;
+               case 0xe:
+                  byte2 = buffer.byteBuffer[count++];
+                  byte3 = buffer.byteBuffer[count++];
+                  buffer.charBuffer[charCount++] = (char)((c & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F) << 0);
+                  break;
+               default:
+                  throw new InternalError("unhandled utf8 byte " + c);
+            }
+         }
+      }
+
+      return new String(buffer.charBuffer, 0, charCount);
+   }
+
+   public boolean readable()
+   {
+      return this.internalBuffer.hasRemaining();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/NotEnoughBytesException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/NotEnoughBytesException.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/NotEnoughBytesException.java
new file mode 100644
index 0000000..940649f
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/NotEnoughBytesException.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import java.io.IOException;
+
+public class NotEnoughBytesException extends IOException
+{
+   private static final long serialVersionUID = 3752739907942923658L;
+
+}


[05/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlTest.java
index f78509e..2d6b052 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlTest.java
@@ -18,8 +18,12 @@ import javax.jms.Message;
 import javax.jms.MessageConsumer;
 import javax.jms.MessageProducer;
 import javax.jms.Session;
+import javax.management.Notification;
 import javax.naming.Context;
+
+import java.util.ArrayList;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
@@ -31,9 +35,11 @@ import org.hornetq.api.core.client.ClientProducer;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.api.core.management.ObjectNameBuilder;
 import org.hornetq.api.jms.HornetQJMSClient;
 import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.api.jms.management.JMSQueueControl;
+import org.hornetq.api.jms.management.JMSServerControl;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory;
 import org.hornetq.core.server.HornetQServer;
@@ -43,6 +49,7 @@ import org.hornetq.jms.client.HornetQConnectionFactory;
 import org.hornetq.jms.client.HornetQDestination;
 import org.hornetq.jms.client.HornetQQueue;
 import org.hornetq.jms.server.impl.JMSServerManagerImpl;
+import org.hornetq.jms.server.management.JMSNotificationType;
 import org.hornetq.tests.integration.management.ManagementControlHelper;
 import org.hornetq.tests.integration.management.ManagementTestBase;
 import org.hornetq.tests.unit.util.InVMNamingContext;
@@ -90,7 +97,7 @@ public class JMSQueueControlTest extends ManagementTestBase
    {
       JMSQueueControl queueControl = createManagementControl();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
       Assert.assertEquals(0, queueControl.getConsumerCount());
 
       Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName());
@@ -104,16 +111,16 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       JMSUtil.sendMessages(queue, 2);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
-      Assert.assertEquals(2, queueControl.getMessagesAdded());
+      Assert.assertEquals(2, getMessageCount(queueControl));
+      Assert.assertEquals(2, getMessagesAdded(queueControl));
 
       connection.start();
 
       Assert.assertNotNull(consumer.receive(500));
       Assert.assertNotNull(consumer.receive(500));
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
-      Assert.assertEquals(2, queueControl.getMessagesAdded());
+      Assert.assertEquals(0, getMessageCount(queueControl));
+      Assert.assertEquals(2, getMessagesAdded(queueControl));
 
       consumer.close();
 
@@ -127,11 +134,11 @@ public class JMSQueueControlTest extends ManagementTestBase
    {
       JMSQueueControl queueControl = createManagementControl();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       String[] ids = JMSUtil.sendMessages(queue, 2);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       Map<String, Object>[] data = queueControl.listMessages(null);
       Assert.assertEquals(2, data.length);
@@ -150,11 +157,11 @@ public class JMSQueueControlTest extends ManagementTestBase
    {
       JMSQueueControl queueControl = createManagementControl();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       String[] ids = JMSUtil.sendMessages(queue, 2);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       String jsonString = queueControl.listMessagesAsJSON(null);
       Assert.assertNotNull(jsonString);
@@ -176,11 +183,11 @@ public class JMSQueueControlTest extends ManagementTestBase
    {
       JMSQueueControl queueControl = createManagementControl();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       JMSUtil.sendMessages(queue, 2);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       Map<String, Object>[] data = queueControl.listMessages(null);
       Assert.assertEquals(2, data.length);
@@ -197,7 +204,7 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       queueControl.removeMessage(messageID.toString());
 
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
    }
 
    @Test
@@ -207,7 +214,7 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       JMSQueueControl queueControl = createManagementControl();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       try
       {
@@ -224,15 +231,15 @@ public class JMSQueueControlTest extends ManagementTestBase
    {
       JMSQueueControl queueControl = createManagementControl();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       JMSUtil.sendMessages(queue, 2);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       queueControl.removeMessages(null);
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName());
       connection.start();
@@ -248,7 +255,7 @@ public class JMSQueueControlTest extends ManagementTestBase
    {
       JMSQueueControl queueControl = createManagementControl();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       Connection conn = createConnection();
 
@@ -263,12 +270,12 @@ public class JMSQueueControlTest extends ManagementTestBase
       message.setStringProperty("foo", "baz");
       producer.send(message);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       int removedMatchingMessagesCount = queueControl.removeMessages("foo = 'bar'");
       Assert.assertEquals(1, removedMatchingMessagesCount);
 
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       conn.start();
       MessageConsumer consumer = JMSUtil.createConsumer(conn, queue);
@@ -286,7 +293,7 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       JMSUtil.sendMessages(queue, 1);
 
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       Map<String, Object>[] data = queueControl.listMessages(null);
       // retrieve the first message info
@@ -317,7 +324,7 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       String[] messageIDs = JMSUtil.sendMessages(queue, 1);
 
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       try
       {
@@ -371,11 +378,11 @@ public class JMSQueueControlTest extends ManagementTestBase
       Message msg_2 = JMSUtil.sendMessageWithProperty(session, queue, key, unmatchingValue);
 
       JMSQueueControl queueControl = createManagementControl();
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       int changedMessagesCount = queueControl.changeMessagesPriority(filter, newPriority);
       Assert.assertEquals(1, changedMessagesCount);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       connection.start();
       MessageConsumer consumer = session.createConsumer(queue);
@@ -463,13 +470,13 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       String[] messageIDs = JMSUtil.sendMessages(queue, 1);
 
-      Assert.assertEquals(1, queueControl.getMessageCount());
-      Assert.assertEquals(0, expiryQueueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
+      Assert.assertEquals(0, getMessageCount(expiryQueueControl));
 
       Assert.assertTrue(queueControl.expireMessage(messageIDs[0]));
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
-      Assert.assertEquals(1, expiryQueueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
+      Assert.assertEquals(1, getMessageCount(expiryQueueControl));
 
       Connection connection = JMSUtil.createConnection(InVMConnectorFactory.class.getName());
       connection.start();
@@ -517,11 +524,11 @@ public class JMSQueueControlTest extends ManagementTestBase
       connection.close();
 
       JMSQueueControl queueControl = createManagementControl();
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       int expiredMessagesCount = queueControl.expireMessages(filter);
       Assert.assertEquals(1, expiredMessagesCount);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // consume the unmatched message from queue
       JMSUtil.consumeMessages(1, queue);
@@ -543,7 +550,7 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSUtil.sendMessageWithProperty(session, queue, key, unmatchingValue);
       JMSUtil.sendMessageWithProperty(session, queue, key, matchingValue);
 
-      Assert.assertEquals(3, queueControl.getMessageCount());
+      Assert.assertEquals(3, getMessageCount(queueControl));
 
       Assert.assertEquals(2, queueControl.countMessages(key + " =" + matchingValue));
       Assert.assertEquals(1, queueControl.countMessages(key + " =" + unmatchingValue));
@@ -608,15 +615,15 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSQueueControl queueControl = createManagementControl();
       JMSQueueControl dlqControl = ManagementControlHelper.createJMSQueueControl(dlq, mbeanServer);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
-      Assert.assertEquals(0, dlqControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
+      Assert.assertEquals(0, getMessageCount(dlqControl));
 
       queueControl.setDeadLetterAddress(dlq.getAddress());
 
       boolean movedToDeadLetterAddress = queueControl.sendMessageToDeadLetterAddress(message.getJMSMessageID());
       Assert.assertTrue(movedToDeadLetterAddress);
-      Assert.assertEquals(1, queueControl.getMessageCount());
-      Assert.assertEquals(1, dlqControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
+      Assert.assertEquals(1, getMessageCount(dlqControl));
 
       // check there is a single message to consume from queue
       JMSUtil.consumeMessages(1, queue);
@@ -667,15 +674,15 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSQueueControl queueControl = createManagementControl();
       JMSQueueControl dlqControl = ManagementControlHelper.createJMSQueueControl(dlq, mbeanServer);
 
-      Assert.assertEquals(2, queueControl.getMessageCount());
-      Assert.assertEquals(0, dlqControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
+      Assert.assertEquals(0, getMessageCount(dlqControl));
 
       queueControl.setDeadLetterAddress(dlq.getAddress());
 
       int deadMessageCount = queueControl.sendMessagesToDeadLetterAddress(filter);
       Assert.assertEquals(1, deadMessageCount);
-      Assert.assertEquals(1, queueControl.getMessageCount());
-      Assert.assertEquals(1, dlqControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
+      Assert.assertEquals(1, getMessageCount(dlqControl));
 
       conn.start();
       MessageConsumer consumer = sess.createConsumer(queue);
@@ -704,12 +711,12 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSUtil.sendMessages(queue, 2);
 
       JMSQueueControl queueControl = createManagementControl();
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // moved all messages to otherQueue
       int movedMessagesCount = queueControl.moveMessages(null, otherQueueName);
       Assert.assertEquals(2, movedMessagesCount);
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       // check there is no message to consume from queue
       JMSUtil.consumeMessages(0, queue);
@@ -756,12 +763,12 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSUtil.sendMessageWithProperty(session, queue, key, unmatchingValue);
 
       JMSQueueControl queueControl = createManagementControl();
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // moved matching messages to otherQueue
       int movedMessagesCount = queueControl.moveMessages(filter, otherQueueName);
       Assert.assertEquals(1, movedMessagesCount);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       connection.start();
       MessageConsumer consumer = session.createConsumer(queue);
@@ -788,11 +795,11 @@ public class JMSQueueControlTest extends ManagementTestBase
       String[] messageIDs = JMSUtil.sendMessages(queue, 1);
 
       JMSQueueControl queueControl = createManagementControl();
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       boolean moved = queueControl.moveMessage(messageIDs[0], otherQueueName);
       Assert.assertTrue(moved);
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       JMSUtil.consumeMessages(0, queue);
       JMSUtil.consumeMessages(1, otherQueue);
@@ -837,7 +844,7 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((HornetQQueue) otherQueue,
                                                                                         mbeanServer);
 
-      Assert.assertEquals(10, queueControl.getMessageCount());
+      Assert.assertEquals(10, getMessageCount(queueControl));
 
       int moved = queueControl.moveMessages(null, otherQueueName, true);
 
@@ -872,9 +879,9 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       locator.close();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
-      Assert.assertEquals(0, otherQueueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(otherQueueControl));
 
       serverManager.destroyQueue(otherQueueName);
    }
@@ -923,7 +930,7 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((HornetQQueue) otherQueue,
                                                                                         mbeanServer);
 
-      Assert.assertEquals(10, queueControl.getMessageCount());
+      Assert.assertEquals(10, getMessageCount(queueControl));
 
       for (int i = 0; i < 10; i++)
       {
@@ -959,9 +966,9 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       locator.close();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
-      Assert.assertEquals(0, otherQueueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(otherQueueControl));
 
       serverManager.destroyQueue(otherQueueName);
    }
@@ -994,8 +1001,8 @@ public class JMSQueueControlTest extends ManagementTestBase
       JMSQueueControl otherQueueControl = ManagementControlHelper.createJMSQueueControl((HornetQQueue) otherQueue,
                                                                                         mbeanServer);
 
-      Assert.assertEquals(1, queueControl.getMessageCount());
-      Assert.assertEquals(1, otherQueueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
+      Assert.assertEquals(1, getMessageCount(otherQueueControl));
 
       int moved = queueControl.moveMessages(null, otherQueueName, true);
 
@@ -1027,9 +1034,9 @@ public class JMSQueueControlTest extends ManagementTestBase
 
       locator.close();
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
-      Assert.assertEquals(0, otherQueueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(otherQueueControl));
 
       serverManager.destroyQueue(otherQueueName);
    }
@@ -1043,7 +1050,7 @@ public class JMSQueueControlTest extends ManagementTestBase
       serverManager.createQueue(false, otherQueueName, null, true, otherQueueName);
 
       JMSQueueControl queueControl = createManagementControl();
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       try
       {
@@ -1170,7 +1177,7 @@ public class JMSQueueControlTest extends ManagementTestBase
       String[] messageIDs = JMSUtil.sendMessages(queue, 1);
 
       JMSQueueControl queueControl = createManagementControl();
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       try
       {
@@ -1259,6 +1266,46 @@ public class JMSQueueControlTest extends ManagementTestBase
       assertTrue(newBindingAdded);
    }
 
+   //make sure notifications are always received no matter whether
+   //a Queue is created via JMSServerControl or by JMSServerManager directly.
+   @Test
+   public void testCreateQueueNotification() throws Exception
+   {
+      JMSUtil.JMXListener listener = new JMSUtil.JMXListener();
+      this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), listener, null, null);
+
+      List<String> connectors = new ArrayList<String>();
+      connectors.add("invm");
+
+      String testQueueName = "newQueue";
+      serverManager.createQueue(true, testQueueName, null, true, testQueueName);
+
+      Notification notif = listener.getNotification();
+
+      assertEquals(JMSNotificationType.QUEUE_CREATED.toString(), notif.getType());
+      assertEquals(testQueueName, notif.getMessage());
+
+      this.serverManager.destroyQueue(testQueueName);
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.QUEUE_DESTROYED.toString(), notif.getType());
+      assertEquals(testQueueName, notif.getMessage());
+
+      JMSServerControl control = ManagementControlHelper.createJMSServerControl(mbeanServer);
+
+      control.createQueue(testQueueName);
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.QUEUE_CREATED.toString(), notif.getType());
+      assertEquals(testQueueName, notif.getMessage());
+
+      control.destroyQueue(testQueueName);
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.QUEUE_DESTROYED.toString(), notif.getType());
+      assertEquals(testQueueName, notif.getMessage());
+   }
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
@@ -1269,11 +1316,9 @@ public class JMSQueueControlTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
-      conf.setFileDeploymentEnabled(false);
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY))
+         .setFileDeploymentEnabled(false);
       server = createServer(this.getName().contains("WithRealData"), conf, mbeanServer);
 
       serverManager = new JMSServerManagerImpl(server);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java
index 6b833d5..13c8cb7 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSQueueControlUsingJMSTest.java
@@ -89,6 +89,20 @@ public class JMSQueueControlUsingJMSTest extends JMSQueueControlTest
 
       return new JMSQueueControl()
       {
+
+         @Override
+         public void flushExecutor()
+         {
+            try
+            {
+               proxy.invokeOperation("flushExecutor");
+            }
+            catch (Exception e)
+            {
+               throw new RuntimeException(e.getMessage(), e);
+            }
+         }
+
          public boolean changeMessagePriority(final String messageID, final int newPriority) throws Exception
          {
             return (Boolean)proxy.invokeOperation("changeMessagePriority", messageID, newPriority);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControl2Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControl2Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControl2Test.java
index 93e8b26..1395a81 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControl2Test.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControl2Test.java
@@ -29,6 +29,7 @@ import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
 import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.management.QueueControl;
 import org.hornetq.api.jms.HornetQJMSClient;
 import org.hornetq.api.jms.management.JMSConnectionInfo;
 import org.hornetq.api.jms.management.JMSConsumerInfo;
@@ -76,10 +77,8 @@ public class JMSServerControl2Test extends ManagementTestBase
 
    private void startHornetQServer(final String acceptorFactory) throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(acceptorFactory));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(acceptorFactory));
       server = addServer(HornetQServers.newHornetQServer(conf, mbeanServer, true));
       server.start();
 
@@ -128,6 +127,42 @@ public class JMSServerControl2Test extends ManagementTestBase
    }
 
    @Test
+   public void testCloseConsumerConnectionsForAddressForInVM() throws Exception
+   {
+      doCloseConsumerConnectionsForAddress(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName());
+   }
+
+   @Test
+   public void testCloseConsumerConnectionsForAddressForNetty() throws Exception
+   {
+      doCloseConsumerConnectionsForAddress(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName());
+   }
+
+   @Test
+   public void testCloseConsumerConnectionsForWildcardAddressForInVM() throws Exception
+   {
+      doCloseConsumerConnectionsForWildcardAddress(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName());
+   }
+
+   @Test
+   public void testCloseConsumerConnectionsForWildcardAddressForNetty() throws Exception
+   {
+      doCloseConsumerConnectionsForWildcardAddress(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName());
+   }
+
+   @Test
+   public void testCloseConnectionsForUserForInVM() throws Exception
+   {
+      doCloseConnectionsForUser(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName());
+   }
+
+   @Test
+   public void testCloseConnectionsForUserForNetty() throws Exception
+   {
+      doCloseConnectionsForUser(NettyAcceptorFactory.class.getName(), NettyConnectorFactory.class.getName());
+   }
+
+   @Test
    public void testListSessionsForInVM() throws Exception
    {
       doListSessions(InVMAcceptorFactory.class.getName(), InVMConnectorFactory.class.getName());
@@ -1023,6 +1058,261 @@ public class JMSServerControl2Test extends ManagementTestBase
       }
    }
 
+   private void doCloseConsumerConnectionsForAddress(final String acceptorFactory, final String connectorFactory) throws Exception
+   {
+      String queueName = RandomUtil.randomString();
+      String queueName2 = RandomUtil.randomString();
+
+      try
+      {
+         startHornetQServer(acceptorFactory);
+         serverManager.createQueue(false, queueName, null, true, queueName);
+         Queue queue = HornetQJMSClient.createQueue(queueName);
+         serverManager.createQueue(false, queueName2, null, true, queueName2);
+         Queue queue2 = HornetQJMSClient.createQueue(queueName2);
+
+         JMSServerControl control = createManagementControl();
+         QueueControl queueControl = createManagementControl("jms.queue." + queueName, "jms.queue." + queueName);
+         QueueControl queueControl2 = createManagementControl("jms.queue." + queueName2, "jms.queue." + queueName2);
+
+         Assert.assertEquals(0, server.getConnectionCount());
+         Assert.assertEquals(0, control.listRemoteAddresses().length);
+         Assert.assertEquals(0, queueControl.getConsumerCount());
+         Assert.assertEquals(0, queueControl2.getConsumerCount());
+
+         ConnectionFactory cf = JMSUtil.createFactory(connectorFactory,
+                                                      JMSServerControl2Test.CONNECTION_TTL,
+                                                      JMSServerControl2Test.PING_PERIOD);
+         Connection connection = cf.createConnection();
+         Session session = connection.createSession();
+         MessageConsumer messageConsumer = session.createConsumer(queue);
+
+         Connection connection2 = cf.createConnection();
+         Session session2 = connection2.createSession();
+         MessageConsumer messageConsumer2 = session2.createConsumer(queue2);
+
+         Assert.assertEquals(2, server.getConnectionCount());
+
+         String[] remoteAddresses = control.listRemoteAddresses();
+         Assert.assertEquals(2, remoteAddresses.length);
+
+         Assert.assertEquals(1, queueControl.getConsumerCount());
+         Assert.assertEquals(1, queueControl2.getConsumerCount());
+
+         final CountDownLatch exceptionLatch = new CountDownLatch(1);
+         connection.setExceptionListener(new ExceptionListener()
+         {
+            public void onException(final JMSException e)
+            {
+               exceptionLatch.countDown();
+            }
+         });
+
+         Assert.assertTrue(control.closeConsumerConnectionsForAddress("jms.queue." + queueName));
+
+         boolean gotException = exceptionLatch.await(2 * JMSServerControl2Test.CONNECTION_TTL, TimeUnit.MILLISECONDS);
+         Assert.assertTrue("did not received the expected JMSException", gotException);
+
+         remoteAddresses = control.listRemoteAddresses();
+         Assert.assertEquals("got " + Arrays.asList(remoteAddresses), 1, remoteAddresses.length);
+         Assert.assertEquals(1, server.getConnectionCount());
+
+         Assert.assertEquals(0, queueControl.getConsumerCount());
+         Assert.assertEquals(1, queueControl2.getConsumerCount());
+
+         connection2.close();
+      }
+      finally
+      {
+         if (serverManager != null)
+         {
+            serverManager.stop();
+         }
+
+         if (server != null)
+         {
+            server.stop();
+         }
+      }
+   }
+
+   private void doCloseConsumerConnectionsForWildcardAddress(final String acceptorFactory, final String connectorFactory) throws Exception
+   {
+      String queueName1 = "x." + RandomUtil.randomString();
+      String queueName2 = "x." + RandomUtil.randomString();
+      String queueName3 = "y." + RandomUtil.randomString();
+
+      try
+      {
+         startHornetQServer(acceptorFactory);
+         serverManager.createQueue(false, queueName1, null, true, queueName1);
+         Queue queue = HornetQJMSClient.createQueue(queueName1);
+         serverManager.createQueue(false, queueName2, null, true, queueName2);
+         Queue queue2 = HornetQJMSClient.createQueue(queueName2);
+         serverManager.createQueue(false, queueName3, null, true, queueName3);
+         Queue queue3 = HornetQJMSClient.createQueue(queueName3);
+
+         JMSServerControl control = createManagementControl();
+         QueueControl queueControl = createManagementControl("jms.queue." + queueName1, "jms.queue." + queueName1);
+         QueueControl queueControl2 = createManagementControl("jms.queue." + queueName2, "jms.queue." + queueName2);
+         QueueControl queueControl3 = createManagementControl("jms.queue." + queueName3, "jms.queue." + queueName3);
+
+         Assert.assertEquals(0, server.getConnectionCount());
+         Assert.assertEquals(0, control.listRemoteAddresses().length);
+         Assert.assertEquals(0, queueControl.getConsumerCount());
+         Assert.assertEquals(0, queueControl2.getConsumerCount());
+         Assert.assertEquals(0, queueControl3.getConsumerCount());
+
+         ConnectionFactory cf = JMSUtil.createFactory(connectorFactory,
+                                                      JMSServerControl2Test.CONNECTION_TTL,
+                                                      JMSServerControl2Test.PING_PERIOD);
+         Connection connection = cf.createConnection();
+         Session session = connection.createSession();
+         MessageConsumer messageConsumer = session.createConsumer(queue);
+
+         Connection connection2 = cf.createConnection();
+         Session session2 = connection2.createSession();
+         MessageConsumer messageConsumer2 = session2.createConsumer(queue2);
+
+         Connection connection3 = cf.createConnection();
+         Session session3 = connection3.createSession();
+         MessageConsumer messageConsumer3 = session3.createConsumer(queue3);
+
+         Assert.assertEquals(3, server.getConnectionCount());
+
+         String[] remoteAddresses = control.listRemoteAddresses();
+         Assert.assertEquals(3, remoteAddresses.length);
+
+         Assert.assertEquals(1, queueControl.getConsumerCount());
+         Assert.assertEquals(1, queueControl2.getConsumerCount());
+         Assert.assertEquals(1, queueControl3.getConsumerCount());
+
+         final CountDownLatch exceptionLatch = new CountDownLatch(2);
+         connection.setExceptionListener(new ExceptionListener()
+         {
+            public void onException(final JMSException e)
+            {
+               exceptionLatch.countDown();
+            }
+         });
+
+         connection2.setExceptionListener(new ExceptionListener()
+         {
+            public void onException(final JMSException e)
+            {
+               exceptionLatch.countDown();
+            }
+         });
+
+         Assert.assertTrue(control.closeConsumerConnectionsForAddress("jms.queue.x.#"));
+
+         boolean gotException = exceptionLatch.await(2 * JMSServerControl2Test.CONNECTION_TTL, TimeUnit.MILLISECONDS);
+         Assert.assertTrue("did not received the expected JMSException", gotException);
+
+         remoteAddresses = control.listRemoteAddresses();
+         Assert.assertEquals("got " + Arrays.asList(remoteAddresses), 1, remoteAddresses.length);
+         Assert.assertEquals(1, server.getConnectionCount());
+
+         Assert.assertEquals(0, queueControl.getConsumerCount());
+         Assert.assertEquals(0, queueControl2.getConsumerCount());
+         Assert.assertEquals(1, queueControl3.getConsumerCount());
+
+         connection.close();
+         connection2.close();
+         connection3.close();
+      }
+      finally
+      {
+         if (serverManager != null)
+         {
+            serverManager.stop();
+         }
+
+         if (server != null)
+         {
+            server.stop();
+         }
+      }
+   }
+
+   private void doCloseConnectionsForUser(final String acceptorFactory, final String connectorFactory) throws Exception
+   {
+      String queueName = RandomUtil.randomString();
+      String queueName2 = RandomUtil.randomString();
+
+      try
+      {
+         startHornetQServer(acceptorFactory);
+         serverManager.createQueue(false, queueName, null, true, queueName);
+         Queue queue = HornetQJMSClient.createQueue(queueName);
+         serverManager.createQueue(false, queueName2, null, true, queueName2);
+         Queue queue2 = HornetQJMSClient.createQueue(queueName2);
+
+         JMSServerControl control = createManagementControl();
+         QueueControl queueControl = createManagementControl("jms.queue." + queueName, "jms.queue." + queueName);
+         QueueControl queueControl2 = createManagementControl("jms.queue." + queueName2, "jms.queue." + queueName2);
+
+         Assert.assertEquals(0, server.getConnectionCount());
+         Assert.assertEquals(0, control.listRemoteAddresses().length);
+         Assert.assertEquals(0, queueControl.getConsumerCount());
+         Assert.assertEquals(0, queueControl2.getConsumerCount());
+
+         ConnectionFactory cf = JMSUtil.createFactory(connectorFactory,
+                                                      JMSServerControl2Test.CONNECTION_TTL,
+                                                      JMSServerControl2Test.PING_PERIOD);
+         Connection connection = cf.createConnection("fakeUser", "fakePassword");
+         Session session = connection.createSession();
+         MessageConsumer messageConsumer = session.createConsumer(queue);
+
+         Connection connection2 = cf.createConnection();
+         Session session2 = connection2.createSession();
+         MessageConsumer messageConsumer2 = session2.createConsumer(queue2);
+
+         Assert.assertEquals(2, server.getConnectionCount());
+
+         String[] remoteAddresses = control.listRemoteAddresses();
+         Assert.assertEquals(2, remoteAddresses.length);
+
+         Assert.assertEquals(1, queueControl.getConsumerCount());
+         Assert.assertEquals(1, queueControl2.getConsumerCount());
+
+         final CountDownLatch exceptionLatch = new CountDownLatch(1);
+         connection.setExceptionListener(new ExceptionListener()
+         {
+            public void onException(final JMSException e)
+            {
+               exceptionLatch.countDown();
+            }
+         });
+
+         Assert.assertTrue(control.closeConnectionsForUser("fakeUser"));
+
+         boolean gotException = exceptionLatch.await(2 * JMSServerControl2Test.CONNECTION_TTL, TimeUnit.MILLISECONDS);
+         Assert.assertTrue("did not received the expected JMSException", gotException);
+
+         remoteAddresses = control.listRemoteAddresses();
+         Assert.assertEquals("got " + Arrays.asList(remoteAddresses), 1, remoteAddresses.length);
+         Assert.assertEquals(1, server.getConnectionCount());
+
+         Assert.assertEquals(0, queueControl.getConsumerCount());
+         Assert.assertEquals(1, queueControl2.getConsumerCount());
+
+         connection2.close();
+      }
+      finally
+      {
+         if (serverManager != null)
+         {
+            serverManager.stop();
+         }
+
+         if (server != null)
+         {
+            server.stop();
+         }
+      }
+   }
+
    // Inner classes -------------------------------------------------
 
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlRestartTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlRestartTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlRestartTest.java
index d8148fc..b6885f8 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlRestartTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlRestartTest.java
@@ -146,12 +146,12 @@ public class JMSServerControlRestartTest extends ManagementTestBase
 
    private JMSServerManager createJMSServer() throws Exception
    {
-      Configuration conf = createDefaultConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.setPersistenceEnabled(true);
-      conf.setJournalType(JournalType.NIO);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration conf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .setJMXManagementEnabled(true)
+         .setPersistenceEnabled(true)
+         .setJournalType(JournalType.NIO)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       HornetQServer server = HornetQServers.newHornetQServer(conf, mbeanServer);
 
       context = new InVMNamingContext();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlTest.java
index 3cc8651..d7eefef 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlTest.java
@@ -363,6 +363,112 @@ public class JMSServerControlTest extends ManagementTestBase
       }
    }
 
+   @Test
+   public void testDestroyQueueWithConsumersWithoutForcingTheConsumersToClose() throws Exception
+   {
+      String queueJNDIBinding = RandomUtil.randomString();
+      String queueName = RandomUtil.randomString();
+
+      UnitTestCase.checkNoBinding(context, queueJNDIBinding);
+      checkNoResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));
+
+      JMSServerControl control = createManagementControl();
+      control.createQueue(queueName, queueJNDIBinding);
+
+      UnitTestCase.checkBinding(context, queueJNDIBinding);
+      checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));
+
+      HornetQConnectionFactory cf = new HornetQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+      HornetQConnection connection = (HornetQConnection) cf.createConnection();
+      connection.start();
+      try
+      {
+         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+         MessageProducer producer = session.createProducer(HornetQJMSClient.createQueue(queueName));
+         producer.send(session.createTextMessage());
+         // create a consumer will create a Core queue bound to the topic address
+         HornetQMessageConsumer cons = (HornetQMessageConsumer) session.createConsumer(HornetQJMSClient.createQueue(queueName));
+
+         try
+         {
+            control.destroyQueue(queueName, false);
+            fail();
+         }
+         catch (Exception e)
+         {
+            assertTrue(e.getMessage().startsWith("HQ119025"));
+         }
+
+         UnitTestCase.checkBinding(context, queueJNDIBinding);
+         checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));
+
+         Assert.assertNotNull(fakeJMSStorageManager.destinationMap.get(queueName));
+
+         assertFalse(cons.isClosed());
+
+         assertNotNull(cons.receive(5000));
+      }
+      finally
+      {
+         if (connection != null)
+         {
+            connection.close();
+         }
+      }
+   }
+
+
+   @Test
+   public void testDestroyTopicWithConsumersWithoutForcingTheConsumersToClose() throws Exception
+   {
+      String topicJNDIBinding = RandomUtil.randomString();
+      String topicName = RandomUtil.randomString();
+
+      UnitTestCase.checkNoBinding(context, topicJNDIBinding);
+      checkNoResource(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topicName));
+
+      JMSServerControl control = createManagementControl();
+      control.createTopic(topicName, topicJNDIBinding);
+
+      UnitTestCase.checkBinding(context, topicJNDIBinding);
+      checkResource(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topicName));
+
+      HornetQConnectionFactory cf = new HornetQConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+      HornetQConnection connection = (HornetQConnection) cf.createConnection();
+      connection.start();
+      try
+      {
+         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+         // create a consumer will create a Core queue bound to the topic address
+         HornetQMessageConsumer cons = (HornetQMessageConsumer) session.createConsumer(HornetQJMSClient.createTopic(topicName));
+         MessageProducer producer = session.createProducer(HornetQJMSClient.createTopic(topicName));
+         producer.send(session.createTextMessage());
+
+         try
+         {
+            control.destroyTopic(topicName, false);
+            fail();
+         }
+         catch (Exception e)
+         {
+            assertTrue(e.getMessage().startsWith("HQ119025"));
+         }
+
+         UnitTestCase.checkBinding(context, topicJNDIBinding);
+         checkResource(ObjectNameBuilder.DEFAULT.getJMSTopicObjectName(topicName));
+         assertFalse(cons.isClosed());
+
+         assertNotNull(cons.receive(5000));
+      }
+      finally
+      {
+         if (connection != null)
+         {
+            connection.close();
+         }
+      }
+   }
+
 
    @Test
    public void testDestroyTopicWithConsumers() throws Exception
@@ -791,6 +897,23 @@ public class JMSServerControlTest extends ManagementTestBase
    }
 
    @Test
+   public void testDestroyConnectionFactoryWithNullBindings() throws Exception
+   {
+      // Create Connection Factory with Null Bindings
+      JMSServerControl control = createManagementControl();
+      control.createConnectionFactory("test-cf", // Name
+                                      false,     // HA
+                                      false,     // Use Discovery?
+                                      1,         // ConnectionFactory Type
+                                      "invm",    // Connector Names
+                                      null);     // JNDI Bindings
+
+      control.destroyConnectionFactory("test-cf");
+
+      assertTrue(control.getConnectionFactoryNames().length == 0);
+   }
+
+   @Test
    public void testListPreparedTransactionDetails() throws Exception
    {
       Xid xid = newXID();
@@ -935,15 +1058,12 @@ public class JMSServerControlTest extends ManagementTestBase
     */
    protected void startServer() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.setPersistenceEnabled(true);
-
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
-      conf.getConnectorConfigurations().put("netty", new TransportConfiguration(NETTY_CONNECTOR_FACTORY));
-      conf.getConnectorConfigurations().put("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+      Configuration conf = createBasicConfig()
+         .setPersistenceEnabled(true)
+         .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY))
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY))
+         .addConnectorConfiguration("netty", new TransportConfiguration(NETTY_CONNECTOR_FACTORY))
+         .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
 
       server = addServer(HornetQServers.newHornetQServer(conf, mbeanServer, true));
 
@@ -1131,4 +1251,4 @@ public class JMSServerControlTest extends ManagementTestBase
       }
    }
 
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java
index 435cf56..13c3c91 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSServerControlUsingJMSTest.java
@@ -184,6 +184,16 @@ public class JMSServerControlUsingJMSTest extends JMSServerControlTest
             return (Boolean)proxy.invokeOperation("closeConnectionsForAddress", ipAddress);
          }
 
+         public boolean closeConsumerConnectionsForAddress(final String address) throws Exception
+         {
+            return (Boolean)proxy.invokeOperation("closeConsumerConnectionsForAddress", address);
+         }
+
+         public boolean closeConnectionsForUser(final String userName) throws Exception
+         {
+            return (Boolean)proxy.invokeOperation("closeConnectionsForUser", userName);
+         }
+
          public boolean createQueue(final String name) throws Exception
          {
             return (Boolean)proxy.invokeOperation("createQueue", name);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSUtil.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSUtil.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSUtil.java
index 1b870ee..ede6476 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSUtil.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/JMSUtil.java
@@ -25,11 +25,13 @@ import javax.jms.MessageProducer;
 import javax.jms.Session;
 import javax.jms.Topic;
 import javax.jms.TopicSubscriber;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+
 import java.util.Collection;
 import java.util.Set;
 
 import org.junit.Assert;
-
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSession;
@@ -343,4 +345,20 @@ public class JMSUtil
          }
       }
    }
+
+   public static class JMXListener implements NotificationListener
+   {
+      private Notification notif;
+
+      @Override
+      public void handleNotification(Notification notification, Object handback)
+      {
+         notif = notification;
+      }
+
+      public Notification getNotification()
+      {
+         return notif;
+      }
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlTest.java
index acc0ad9..d4deaeb 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlTest.java
@@ -19,19 +19,28 @@ import javax.jms.MessageProducer;
 import javax.jms.Session;
 import javax.jms.TextMessage;
 import javax.jms.TopicSubscriber;
+import javax.management.Notification;
+
+import java.util.ArrayList;
+import java.util.List;
 import java.util.Map;
 
 import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.management.ObjectNameBuilder;
 import org.hornetq.api.jms.HornetQJMSClient;
+import org.hornetq.api.jms.management.JMSServerControl;
 import org.hornetq.api.jms.management.SubscriptionInfo;
 import org.hornetq.api.jms.management.TopicControl;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.postoffice.Binding;
+import org.hornetq.core.postoffice.impl.LocalQueueBinding;
 import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
 import org.hornetq.jms.client.HornetQDestination;
 import org.hornetq.jms.client.HornetQTopic;
 import org.hornetq.jms.server.impl.JMSServerManagerImpl;
+import org.hornetq.jms.server.management.JMSNotificationType;
 import org.hornetq.tests.integration.management.ManagementControlHelper;
 import org.hornetq.tests.integration.management.ManagementTestBase;
 import org.hornetq.tests.unit.util.InVMNamingContext;
@@ -201,6 +210,21 @@ public class TopicControlTest extends ManagementTestBase
    }
 
    @Test
+   public void testListSubscriptionsAsJSONWithHierarchicalTopics() throws Exception
+   {
+      serverManager.createTopic(false, "my.jms.#", "jms/all");
+      serverManager.createTopic(false, "my.jms.A", "jms/A");
+      HornetQTopic myTopic = (HornetQTopic) HornetQJMSClient.createTopic("my.jms.A");
+
+      TopicControl topicControl = ManagementControlHelper.createTopicControl(myTopic, mbeanServer);
+      String jsonString = topicControl.listDurableSubscriptionsAsJSON();
+      SubscriptionInfo[] infos = SubscriptionInfo.from(jsonString);
+      Assert.assertEquals(1, infos.length);
+      Assert.assertEquals("HornetQ", infos[0].getClientID());
+      Assert.assertEquals("HornetQ", infos[0].getName());
+   }
+
+   @Test
    public void testCountMessagesForSubscription() throws Exception
    {
       String key = "key";
@@ -216,6 +240,11 @@ public class TopicControlTest extends ManagementTestBase
       JMSUtil.sendMessageWithProperty(session, topic, key, unmatchingValue);
       JMSUtil.sendMessageWithProperty(session, topic, key, matchingValue);
 
+      for (Binding binding : server.getPostOffice().getBindingsForAddress(topic.getSimpleAddress()).getBindings())
+      {
+         ((LocalQueueBinding)binding).getQueue().flushExecutor();
+      }
+
       TopicControl topicControl = createManagementControl();
 
       Assert.assertEquals(3, topicControl.getMessageCount());
@@ -517,6 +546,46 @@ public class TopicControlTest extends ManagementTestBase
       connection_3.close();
    }
 
+   //make sure notifications are always received no matter whether
+   //a Topic is created via JMSServerControl or by JMSServerManager directly.
+   @Test
+   public void testCreateTopicNotification() throws Exception
+   {
+      JMSUtil.JMXListener listener = new JMSUtil.JMXListener();
+      this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), listener, null, null);
+
+      List<String> connectors = new ArrayList<String>();
+      connectors.add("invm");
+
+      String testTopicName = "newTopic";
+      serverManager.createTopic(true, testTopicName, testTopicName);
+
+      Notification notif = listener.getNotification();
+
+      assertEquals(JMSNotificationType.TOPIC_CREATED.toString(), notif.getType());
+      assertEquals(testTopicName, notif.getMessage());
+
+      this.serverManager.destroyTopic(testTopicName);
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.TOPIC_DESTROYED.toString(), notif.getType());
+      assertEquals(testTopicName, notif.getMessage());
+
+      JMSServerControl control = ManagementControlHelper.createJMSServerControl(mbeanServer);
+
+      control.createTopic(testTopicName);
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.TOPIC_CREATED.toString(), notif.getType());
+      assertEquals(testTopicName, notif.getMessage());
+
+      control.destroyTopic(testTopicName);
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.TOPIC_DESTROYED.toString(), notif.getType());
+      assertEquals(testTopicName, notif.getMessage());
+   }
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
@@ -527,11 +596,8 @@ public class TopicControlTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations()
-         .add(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
       server = HornetQServers.newHornetQServer(conf, mbeanServer, false);
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlUsingJMSTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlUsingJMSTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlUsingJMSTest.java
index 3bf01c0..e0d3bbe 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlUsingJMSTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/TopicControlUsingJMSTest.java
@@ -437,11 +437,8 @@ public class TopicControlUsingJMSTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations()
-          .add(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
       server = HornetQServers.newHornetQServer(conf, mbeanServer, false);
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/journal/NIOJournalCompactTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/journal/NIOJournalCompactTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/journal/NIOJournalCompactTest.java
index 903fcc2..a0f7b0d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/journal/NIOJournalCompactTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/journal/NIOJournalCompactTest.java
@@ -1768,14 +1768,12 @@ public class NIOJournalCompactTest extends JournalImplTestBase
    @Test
    public void testStressDeletesNoSync() throws Exception
    {
-      Configuration config = createBasicConfig();
-      config.setJournalFileSize(100 * 1024);
-      config.setJournalSyncNonTransactional(false);
-      config.setJournalSyncTransactional(false);
-//      config.setJournalBufferTimeout_NIO(2000000000);
-//      config.setJournalBufferTimeout_AIO(2000000000);
-      config.setJournalCompactMinFiles(0);
-      config.setJournalCompactPercentage(0);
+      Configuration config = createBasicConfig()
+         .setJournalFileSize(100 * 1024)
+         .setJournalSyncNonTransactional(false)
+         .setJournalSyncTransactional(false)
+         .setJournalCompactMinFiles(0)
+         .setJournalCompactPercentage(0);
 
       final AtomicInteger errors = new AtomicInteger(0);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AcceptorControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AcceptorControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AcceptorControlTest.java
index 77f8e09..b55023b 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AcceptorControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AcceptorControlTest.java
@@ -17,7 +17,6 @@ import org.junit.Test;
 import java.util.HashMap;
 
 import org.junit.Assert;
-
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
@@ -25,7 +24,7 @@ import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.api.core.management.AcceptorControl;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory;
 import org.hornetq.core.server.HornetQServer;
@@ -57,10 +56,8 @@ public class AcceptorControlTest extends ManagementTestBase
                                                                          new HashMap<String, Object>(),
                                                                          RandomUtil.randomString());
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(acceptorConfig);
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(acceptorConfig);
       HornetQServer service = createServer(false, conf, mbeanServer);
       service.start();
 
@@ -76,10 +73,8 @@ public class AcceptorControlTest extends ManagementTestBase
       TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(),
                                                                          new HashMap<String, Object>(),
                                                                          RandomUtil.randomString());
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(acceptorConfig);
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(acceptorConfig);
       HornetQServer service = createServer(false, conf, mbeanServer);
       service.start();
 
@@ -137,10 +132,8 @@ public class AcceptorControlTest extends ManagementTestBase
       TransportConfiguration acceptorConfig = new TransportConfiguration(InVMAcceptorFactory.class.getName(),
                                                                          new HashMap<String, Object>(),
                                                                          RandomUtil.randomString());
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(acceptorConfig);
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(acceptorConfig);
       HornetQServer service = createServer(false, conf, mbeanServer);
       service.start();
 
@@ -156,7 +149,7 @@ public class AcceptorControlTest extends ManagementTestBase
 
       Assert.assertEquals(1, notifListener.getNotifications().size());
       Notification notif = notifListener.getNotifications().get(0);
-      Assert.assertEquals(NotificationType.ACCEPTOR_STOPPED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.ACCEPTOR_STOPPED, notif.getType());
       Assert.assertEquals(InVMAcceptorFactory.class.getName(),
                           notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString());
 
@@ -164,7 +157,7 @@ public class AcceptorControlTest extends ManagementTestBase
 
       Assert.assertEquals(2, notifListener.getNotifications().size());
       notif = notifListener.getNotifications().get(1);
-      Assert.assertEquals(NotificationType.ACCEPTOR_STARTED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.ACCEPTOR_STARTED, notif.getType());
       Assert.assertEquals(InVMAcceptorFactory.class.getName(),
                           notif.getProperties().getSimpleStringProperty(new SimpleString("factory")).toString());
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlTest.java
index b792140..562e695 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlTest.java
@@ -309,10 +309,8 @@ public class AddressControlTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       server = createServer(false, conf, mbeanServer);
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlUsingCoreTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlUsingCoreTest.java
index 61ee30e..ef5a2e0 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlUsingCoreTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/AddressControlUsingCoreTest.java
@@ -183,10 +183,8 @@ public class AddressControlUsingCoreTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       server = createServer(false, conf, mbeanServer);
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlTest.java
index 63233ca..11acdb2 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlTest.java
@@ -12,7 +12,6 @@
  */
 package org.hornetq.tests.integration.management;
 import org.junit.Before;
-
 import org.junit.Test;
 
 import java.util.ArrayList;
@@ -24,13 +23,10 @@ import javax.management.MBeanServer;
 import javax.management.MBeanServerFactory;
 
 import org.junit.Assert;
-
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.management.BridgeControl;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ObjectNameBuilder;
 import org.hornetq.core.config.BridgeConfiguration;
 import org.hornetq.core.config.Configuration;
@@ -108,7 +104,7 @@ public class BridgeControlTest extends ManagementTestBase
 
       Assert.assertEquals(1, notifListener.getNotifications().size());
       Notification notif = notifListener.getNotifications().get(0);
-      Assert.assertEquals(NotificationType.BRIDGE_STOPPED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.BRIDGE_STOPPED, notif.getType());
       Assert.assertEquals(bridgeControl.getName(), notif.getProperties()
                                                         .getSimpleStringProperty(new SimpleString("name"))
                                                         .toString());
@@ -117,7 +113,7 @@ public class BridgeControlTest extends ManagementTestBase
 
       Assert.assertEquals(2, notifListener.getNotifications().size());
       notif = notifListener.getNotifications().get(1);
-      Assert.assertEquals(NotificationType.BRIDGE_STARTED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.BRIDGE_STARTED, notif.getType());
       Assert.assertEquals(bridgeControl.getName(), notif.getProperties()
                                                         .getSimpleStringProperty(new SimpleString("name"))
                                                         .toString());
@@ -139,49 +135,41 @@ public class BridgeControlTest extends ManagementTestBase
                                                                           acceptorParams,
                                                                           RandomUtil.randomString());
 
-      CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                                    RandomUtil.randomString(),
-                                                                    null,
-                                                                    false);
-      CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                                    RandomUtil.randomString(),
-                                                                    null,
-                                                                    false);
+      CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
+      CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
       List<String> connectors = new ArrayList<String>();
       connectors.add(connectorConfig.getName());
-      bridgeConfig = new BridgeConfiguration(RandomUtil.randomString(),
-                                             sourceQueueConfig.getName(),
-                                             targetQueueConfig.getAddress(),
-                                             null,
-                                             null,
-                                             HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                             HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                             HornetQClient.DEFAULT_CONNECTION_TTL,
-                                             RandomUtil.randomPositiveLong(),
-                                             HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                             RandomUtil.randomDouble(),
-                                             RandomUtil.randomPositiveInt(),
-                                             RandomUtil.randomPositiveInt(),
-                                             RandomUtil.randomPositiveInt(),
-                                             RandomUtil.randomBoolean(),
-                                             RandomUtil.randomPositiveInt(),
-                                             connectors,
-                                             false,
-                                       HornetQDefaultConfiguration.getDefaultClusterUser(), CLUSTER_PASSWORD);
-
-      Configuration conf_1 = createBasicConfig();
-      conf_1.setSecurityEnabled(false);
-      conf_1.setJMXManagementEnabled(true);
-      conf_1.getAcceptorConfigurations().add(acceptorConfig);
-      conf_1.getQueueConfigurations().add(targetQueueConfig);
-
-      Configuration conf_0 = createBasicConfig();
-      conf_0.setSecurityEnabled(false);
-      conf_0.setJMXManagementEnabled(true);
-      conf_0.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
-      conf_0.getConnectorConfigurations().put(connectorConfig.getName(), connectorConfig);
-      conf_0.getQueueConfigurations().add(sourceQueueConfig);
-      conf_0.getBridgeConfigurations().add(bridgeConfig);
+
+
+      Configuration conf_1 = createBasicConfig()
+         .addAcceptorConfiguration(acceptorConfig)
+         .addQueueConfiguration(targetQueueConfig);
+
+      bridgeConfig = new BridgeConfiguration()
+         .setName(RandomUtil.randomString())
+         .setQueueName(sourceQueueConfig.getName())
+         .setForwardingAddress(targetQueueConfig.getAddress())
+         .setRetryInterval(RandomUtil.randomPositiveLong())
+         .setRetryIntervalMultiplier(RandomUtil.randomDouble())
+         .setInitialConnectAttempts(RandomUtil.randomPositiveInt())
+         .setReconnectAttempts(RandomUtil.randomPositiveInt())
+         .setReconnectAttemptsOnSameNode(RandomUtil.randomPositiveInt())
+         .setUseDuplicateDetection(RandomUtil.randomBoolean())
+         .setConfirmationWindowSize(RandomUtil.randomPositiveInt())
+         .setStaticConnectors(connectors)
+         .setPassword(CLUSTER_PASSWORD);
+
+      Configuration conf_0 = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()))
+         .addConnectorConfiguration(connectorConfig.getName(), connectorConfig)
+         .addQueueConfiguration(sourceQueueConfig)
+         .addBridgeConfiguration(bridgeConfig);
 
       server_1 = HornetQServers.newHornetQServer(conf_1, MBeanServerFactory.createMBeanServer(), false);
       addServer(server_1);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlUsingCoreTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlUsingCoreTest.java
index 17752f4..8ee4e78 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlUsingCoreTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BridgeControlUsingCoreTest.java
@@ -24,7 +24,6 @@ import javax.management.MBeanServerFactory;
 
 import org.junit.Assert;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
@@ -133,50 +132,38 @@ public class BridgeControlUsingCoreTest extends ManagementTestBase
                                                                           acceptorParams,
                                                                           RandomUtil.randomString());
 
-      CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                                    RandomUtil.randomString(),
-                                                                    null,
-                                                                    false);
-      CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                                    RandomUtil.randomString(),
-                                                                    null,
-                                                                    false);
+      CoreQueueConfiguration sourceQueueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
+      CoreQueueConfiguration targetQueueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
       List<String> connectors = new ArrayList<String>();
       connectors.add(connectorConfig.getName());
-      bridgeConfig = new BridgeConfiguration(RandomUtil.randomString(),
-                                             sourceQueueConfig.getName(),
-                                             targetQueueConfig.getAddress(),
-                                             null,
-                                             null,
-                                             HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                             HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                             HornetQClient.DEFAULT_CONNECTION_TTL,
-                                             RandomUtil.randomPositiveLong(),
-                                             HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                             RandomUtil.randomDouble(),
-                                             RandomUtil.randomPositiveInt(),
-                                             RandomUtil.randomPositiveInt(),
-                                             RandomUtil.randomPositiveInt(),
-                                             RandomUtil.randomBoolean(),
-                                             RandomUtil.randomPositiveInt(),
-                                             connectors,
-                                             false,
-                                             HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                             HornetQDefaultConfiguration.getDefaultClusterPassword());
-
-      Configuration conf_1 = createBasicConfig();
-      conf_1.setSecurityEnabled(false);
-      conf_1.setJMXManagementEnabled(true);
-      conf_1.getAcceptorConfigurations().add(acceptorConfig);
-      conf_1.getQueueConfigurations().add(targetQueueConfig);
-
-      Configuration conf_0 = createBasicConfig();
-      conf_0.setSecurityEnabled(false);
-      conf_0.setJMXManagementEnabled(true);
-      conf_0.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
-      conf_0.getConnectorConfigurations().put(connectorConfig.getName(), connectorConfig);
-      conf_0.getQueueConfigurations().add(sourceQueueConfig);
-      conf_0.getBridgeConfigurations().add(bridgeConfig);
+      bridgeConfig = new BridgeConfiguration()
+         .setName(RandomUtil.randomString())
+         .setQueueName(sourceQueueConfig.getName())
+         .setForwardingAddress(targetQueueConfig.getAddress())
+         .setRetryInterval(RandomUtil.randomPositiveLong())
+         .setRetryIntervalMultiplier(RandomUtil.randomDouble())
+         .setInitialConnectAttempts(RandomUtil.randomPositiveInt())
+         .setReconnectAttempts(RandomUtil.randomPositiveInt())
+         .setReconnectAttemptsOnSameNode(RandomUtil.randomPositiveInt())
+         .setUseDuplicateDetection(RandomUtil.randomBoolean())
+         .setConfirmationWindowSize(RandomUtil.randomPositiveInt())
+         .setStaticConnectors(connectors);
+
+      Configuration conf_1 = createBasicConfig()
+         .addAcceptorConfiguration(acceptorConfig)
+         .addQueueConfiguration(targetQueueConfig);
+
+      Configuration conf_0 = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY))
+         .addConnectorConfiguration(connectorConfig.getName(), connectorConfig)
+         .addQueueConfiguration(sourceQueueConfig)
+         .addBridgeConfiguration(bridgeConfig);
 
       server_1 = addServer(HornetQServers.newHornetQServer(conf_1, MBeanServerFactory.createMBeanServer(), false));
       server_1.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BroadcastGroupControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BroadcastGroupControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BroadcastGroupControlTest.java
index 026ffe2..9c4364e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BroadcastGroupControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/BroadcastGroupControlTest.java
@@ -42,10 +42,14 @@ public class BroadcastGroupControlTest extends ManagementTestBase
 
    public static BroadcastGroupConfiguration randomBroadcastGroupConfiguration(final List<String> connectorInfos)
    {
-      return new BroadcastGroupConfiguration(RandomUtil.randomString(),
-                                             RandomUtil.randomPositiveInt(),
-                                             connectorInfos,
-                                             new UDPBroadcastGroupConfiguration("231.7.7.7", 1199, null, 1198));
+      return new BroadcastGroupConfiguration()
+         .setName(RandomUtil.randomString())
+         .setBroadcastPeriod(RandomUtil.randomPositiveInt())
+         .setConnectorInfos(connectorInfos)
+         .setEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+            .setGroupAddress("231.7.7.7")
+            .setGroupPort(1199)
+            .setLocalBindPort(1198));
    }
 
    public static Pair<String, String> randomPair()
@@ -65,12 +69,10 @@ public class BroadcastGroupControlTest extends ManagementTestBase
       connectorInfos.add(connectorConfiguration.getName());
       BroadcastGroupConfiguration broadcastGroupConfig = BroadcastGroupControlTest.randomBroadcastGroupConfiguration(connectorInfos);
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getConnectorConfigurations().put(connectorConfiguration.getName(), connectorConfiguration);
-      conf.getBroadcastGroupConfigurations().add(broadcastGroupConfig);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf = createBasicConfig()
+         .addConnectorConfiguration(connectorConfiguration.getName(), connectorConfiguration)
+         .addBroadcastGroupConfiguration(broadcastGroupConfig)
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       service = addServer(HornetQServers.newHornetQServer(conf, mbeanServer, false));
       service.start();
 
@@ -105,12 +107,10 @@ public class BroadcastGroupControlTest extends ManagementTestBase
       connectorInfos.add(connectorConfiguration.getName());
       BroadcastGroupConfiguration broadcastGroupConfig = BroadcastGroupControlTest.randomBroadcastGroupConfiguration(connectorInfos);
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getConnectorConfigurations().put(connectorConfiguration.getName(), connectorConfiguration);
-      conf.getBroadcastGroupConfigurations().add(broadcastGroupConfig);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf = createBasicConfig()
+         .addConnectorConfiguration(connectorConfiguration.getName(), connectorConfiguration)
+         .addBroadcastGroupConfiguration(broadcastGroupConfig)
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       service = addServer(HornetQServers.newHornetQServer(conf, mbeanServer, false));
       service.start();
 


[49/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/replicated/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/replicated/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/replicated/hornetq-jms.xml
new file mode 100644
index 0000000..044d7e8
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/replicated/hornetq-jms.xml
@@ -0,0 +1,53 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
+
+   <connection-factory name="NettyXAConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/XAConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/ConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/XAThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/ThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+
+   <queue name="DLQ">
+      <entry name="/queue/DLQ"/>
+   </queue>
+   
+   <queue name="ExpiryQueue">
+      <entry name="/queue/ExpiryQueue"/>
+   </queue>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/replicated/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/replicated/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/replicated/hornetq-users.xml
new file mode 100644
index 0000000..934306c
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/replicated/hornetq-users.xml
@@ -0,0 +1,7 @@
+<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
+   <!-- the default user.  this is used where username is null-->
+   <defaultuser name="guest" password="guest">
+      <role name="guest"/>
+   </defaultuser>
+</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/replicated/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/replicated/jndi.properties b/distribution/hornetq/src/main/resources/config/replicated/jndi.properties
new file mode 100644
index 0000000..e2a9832
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/replicated/jndi.properties
@@ -0,0 +1,2 @@
+java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
+java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/shared-store/bootstrap.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/shared-store/bootstrap.xml b/distribution/hornetq/src/main/resources/config/shared-store/bootstrap.xml
new file mode 100644
index 0000000..9834d3b
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/shared-store/bootstrap.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ Copyright 2005-2014 Red Hat, Inc.
+ Red Hat licenses this file to you under the Apache License, version
+ 2.0 (the "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+    http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied.  See the License for the specific language governing
+ permissions and limitations under the License.
+-->
+
+<broker xmlns="http://hornetq.org/schema">
+
+   <core configuration="file:${hornetq.home}/config/shared-store/hornetq-configuration.xml"></core>
+   <jms configuration="file:${hornetq.home}/config/shared-store/hornetq-jms.xml"></jms>
+
+   <basic-security/>
+
+   <naming bindAddress="localhost" port="1099" rmiBindAddress="localhost" rmiPort="1098"/>
+
+</broker>
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/shared-store/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/shared-store/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/shared-store/hornetq-configuration.xml
new file mode 100644
index 0000000..007acc1
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/shared-store/hornetq-configuration.xml
@@ -0,0 +1,104 @@
+<configuration xmlns="urn:hornetq"
+               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
+   <!--
+   if you want to run this as a backup on different ports you would need to set the following variable
+   export CLUSTER_PROPS="-Djnp.port=1199 -Djnp.rmiPort=1198 -Djnp.host=localhost -Dhornetq.remoting.netty.host=localhost -Dhornetq.remoting.netty.port=5545 -Dhornetq.remoting.netty.batch.port=5555 -Dhornetq.backup=true"
+   -->
+
+   <paging-directory>${data.dir:../data}/paging</paging-directory>
+   
+   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
+   
+   <journal-directory>${data.dir:../data}/journal</journal-directory>
+   
+   <journal-min-files>10</journal-min-files>
+   
+   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
+
+   <connectors>      
+      <connector name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </connector>
+      
+      <connector name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+      </connector>
+   </connectors>
+
+   <acceptors>
+      <acceptor name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </acceptor>
+      
+      <acceptor name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+         <param key="direct-deliver" value="false"/>
+      </acceptor>
+   </acceptors>
+
+   <broadcast-groups>
+      <broadcast-group name="bg-group1">
+         <group-address>231.7.7.7</group-address>
+         <group-port>9876</group-port>
+         <broadcast-period>5000</broadcast-period>
+         <connector-ref>netty</connector-ref>
+      </broadcast-group>
+   </broadcast-groups>
+
+   <discovery-groups>
+      <discovery-group name="dg-group1">
+         <group-address>231.7.7.7</group-address>
+         <group-port>9876</group-port>
+         <refresh-timeout>10000</refresh-timeout>
+      </discovery-group>
+   </discovery-groups>
+   
+   <cluster-connections>
+      <cluster-connection name="my-cluster">
+         <address>jms</address>	 
+         <connector-ref>netty</connector-ref>
+	      <discovery-group-ref discovery-group-name="dg-group1"/>
+      </cluster-connection>
+   </cluster-connections>
+
+   <ha-policy>
+      <shared-store>
+         <master/>
+      </shared-store>
+   </ha-policy>
+   
+   <security-settings>
+      <security-setting match="#">
+         <permission type="createNonDurableQueue" roles="guest"/>
+         <permission type="deleteNonDurableQueue" roles="guest"/>
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+      </security-setting>
+   </security-settings>
+
+   <address-settings>
+      <!--default for catch all-->
+      <address-setting match="#">
+         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
+         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
+         <redelivery-delay>0</redelivery-delay>
+         <max-size-bytes>10485760</max-size-bytes>       
+         <message-counter-history-day-limit>10</message-counter-history-day-limit>
+         <address-full-policy>BLOCK</address-full-policy>
+      </address-setting>
+   </address-settings>
+
+   
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/shared-store/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/shared-store/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/shared-store/hornetq-jms.xml
new file mode 100644
index 0000000..044d7e8
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/shared-store/hornetq-jms.xml
@@ -0,0 +1,53 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
+
+   <connection-factory name="NettyXAConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/XAConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/ConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/XAThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/ThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+
+   <queue name="DLQ">
+      <entry name="/queue/DLQ"/>
+   </queue>
+   
+   <queue name="ExpiryQueue">
+      <entry name="/queue/ExpiryQueue"/>
+   </queue>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/shared-store/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/shared-store/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/shared-store/hornetq-users.xml
new file mode 100644
index 0000000..934306c
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/shared-store/hornetq-users.xml
@@ -0,0 +1,7 @@
+<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
+   <!-- the default user.  this is used where username is null-->
+   <defaultuser name="guest" password="guest">
+      <role name="guest"/>
+   </defaultuser>
+</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/shared-store/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/shared-store/jndi.properties b/distribution/hornetq/src/main/resources/config/shared-store/jndi.properties
new file mode 100644
index 0000000..e2a9832
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/shared-store/jndi.properties
@@ -0,0 +1,2 @@
+java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
+java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-beans.xml b/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-beans.xml
deleted file mode 100644
index 423c8cb..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-beans.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   </bean>
-
-    <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The Stand alone server that controls the jndi server-->
-   <bean name="StandaloneServer" class="org.hornetq.jms.server.impl.StandaloneNamingServer">
-      <constructor>
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-      <property name="port">${jnp.port:1099}</property>
-      <property name="bindAddress">${jnp.host:localhost}</property>
-      <property name="rmiPort">${jnp.rmiPort:1098}</property>
-      <property name="rmiBindAddress">${jnp.host:localhost}</property>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-  
-   
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-configuration.xml
deleted file mode 100644
index 474d507..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-configuration.xml
+++ /dev/null
@@ -1,94 +0,0 @@
-<configuration xmlns="urn:hornetq"
-               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-   
-   <paging-directory>${data.dir:../data}/paging</paging-directory>
-   
-   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
-   
-   <journal-directory>${data.dir:../data}/journal</journal-directory>
-   
-   <journal-min-files>10</journal-min-files>
-   
-   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
-
-   <connectors>      
-      <connector name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </connector>
-      
-      <connector name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-      </connector>
-   </connectors>
-
-   <acceptors>
-      <acceptor name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </acceptor>
-      
-      <acceptor name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-         <param key="direct-deliver" value="false"/>
-      </acceptor>
-   </acceptors>
-
-   <broadcast-groups>
-      <broadcast-group name="bg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <broadcast-period>5000</broadcast-period>
-         <connector-ref>netty</connector-ref>
-      </broadcast-group>
-   </broadcast-groups>
-
-   <discovery-groups>
-      <discovery-group name="dg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <refresh-timeout>10000</refresh-timeout>
-      </discovery-group>
-   </discovery-groups>
-   
-   <cluster-connections>
-      <cluster-connection name="my-cluster">
-         <address>jms</address>	 
-         <connector-ref>netty</connector-ref>
-	      <discovery-group-ref discovery-group-name="dg-group1"/>
-      </cluster-connection>
-   </cluster-connections>
-   
-   <security-settings>
-      <security-setting match="#">
-         <permission type="createNonDurableQueue" roles="guest"/>
-         <permission type="deleteNonDurableQueue" roles="guest"/>
-         <permission type="consume" roles="guest"/>
-         <permission type="send" roles="guest"/>
-      </security-setting>
-   </security-settings>
-
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-
-   
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-jms.xml
deleted file mode 100644
index 044d7e8..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-jms.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-
-   <connection-factory name="NettyXAConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/ConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/XAThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/ThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-
-   <queue name="DLQ">
-      <entry name="/queue/DLQ"/>
-   </queue>
-   
-   <queue name="ExpiryQueue">
-      <entry name="/queue/ExpiryQueue"/>
-   </queue>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/clustered/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/jndi.properties b/distribution/hornetq/src/main/resources/config/stand-alone/clustered/jndi.properties
deleted file mode 100644
index e2a9832..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/jndi.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/clustered/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/logging.properties b/distribution/hornetq/src/main/resources/config/stand-alone/clustered/logging.properties
deleted file mode 100644
index 3b725af..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/clustered/logging.properties
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# JBoss, Home of Professional Open Source.
-# Copyright 2010, Red Hat, Inc., and individual contributors
-# as indicated by the @author tags. See the copyright.txt file 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.
-#
-
-# Additional logger names to configure (root logger is always configured)
-# Root logger option
-loggers=org.jboss.logging,org.hornetq.core.server,org.hornetq.utils,org.hornetq.journal,org.hornetq.jms,org.hornetq.integration.bootstrap
-
-# Root logger level
-logger.level=INFO
-# HornetQ logger levels
-logger.org.hornetq.core.server.level=INFO
-logger.org.hornetq.journal.level=INFO
-logger.org.hornetq.utils.level=INFO
-logger.org.hornetq.jms.level=INFO
-logger.org.hornetq.integration.bootstrap.level=INFO
-# Root logger handlers
-logger.handlers=FILE,CONSOLE
-
-# Console handler configuration
-handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
-handler.CONSOLE.properties=autoFlush
-handler.CONSOLE.level=DEBUG
-handler.CONSOLE.autoFlush=true
-handler.CONSOLE.formatter=PATTERN
-
-# File handler configuration
-handler.FILE=org.jboss.logmanager.handlers.FileHandler
-handler.FILE.level=DEBUG
-handler.FILE.properties=autoFlush,fileName
-handler.FILE.autoFlush=true
-handler.FILE.fileName=logs/hornetq.log
-handler.FILE.formatter=PATTERN
-
-# Formatter pattern configuration
-formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
-formatter.PATTERN.properties=pattern
-formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-beans.xml b/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-beans.xml
deleted file mode 100644
index 2cbcb12..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-beans.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   </bean>
-
-    <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The Stand alone server that controls the jndi server-->
-   <bean name="StandaloneServer" class="org.hornetq.jms.server.impl.StandaloneNamingServer">
-      <constructor>
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-      <property name="port">${jnp.port:1099}</property>
-      <property name="bindAddress">${jnp.host:localhost}</property>
-      <property name="rmiPort">${jnp.rmiPort:1098}</property>
-      <property name="rmiBindAddress">${jnp.host:localhost}</property>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-  
-   
-</deployment>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-configuration.xml
deleted file mode 100644
index 8b0922d..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-configuration.xml
+++ /dev/null
@@ -1,67 +0,0 @@
-<configuration xmlns="urn:hornetq"
-               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-
-   <paging-directory>${data.dir:../data}/paging</paging-directory>
-   
-   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
-   
-   <journal-directory>${data.dir:../data}/journal</journal-directory>
-   
-   <journal-min-files>10</journal-min-files>
-   
-   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
-   
-   <connectors>
-      <connector name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </connector>
-      
-      <connector name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-      </connector>
-   </connectors>
-
-   <acceptors>
-      <acceptor name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </acceptor>
-      
-      <acceptor name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-         <param key="direct-deliver" value="false"/>
-      </acceptor>
-   </acceptors>
-
-   <security-settings>
-      <security-setting match="#">
-         <permission type="createNonDurableQueue" roles="guest"/>
-         <permission type="deleteNonDurableQueue" roles="guest"/>
-         <permission type="consume" roles="guest"/>
-         <permission type="send" roles="guest"/>
-      </security-setting>
-   </security-settings>
-
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-jms.xml
deleted file mode 100644
index 044d7e8..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-jms.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-
-   <connection-factory name="NettyXAConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/ConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/XAThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/ThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-
-   <queue name="DLQ">
-      <entry name="/queue/DLQ"/>
-   </queue>
-   
-   <queue name="ExpiryQueue">
-      <entry name="/queue/ExpiryQueue"/>
-   </queue>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/jndi.properties b/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/jndi.properties
deleted file mode 100644
index e2a9832..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/jndi.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/logging.properties b/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/logging.properties
deleted file mode 100644
index e9b2580..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/non-clustered/logging.properties
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# JBoss, Home of Professional Open Source.
-# Copyright 2010, Red Hat, Inc., and individual contributors
-# as indicated by the @author tags. See the copyright.txt file 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.
-#
-
-# Additional logger names to configure (root logger is always configured)
-# Root logger option
-loggers=org.jboss.logging,org.hornetq.core.server,org.hornetq.utils,org.hornetq.journal,org.hornetq.jms,org.hornetq.integration.bootstrap
-
-# Root logger level
-logger.level=INFO
-# HornetQ logger levels
-logger.org.hornetq.core.server.level=INFO
-logger.org.hornetq.journal.level=INFO
-logger.org.hornetq.utils.level=INFO
-logger.org.hornetq.jms.level=INFO
-logger.org.hornetq.integration.bootstrap.level=INFO
-# Root logger handlers
-logger.handlers=FILE,CONSOLE
-
-# Console handler configuration
-handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
-handler.CONSOLE.properties=autoFlush
-handler.CONSOLE.level=FINE
-handler.CONSOLE.autoFlush=true
-handler.CONSOLE.formatter=PATTERN
-
-# File handler configuration
-handler.FILE=org.jboss.logmanager.handlers.FileHandler
-handler.FILE.level=FINE
-handler.FILE.properties=autoFlush,fileName
-handler.FILE.autoFlush=true
-handler.FILE.fileName=logs/hornetq.log
-handler.FILE.formatter=PATTERN
-
-# Formatter pattern configuration
-formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
-formatter.PATTERN.properties=pattern
-formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-beans.xml b/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-beans.xml
deleted file mode 100644
index 423c8cb..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-beans.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   </bean>
-
-    <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The Stand alone server that controls the jndi server-->
-   <bean name="StandaloneServer" class="org.hornetq.jms.server.impl.StandaloneNamingServer">
-      <constructor>
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-      <property name="port">${jnp.port:1099}</property>
-      <property name="bindAddress">${jnp.host:localhost}</property>
-      <property name="rmiPort">${jnp.rmiPort:1098}</property>
-      <property name="rmiBindAddress">${jnp.host:localhost}</property>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-  
-   
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-configuration.xml
deleted file mode 100644
index 5605f00..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-configuration.xml
+++ /dev/null
@@ -1,101 +0,0 @@
-<configuration xmlns="urn:hornetq"
-               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-   <!--
-   if you want to run this as a backup on different ports you would need to set the following variable
-   export CLUSTER_PROPS="-Djnp.port=1199 -Djnp.rmiPort=1198 -Djnp.host=localhost -Dhornetq.remoting.netty.host=localhost -Dhornetq.remoting.netty.port=5545 -Dhornetq.remoting.netty.batch.port=5555 -Dhornetq.backup=true"
-   -->
-   <shared-store>false</shared-store>
-
-   <backup>${hornetq.backup:false}</backup>
-
-   <paging-directory>${data.dir:../data}/paging</paging-directory>
-   
-   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
-   
-   <journal-directory>${data.dir:../data}/journal</journal-directory>
-   
-   <journal-min-files>10</journal-min-files>
-   
-   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
-
-   <connectors>      
-      <connector name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </connector>
-      
-      <connector name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-      </connector>
-   </connectors>
-
-   <acceptors>
-      <acceptor name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </acceptor>
-      
-      <acceptor name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-         <param key="direct-deliver" value="false"/>
-      </acceptor>
-   </acceptors>
-
-   <broadcast-groups>
-      <broadcast-group name="bg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <broadcast-period>5000</broadcast-period>
-         <connector-ref>netty</connector-ref>
-      </broadcast-group>
-   </broadcast-groups>
-
-   <discovery-groups>
-      <discovery-group name="dg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <refresh-timeout>10000</refresh-timeout>
-      </discovery-group>
-   </discovery-groups>
-   
-   <cluster-connections>
-      <cluster-connection name="my-cluster">
-         <address>jms</address>	 
-         <connector-ref>netty</connector-ref>
-	      <discovery-group-ref discovery-group-name="dg-group1"/>
-      </cluster-connection>
-   </cluster-connections>
-   
-   <security-settings>
-      <security-setting match="#">
-         <permission type="createNonDurableQueue" roles="guest"/>
-         <permission type="deleteNonDurableQueue" roles="guest"/>
-         <permission type="consume" roles="guest"/>
-         <permission type="send" roles="guest"/>
-      </security-setting>
-   </security-settings>
-
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-
-   
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-jms.xml
deleted file mode 100644
index 044d7e8..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-jms.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-
-   <connection-factory name="NettyXAConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/ConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/XAThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/ThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-
-   <queue name="DLQ">
-      <entry name="/queue/DLQ"/>
-   </queue>
-   
-   <queue name="ExpiryQueue">
-      <entry name="/queue/ExpiryQueue"/>
-   </queue>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/replicated/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/jndi.properties b/distribution/hornetq/src/main/resources/config/stand-alone/replicated/jndi.properties
deleted file mode 100644
index e2a9832..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/jndi.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/replicated/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/logging.properties b/distribution/hornetq/src/main/resources/config/stand-alone/replicated/logging.properties
deleted file mode 100644
index 3b725af..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/replicated/logging.properties
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# JBoss, Home of Professional Open Source.
-# Copyright 2010, Red Hat, Inc., and individual contributors
-# as indicated by the @author tags. See the copyright.txt file 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.
-#
-
-# Additional logger names to configure (root logger is always configured)
-# Root logger option
-loggers=org.jboss.logging,org.hornetq.core.server,org.hornetq.utils,org.hornetq.journal,org.hornetq.jms,org.hornetq.integration.bootstrap
-
-# Root logger level
-logger.level=INFO
-# HornetQ logger levels
-logger.org.hornetq.core.server.level=INFO
-logger.org.hornetq.journal.level=INFO
-logger.org.hornetq.utils.level=INFO
-logger.org.hornetq.jms.level=INFO
-logger.org.hornetq.integration.bootstrap.level=INFO
-# Root logger handlers
-logger.handlers=FILE,CONSOLE
-
-# Console handler configuration
-handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
-handler.CONSOLE.properties=autoFlush
-handler.CONSOLE.level=DEBUG
-handler.CONSOLE.autoFlush=true
-handler.CONSOLE.formatter=PATTERN
-
-# File handler configuration
-handler.FILE=org.jboss.logmanager.handlers.FileHandler
-handler.FILE.level=DEBUG
-handler.FILE.properties=autoFlush,fileName
-handler.FILE.autoFlush=true
-handler.FILE.fileName=logs/hornetq.log
-handler.FILE.formatter=PATTERN
-
-# Formatter pattern configuration
-formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
-formatter.PATTERN.properties=pattern
-formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-beans.xml b/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-beans.xml
deleted file mode 100644
index 423c8cb..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-beans.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   </bean>
-
-    <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The Stand alone server that controls the jndi server-->
-   <bean name="StandaloneServer" class="org.hornetq.jms.server.impl.StandaloneNamingServer">
-      <constructor>
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-      <property name="port">${jnp.port:1099}</property>
-      <property name="bindAddress">${jnp.host:localhost}</property>
-      <property name="rmiPort">${jnp.rmiPort:1098}</property>
-      <property name="rmiBindAddress">${jnp.host:localhost}</property>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-  
-   
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-configuration.xml
deleted file mode 100644
index dea7a7b..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-configuration.xml
+++ /dev/null
@@ -1,101 +0,0 @@
-<configuration xmlns="urn:hornetq"
-               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-   <!--
-   if you want to run this as a backup on different ports you would need to set the following variable
-   export CLUSTER_PROPS="-Djnp.port=1199 -Djnp.rmiPort=1198 -Djnp.host=localhost -Dhornetq.remoting.netty.host=localhost -Dhornetq.remoting.netty.port=5545 -Dhornetq.remoting.netty.batch.port=5555 -Dhornetq.backup=true"
-   -->
-   <shared-store>true</shared-store>
-
-   <backup>${hornetq.backup:false}</backup>
-
-   <paging-directory>${data.dir:../data}/paging</paging-directory>
-   
-   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
-   
-   <journal-directory>${data.dir:../data}/journal</journal-directory>
-   
-   <journal-min-files>10</journal-min-files>
-   
-   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
-
-   <connectors>      
-      <connector name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </connector>
-      
-      <connector name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-      </connector>
-   </connectors>
-
-   <acceptors>
-      <acceptor name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </acceptor>
-      
-      <acceptor name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-         <param key="direct-deliver" value="false"/>
-      </acceptor>
-   </acceptors>
-
-   <broadcast-groups>
-      <broadcast-group name="bg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <broadcast-period>5000</broadcast-period>
-         <connector-ref>netty</connector-ref>
-      </broadcast-group>
-   </broadcast-groups>
-
-   <discovery-groups>
-      <discovery-group name="dg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <refresh-timeout>10000</refresh-timeout>
-      </discovery-group>
-   </discovery-groups>
-   
-   <cluster-connections>
-      <cluster-connection name="my-cluster">
-         <address>jms</address>	 
-         <connector-ref>netty</connector-ref>
-	      <discovery-group-ref discovery-group-name="dg-group1"/>
-      </cluster-connection>
-   </cluster-connections>
-   
-   <security-settings>
-      <security-setting match="#">
-         <permission type="createNonDurableQueue" roles="guest"/>
-         <permission type="deleteNonDurableQueue" roles="guest"/>
-         <permission type="consume" roles="guest"/>
-         <permission type="send" roles="guest"/>
-      </security-setting>
-   </security-settings>
-
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-
-   
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-jms.xml
deleted file mode 100644
index 044d7e8..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-jms.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-
-   <connection-factory name="NettyXAConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/ConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/XAThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>false</xa>
-      <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-      </connectors>
-      <entries>
-         <entry name="/ThroughputConnectionFactory"/>
-      </entries>
-   </connection-factory>
-
-   <queue name="DLQ">
-      <entry name="/queue/DLQ"/>
-   </queue>
-   
-   <queue name="ExpiryQueue">
-      <entry name="/queue/ExpiryQueue"/>
-   </queue>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/jndi.properties b/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/jndi.properties
deleted file mode 100644
index e2a9832..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/jndi.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/logging.properties b/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/logging.properties
deleted file mode 100644
index 3b725af..0000000
--- a/distribution/hornetq/src/main/resources/config/stand-alone/shared-store/logging.properties
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# JBoss, Home of Professional Open Source.
-# Copyright 2010, Red Hat, Inc., and individual contributors
-# as indicated by the @author tags. See the copyright.txt file 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.
-#
-
-# Additional logger names to configure (root logger is always configured)
-# Root logger option
-loggers=org.jboss.logging,org.hornetq.core.server,org.hornetq.utils,org.hornetq.journal,org.hornetq.jms,org.hornetq.integration.bootstrap
-
-# Root logger level
-logger.level=INFO
-# HornetQ logger levels
-logger.org.hornetq.core.server.level=INFO
-logger.org.hornetq.journal.level=INFO
-logger.org.hornetq.utils.level=INFO
-logger.org.hornetq.jms.level=INFO
-logger.org.hornetq.integration.bootstrap.level=INFO
-# Root logger handlers
-logger.handlers=FILE,CONSOLE
-
-# Console handler configuration
-handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
-handler.CONSOLE.properties=autoFlush
-handler.CONSOLE.level=DEBUG
-handler.CONSOLE.autoFlush=true
-handler.CONSOLE.formatter=PATTERN
-
-# File handler configuration
-handler.FILE=org.jboss.logmanager.handlers.FileHandler
-handler.FILE.level=DEBUG
-handler.FILE.properties=autoFlush,fileName
-handler.FILE.autoFlush=true
-handler.FILE.fileName=logs/hornetq.log
-handler.FILE.formatter=PATTERN
-
-# Formatter pattern configuration
-formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
-formatter.PATTERN.properties=pattern
-formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-beans.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-beans.xml
deleted file mode 100644
index 9705de0..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-beans.xml
+++ /dev/null
@@ -1,74 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<!--
-  ~ Copyright 2009 Red Hat, Inc.
-  ~  Red Hat licenses this file to you under the Apache License, version
-  ~  2.0 (the "License"); you may not use this file except in compliance
-  ~  with the License.  You may obtain a copy of the License at
-  ~     http://www.apache.org/licenses/LICENSE-2.0
-  ~  Unless required by applicable law or agreed to in writing, software
-  ~  distributed under the License is distributed on an "AS IS" BASIS,
-  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-  ~  implied.  See the License for the specific language governing
-  ~  permissions and limitations under the License.
-  -->
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">${jnp.port:1199}</property>
-      <property name="bindAddress">${jnp.host:localhost}</property>
-      <property name="rmiPort">${jnp.rmiPort:1198}</property>
-      <property name="rmiBindAddress">${jnp.host:localhost}</property>
-   </bean>
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   </bean>
-
-    <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-  
-   
-</deployment>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-configuration.xml
deleted file mode 100644
index f0a2dc2..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-configuration.xml
+++ /dev/null
@@ -1,88 +0,0 @@
-<!--
-  ~ Copyright 2009 Red Hat, Inc.
-  ~  Red Hat licenses this file to you under the Apache License, version
-  ~  2.0 (the "License"); you may not use this file except in compliance
-  ~  with the License.  You may obtain a copy of the License at
-  ~     http://www.apache.org/licenses/LICENSE-2.0
-  ~  Unless required by applicable law or agreed to in writing, software
-  ~  distributed under the License is distributed on an "AS IS" BASIS,
-  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-  ~  implied.  See the License for the specific language governing
-  ~  permissions and limitations under the License.
-  -->
-
-<configuration xmlns="urn:hornetq"
-	       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	       xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-
-    <backup>true</backup>
-
-    <allow-failback>true</allow-failback>
-
-    <shared-store>true</shared-store>
-	
-	<journal-min-files>10</journal-min-files>
-	
-	<connectors>      
-		<connector name="netty">
-			<factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-			<param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-			<param key="port"  value="${hornetq.remoting.netty.port:5446}"/>
-		</connector>
-	</connectors>
-	
-	<acceptors>
-		<acceptor name="netty">
-			<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-			<param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-			<param key="port"  value="${hornetq.remoting.netty.port:5446}"/>
-		</acceptor>
-	</acceptors>
-	
-	<broadcast-groups>
-		<broadcast-group name="bg-group1">
-			<group-address>231.7.7.7</group-address>
-			<group-port>9876</group-port>
-			<broadcast-period>5000</broadcast-period>
-         <connector-ref>netty</connector-ref>
-		</broadcast-group>
-	</broadcast-groups>
-	
-	<discovery-groups>
-		<discovery-group name="dg-group1">
-			<group-address>231.7.7.7</group-address>
-			<group-port>9876</group-port>
-			<refresh-timeout>60000</refresh-timeout>
-		</discovery-group>
-	</discovery-groups>
-	
-	<cluster-connections>
-		<cluster-connection name="my-cluster">
-			<address>jms</address>	 
-                <connector-ref>netty</connector-ref>
-			<discovery-group-ref discovery-group-name="dg-group1"/>
-		</cluster-connection>
-	</cluster-connections>
-	
-	<security-settings>
-		<security-setting match="#">
-			<permission type="createNonDurableQueue" roles="guest"/>
-			<permission type="deleteNonDurableQueue" roles="guest"/>
-			<permission type="consume" roles="guest"/>
-			<permission type="send" roles="guest"/>
-		</security-setting>
-	</security-settings>
-	
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-	
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-jms.xml
deleted file mode 100644
index 3346589..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-jms.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<configuration xmlns="urn:hornetq"
-	       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	       xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-	
-	<connection-factory name="ConnectionFactory">
-	   <connectors>
-         <connector-ref connector-name="netty"/>
-	   </connectors>
-		<entries>
-			<entry name="/ConnectionFactory"/>
-			<entry name="/XAConnectionFactory"/>
-		</entries>
-	</connection-factory>
-	
-	<queue name="DLQ">
-		<entry name="/queue/DLQ"/>
-	</queue>
-	<queue name="ExpiryQueue">
-		<entry name="/queue/ExpiryQueue"/>
-	</queue>   
-	<queue name="ExampleQueue">
-		<entry name="/queue/ExampleQueue"/>
-	</queue>
-	<topic name="ExampleTopic">
-		<entry name="/topic/ExampleTopic"/>
-	</topic>
-	
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/jndi.properties b/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/jndi.properties
deleted file mode 100644
index 629072e..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/jndi.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright 2009 Red Hat, Inc.
-#  Red Hat licenses this file to you under the Apache License, version
-#  2.0 (the "License"); you may not use this file except in compliance
-#  with the License.  You may obtain a copy of the License at
-#     http://www.apache.org/licenses/LICENSE-2.0
-#  Unless required by applicable law or agreed to in writing, software
-#  distributed under the License is distributed on an "AS IS" BASIS,
-#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-#  implied.  See the License for the specific language governing
-#  permissions and limitations under the License.
-#
-
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/logging.properties b/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/logging.properties
deleted file mode 100644
index dd49ead..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered-backup/logging.properties
+++ /dev/null
@@ -1,34 +0,0 @@
-############################################################
-#  	Default Logging Configuration File
-#
-# You can use a different file by specifying a filename
-# with the java.util.logging.config.file system property.
-# For example java -Djava.util.logging.config.file=myfile
-############################################################
-
-############################################################
-#  	Global properties
-############################################################
-
-# "handlers" specifies a comma separated list of log Handler
-# classes.  These handlers will be installed during VM startup.
-# Note that these classes must be on the system classpath.
-# By default we only configure a ConsoleHandler, which will only
-# show messages at the INFO and above levels.
-handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler
-java.util.logging.ConsoleHandler.formatter=org.hornetq.integration.logging.HornetQLoggerFormatter
-java.util.logging.FileHandler.level=INFO
-java.util.logging.FileHandler.pattern=logs/hornetq.log
-java.util.logging.FileHandler.formatter=org.hornetq.integration.logging.HornetQLoggerFormatter
-# Default global logging level.
-# This specifies which kinds of events are logged across
-# all loggers.  For any given facility this global level
-# can be overriden by a facility specific level
-# Note that the ConsoleHandler also has a separate level
-# setting to limit messages printed to the console.
-.level= INFO
-
-############################################################
-# Handler specific properties.
-# Describes specific configuration info for Handlers.
-############################################################

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-beans.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-beans.xml
deleted file mode 100644
index 58afc78..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-beans.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">${jnp.port:1099}</property>
-      <property name="bindAddress">${jnp.host:localhost}</property>
-      <property name="rmiPort">${jnp.rmiPort:1098}</property>
-      <property name="rmiBindAddress">${jnp.host:localhost}</property>
-   </bean>
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   </bean>
-
-    <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-    <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-  
-   
-</deployment>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-configuration.xml
deleted file mode 100644
index 41fe395..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-configuration.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-<configuration xmlns="urn:hornetq"
-	       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	       xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-
-    <failover-on-shutdown>false</failover-on-shutdown>
-
-    <shared-store>true</shared-store>
-	
-	<journal-min-files>10</journal-min-files>
-	
-	<connectors>      
-		<connector name="netty">
-			<factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-			<param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-			<param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-		</connector>
-	</connectors>
-	
-	<acceptors>
-		<acceptor name="netty">
-			<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-			<param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-			<param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-		</acceptor>
-	</acceptors>
-	
-	<broadcast-groups>
-		<broadcast-group name="bg-group1">
-			<group-address>231.7.7.7</group-address>
-			<group-port>9876</group-port>
-			<broadcast-period>5000</broadcast-period>
-         <connector-ref>netty</connector-ref>
-		</broadcast-group>
-	</broadcast-groups>
-	
-	<discovery-groups>
-		<discovery-group name="dg-group1">
-			<group-address>231.7.7.7</group-address>
-			<group-port>9876</group-port>
-			<refresh-timeout>60000</refresh-timeout>
-		</discovery-group>
-	</discovery-groups>
-	
-	<cluster-connections>
-		<cluster-connection name="my-cluster">
-			<address>jms</address>	 
-         <connector-ref>netty</connector-ref>
-			<discovery-group-ref discovery-group-name="dg-group1"/>
-		</cluster-connection>
-	</cluster-connections>
-	
-	<security-settings>
-		<security-setting match="#">
-			<permission type="createNonDurableQueue" roles="guest"/>
-			<permission type="deleteNonDurableQueue" roles="guest"/>
-			<permission type="consume" roles="guest"/>
-			<permission type="send" roles="guest"/>
-		</security-setting>
-	</security-settings>
-	
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-	
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-jms.xml
deleted file mode 100644
index 3346589..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-jms.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<configuration xmlns="urn:hornetq"
-	       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	       xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-	
-	<connection-factory name="ConnectionFactory">
-	   <connectors>
-         <connector-ref connector-name="netty"/>
-	   </connectors>
-		<entries>
-			<entry name="/ConnectionFactory"/>
-			<entry name="/XAConnectionFactory"/>
-		</entries>
-	</connection-factory>
-	
-	<queue name="DLQ">
-		<entry name="/queue/DLQ"/>
-	</queue>
-	<queue name="ExpiryQueue">
-		<entry name="/queue/ExpiryQueue"/>
-	</queue>   
-	<queue name="ExampleQueue">
-		<entry name="/queue/ExampleQueue"/>
-	</queue>
-	<topic name="ExampleTopic">
-		<entry name="/topic/ExampleTopic"/>
-	</topic>
-	
-</configuration>
\ No newline at end of file


[02/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer7Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer7Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer7Test.java
new file mode 100644
index 0000000..a3cb991
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer7Test.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.ActiveMQConnection;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer7Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public int ackMode;
+   public byte destinationType;
+
+   public JMSConsumer7Test(int deliveryMode, int ackMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.ackMode = ackMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testMessageListenerOnMessageCloseUnackedWithPrefetch1StayInQueue() throws Exception
+   {
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch sendDone = new CountDownLatch(1);
+      final CountDownLatch got2Done = new CountDownLatch(1);
+
+      // Set prefetch to 1
+      connection.getPrefetchPolicy().setAll(1);
+      // This test case does not work if optimized message dispatch is used as
+      // the main thread send block until the consumer receives the
+      // message. This test depends on thread decoupling so that the main
+      // thread can stop the consumer thread.
+      connection.setOptimizedMessageDispatch(false);
+      connection.start();
+
+      // Use all the ack modes
+      Session session = connection.createSession(false, ackMode);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            try
+            {
+               TextMessage tm = (TextMessage) m;
+               assertEquals("" + counter.get(), tm.getText());
+               counter.incrementAndGet();
+               if (counter.get() == 2)
+               {
+                  sendDone.await();
+                  connection.close();
+                  got2Done.countDown();
+               }
+               System.out.println("acking tm: " + tm.getText());
+               tm.acknowledge();
+            }
+            catch (Throwable e)
+            {
+               System.out.println("ack failed!!");
+               e.printStackTrace();
+            }
+         }
+      });
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+      sendDone.countDown();
+
+      // Wait for first 2 messages to arrive.
+      assertTrue(got2Done.await(100000, TimeUnit.MILLISECONDS));
+
+      // Re-start connection.
+      connection = (ActiveMQConnection) factory.createConnection();
+
+      connection.getPrefetchPolicy().setAll(1);
+      connection.start();
+
+      // Pickup the remaining messages.
+      final CountDownLatch done2 = new CountDownLatch(1);
+      session = connection.createSession(false, ackMode);
+      consumer = session.createConsumer(destination);
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            try
+            {
+               TextMessage tm = (TextMessage) m;
+               System.out.println("2nd received: " + tm.getText());
+               // order is not guaranteed as the connection is started before
+               // the listener is set.
+               // assertEquals("" + counter.get(), tm.getText());
+               counter.incrementAndGet();
+               if (counter.get() == 4)
+               {
+                  done2.countDown();
+               }
+            }
+            catch (Throwable e)
+            {
+               System.err.println("Unexpected exception: " + e);
+            }
+         }
+      });
+
+      assertTrue(done2.await(1000, TimeUnit.MILLISECONDS));
+      Thread.sleep(200);
+
+      // assert msg 2 was redelivered as close() from onMessages() will only ack
+      // in auto_ack and dups_ok mode
+      assertEquals(5, counter.get());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer8Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer8Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer8Test.java
new file mode 100644
index 0000000..cfcfce4
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer8Test.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.ActiveMQConnection;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer8Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public int ackMode;
+   public byte destinationType;
+
+   public JMSConsumer8Test(int deliveryMode, int ackMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.ackMode = ackMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testMessageListenerAutoAckOnCloseWithPrefetch1() throws Exception
+   {
+
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch sendDone = new CountDownLatch(1);
+      final CountDownLatch got2Done = new CountDownLatch(1);
+
+      // Set prefetch to 1
+      connection.getPrefetchPolicy().setAll(1);
+      // This test case does not work if optimized message dispatch is used as
+      // the main thread send block until the consumer receives the
+      // message. This test depends on thread decoupling so that the main
+      // thread can stop the consumer thread.
+      connection.setOptimizedMessageDispatch(false);
+      connection.start();
+
+      // Use all the ack modes
+      Session session = connection.createSession(false, ackMode);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            try
+            {
+               TextMessage tm = (TextMessage) m;
+               assertEquals("" + counter.get(), tm.getText());
+               counter.incrementAndGet();
+               m.acknowledge();
+               if (counter.get() == 2)
+               {
+                  sendDone.await();
+                  connection.close();
+                  got2Done.countDown();
+               }
+            }
+            catch (Throwable e)
+            {
+               e.printStackTrace();
+            }
+         }
+      });
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+      sendDone.countDown();
+
+      // Wait for first 2 messages to arrive.
+      assertTrue(got2Done.await(100000, TimeUnit.MILLISECONDS));
+
+      // Re-start connection.
+      connection = (ActiveMQConnection) factory.createConnection();
+
+      connection.getPrefetchPolicy().setAll(1);
+      connection.start();
+
+      // Pickup the remaining messages.
+      final CountDownLatch done2 = new CountDownLatch(1);
+      session = connection.createSession(false, ackMode);
+      consumer = session.createConsumer(destination);
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            try
+            {
+               TextMessage tm = (TextMessage) m;
+               counter.incrementAndGet();
+               if (counter.get() == 4)
+               {
+                  done2.countDown();
+               }
+            }
+            catch (Throwable e)
+            {
+               System.err.println("Unexpected exception " + e);
+            }
+         }
+      });
+
+      assertTrue(done2.await(1000, TimeUnit.MILLISECONDS));
+      Thread.sleep(200);
+
+      // close from onMessage with Auto_ack will ack
+      // Make sure only 4 messages were delivered.
+      assertEquals(4, counter.get());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer9Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer9Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer9Test.java
new file mode 100644
index 0000000..a69e0e3
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer9Test.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Session;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer9Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public byte destinationType;
+
+   public JMSConsumer9Test(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testMessageListenerWithConsumerWithPrefetch1() throws Exception
+   {
+
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch done = new CountDownLatch(1);
+
+      // Receive a message with the JMS API
+      connection.getPrefetchPolicy().setAll(1);
+      connection.start();
+
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            counter.incrementAndGet();
+            if (counter.get() == 4)
+            {
+               done.countDown();
+            }
+         }
+      });
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+
+      assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
+      Thread.sleep(200);
+
+      // Make sure only 4 messages were delivered.
+      assertEquals(4, counter.get());
+   }
+
+   public void testMessageListenerWithConsumer() throws Exception
+   {
+
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch done = new CountDownLatch(1);
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            counter.incrementAndGet();
+            if (counter.get() == 4)
+            {
+               done.countDown();
+            }
+         }
+      });
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+
+      assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
+      Thread.sleep(200);
+
+      // Make sure only 4 messages were delivered.
+      assertEquals(4, counter.get());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java
new file mode 100644
index 0000000..dd1e931
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSDurableTopicRedeliverTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import javax.jms.Message;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JMSDurableTopicRedeliverTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest
+{
+
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      durable = true;
+      super.setUp();
+   }
+
+   /**
+    * Sends and consumes the messages.
+    *
+    * @throws Exception
+    */
+   @Test
+   public void testRedeliverNewSession() throws Exception
+   {
+      String text = "TEST: " + System.currentTimeMillis();
+      Message sendMessage = session.createTextMessage(text);
+
+      if (verbose)
+      {
+         System.out.println("About to send a message: " + sendMessage
+               + " with text: " + text);
+      }
+      producer.send(producerDestination, sendMessage);
+
+      // receive but don't acknowledge
+      Message unackMessage = consumer.receive(1000);
+      assertNotNull(unackMessage);
+      String unackId = unackMessage.getJMSMessageID();
+      assertEquals(((TextMessage) unackMessage).getText(), text);
+      assertFalse(unackMessage.getJMSRedelivered());
+      assertEquals(unackMessage.getIntProperty("JMSXDeliveryCount"), 1);
+      consumeSession.close();
+      consumer.close();
+
+      // receive then acknowledge
+      consumeSession = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      consumer = createConsumer(getName());
+      Message ackMessage = consumer.receive(1000);
+      assertNotNull(ackMessage);
+
+      ackMessage.acknowledge();
+
+      String ackId = ackMessage.getJMSMessageID();
+      assertEquals(((TextMessage) ackMessage).getText(), text);
+      assertEquals(2, ackMessage.getIntProperty("JMSXDeliveryCount"));
+      assertEquals(unackId, ackId);
+      consumeSession.close();
+      consumer.close();
+
+      consumeSession = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      consumer = createConsumer(getName());
+      assertNull(consumer.receive(1000));
+   }
+
+   protected String getName()
+   {
+      return "JMSDurableTopicRedeliverTest";
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSIndividualAckTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSIndividualAckTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSIndividualAckTest.java
new file mode 100644
index 0000000..203ade9
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSIndividualAckTest.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.ActiveMQSession;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JMSIndividualAckTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JMSIndividualAckTest extends BasicOpenWireTest
+{
+
+   /**
+    * Tests if acknowledged messages are being consumed.
+    *
+    * @throws JMSException
+    */
+   @Test
+   public void testAckedMessageAreConsumed() throws JMSException
+   {
+      connection.start();
+      Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
+      Queue queue = (Queue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
+      MessageProducer producer = session.createProducer(queue);
+      producer.send(session.createTextMessage("Hello"));
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg.acknowledge();
+
+      // Reset the session.
+      session.close();
+      session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
+
+      // Attempt to Consume the message...
+      consumer = session.createConsumer(queue);
+      msg = consumer.receive(1000);
+      assertNull(msg);
+
+      session.close();
+   }
+
+   /**
+    * Tests if acknowledged messages are being consumed.
+    *
+    * @throws JMSException
+    */
+   @Test
+   public void testLastMessageAcked() throws JMSException
+   {
+      connection.start();
+      Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
+      Queue queue = (Queue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
+      MessageProducer producer = session.createProducer(queue);
+      TextMessage msg1 = session.createTextMessage("msg1");
+      TextMessage msg2 = session.createTextMessage("msg2");
+      TextMessage msg3 = session.createTextMessage("msg3");
+      producer.send(msg1);
+      producer.send(msg2);
+      producer.send(msg3);
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg.acknowledge();
+
+      // Reset the session.
+      session.close();
+      session = connection.createSession(false,
+            ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
+
+      // Attempt to Consume the message...
+      consumer = session.createConsumer(queue);
+      msg = consumer.receive(1000);
+      assertNotNull(msg);
+      assertEquals(msg1, msg);
+      msg = consumer.receive(1000);
+      assertNotNull(msg);
+      assertEquals(msg2, msg);
+      msg = consumer.receive(1000);
+      assertNull(msg);
+      session.close();
+   }
+
+   /**
+    * Tests if unacknowledged messages are being re-delivered when the consumer
+    * connects again.
+    *
+    * @throws JMSException
+    */
+   @Test
+   public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException
+   {
+      connection.start();
+      Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
+      Queue queue = (Queue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
+      MessageProducer producer = session.createProducer(queue);
+      producer.send(session.createTextMessage("Hello"));
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNotNull(msg);
+      // Don't ack the message.
+
+      // Reset the session. This should cause the unacknowledged message to be
+      // re-delivered.
+      session.close();
+      session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
+
+      // Attempt to Consume the message...
+      consumer = session.createConsumer(queue);
+      msg = consumer.receive(2000);
+      assertNotNull(msg);
+      msg.acknowledge();
+
+      session.close();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSMessageTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSMessageTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSMessageTest.java
new file mode 100644
index 0000000..fccd136
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSMessageTest.java
@@ -0,0 +1,639 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Vector;
+
+import javax.jms.BytesMessage;
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.MapMessage;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageEOFException;
+import javax.jms.MessageProducer;
+import javax.jms.ObjectMessage;
+import javax.jms.Session;
+import javax.jms.StreamMessage;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSMessageTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSMessageTest extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+      });
+   }
+
+   public int deliveryMode = DeliveryMode.NON_PERSISTENT;
+   public byte destinationType = ActiveMQDestination.QUEUE_TYPE;
+   public ActiveMQDestination destination;
+   public boolean durableConsumer;
+
+   public JMSMessageTest(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testTextMessage() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      // Send the message.
+      {
+         TextMessage message = session.createTextMessage();
+         message.setText("Hi");
+         producer.send(message);
+      }
+
+      // Check the Message
+      {
+         TextMessage message = (TextMessage) consumer.receive(1000);
+         assertNotNull(message);
+         assertEquals("Hi", message.getText());
+      }
+
+      assertNull(consumer.receiveNoWait());
+   }
+
+   @Test
+   public void testBytesMessageLength() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      // Send the message
+      {
+         BytesMessage message = session.createBytesMessage();
+         message.writeInt(1);
+         message.writeInt(2);
+         message.writeInt(3);
+         message.writeInt(4);
+         producer.send(message);
+      }
+
+      // Check the message.
+      {
+         BytesMessage message = (BytesMessage) consumer.receive(1000);
+         assertNotNull(message);
+         assertEquals(16, message.getBodyLength());
+      }
+
+      assertNull(consumer.receiveNoWait());
+   }
+
+   @Test
+   public void testObjectMessage() throws Exception
+   {
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      // send the message.
+      {
+         ObjectMessage message = session.createObjectMessage();
+         message.setObject("Hi");
+         producer.send(message);
+      }
+
+      // Check the message
+      {
+         ObjectMessage message = (ObjectMessage) consumer.receive(1000);
+         assertNotNull(message);
+         assertEquals("Hi", message.getObject());
+      }
+      assertNull(consumer.receiveNoWait());
+   }
+
+   @Test
+   public void testBytesMessage() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      // Send the message
+      {
+         BytesMessage message = session.createBytesMessage();
+         message.writeBoolean(true);
+         producer.send(message);
+      }
+
+      // Check the message
+      {
+         BytesMessage message = (BytesMessage) consumer.receive(1000);
+         assertNotNull(message);
+         assertTrue(message.readBoolean());
+
+         try
+         {
+            message.readByte();
+            fail("Expected exception not thrown.");
+         }
+         catch (MessageEOFException e)
+         {
+         }
+
+      }
+      assertNull(consumer.receiveNoWait());
+   }
+
+   @Test
+   public void testStreamMessage() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      // Send the message.
+      {
+         StreamMessage message = session.createStreamMessage();
+         message.writeString("This is a test to see how it works.");
+         producer.send(message);
+      }
+
+      // Check the message.
+      {
+         StreamMessage message = (StreamMessage) consumer.receive(1000);
+         assertNotNull(message);
+
+         // Invalid conversion should throw exception and not move the stream
+         // position.
+         try
+         {
+            message.readByte();
+            fail("Should have received NumberFormatException");
+         }
+         catch (NumberFormatException e)
+         {
+         }
+
+         assertEquals("This is a test to see how it works.",
+               message.readString());
+
+         // Invalid conversion should throw exception and not move the stream
+         // position.
+         try
+         {
+            message.readByte();
+            fail("Should have received MessageEOFException");
+         }
+         catch (MessageEOFException e)
+         {
+         }
+      }
+      assertNull(consumer.receiveNoWait());
+   }
+
+   @Test
+   public void testMapMessage() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      // send the message.
+      {
+         MapMessage message = session.createMapMessage();
+         message.setBoolean("boolKey", true);
+         producer.send(message);
+      }
+
+      // get the message.
+      {
+         MapMessage message = (MapMessage) consumer.receive(1000);
+         assertNotNull(message);
+         assertTrue(message.getBoolean("boolKey"));
+      }
+      assertNull(consumer.receiveNoWait());
+   }
+
+   static class ForeignMessage implements TextMessage
+   {
+
+      public int deliveryMode;
+
+      private String messageId;
+      private long timestamp;
+      private String correlationId;
+      private Destination replyTo;
+      private Destination destination;
+      private boolean redelivered;
+      private String type;
+      private long expiration;
+      private int priority;
+      private String text;
+      private final HashMap<String, Object> props = new HashMap<String, Object>();
+
+      @Override
+      public String getJMSMessageID() throws JMSException
+      {
+         return messageId;
+      }
+
+      @Override
+      public void setJMSMessageID(String arg0) throws JMSException
+      {
+         messageId = arg0;
+      }
+
+      @Override
+      public long getJMSTimestamp() throws JMSException
+      {
+         return timestamp;
+      }
+
+      @Override
+      public void setJMSTimestamp(long arg0) throws JMSException
+      {
+         timestamp = arg0;
+      }
+
+      @Override
+      public byte[] getJMSCorrelationIDAsBytes() throws JMSException
+      {
+         return null;
+      }
+
+      @Override
+      public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException
+      {
+      }
+
+      @Override
+      public void setJMSCorrelationID(String arg0) throws JMSException
+      {
+         correlationId = arg0;
+      }
+
+      @Override
+      public String getJMSCorrelationID() throws JMSException
+      {
+         return correlationId;
+      }
+
+      @Override
+      public Destination getJMSReplyTo() throws JMSException
+      {
+         return replyTo;
+      }
+
+      @Override
+      public void setJMSReplyTo(Destination arg0) throws JMSException
+      {
+         replyTo = arg0;
+      }
+
+      @Override
+      public Destination getJMSDestination() throws JMSException
+      {
+         return destination;
+      }
+
+      @Override
+      public void setJMSDestination(Destination arg0) throws JMSException
+      {
+         destination = arg0;
+      }
+
+      @Override
+      public int getJMSDeliveryMode() throws JMSException
+      {
+         return deliveryMode;
+      }
+
+      @Override
+      public void setJMSDeliveryMode(int arg0) throws JMSException
+      {
+         deliveryMode = arg0;
+      }
+
+      @Override
+      public boolean getJMSRedelivered() throws JMSException
+      {
+         return redelivered;
+      }
+
+      @Override
+      public void setJMSRedelivered(boolean arg0) throws JMSException
+      {
+         redelivered = arg0;
+      }
+
+      @Override
+      public String getJMSType() throws JMSException
+      {
+         return type;
+      }
+
+      @Override
+      public void setJMSType(String arg0) throws JMSException
+      {
+         type = arg0;
+      }
+
+      @Override
+      public long getJMSExpiration() throws JMSException
+      {
+         return expiration;
+      }
+
+      @Override
+      public void setJMSExpiration(long arg0) throws JMSException
+      {
+         expiration = arg0;
+      }
+
+      @Override
+      public int getJMSPriority() throws JMSException
+      {
+         return priority;
+      }
+
+      @Override
+      public void setJMSPriority(int arg0) throws JMSException
+      {
+         priority = arg0;
+      }
+
+      @Override
+      public void clearProperties() throws JMSException
+      {
+      }
+
+      @Override
+      public boolean propertyExists(String arg0) throws JMSException
+      {
+         return false;
+      }
+
+      @Override
+      public boolean getBooleanProperty(String arg0) throws JMSException
+      {
+         return false;
+      }
+
+      @Override
+      public byte getByteProperty(String arg0) throws JMSException
+      {
+         return 0;
+      }
+
+      @Override
+      public short getShortProperty(String arg0) throws JMSException
+      {
+         return 0;
+      }
+
+      @Override
+      public int getIntProperty(String arg0) throws JMSException
+      {
+         return 0;
+      }
+
+      @Override
+      public long getLongProperty(String arg0) throws JMSException
+      {
+         return 0;
+      }
+
+      @Override
+      public float getFloatProperty(String arg0) throws JMSException
+      {
+         return 0;
+      }
+
+      @Override
+      public double getDoubleProperty(String arg0) throws JMSException
+      {
+         return 0;
+      }
+
+      @Override
+      public String getStringProperty(String arg0) throws JMSException
+      {
+         return (String) props.get(arg0);
+      }
+
+      @Override
+      public Object getObjectProperty(String arg0) throws JMSException
+      {
+         return props.get(arg0);
+      }
+
+      @Override
+      public Enumeration<?> getPropertyNames() throws JMSException
+      {
+         return new Vector<String>(props.keySet()).elements();
+      }
+
+      @Override
+      public void setBooleanProperty(String arg0, boolean arg1) throws JMSException
+      {
+      }
+
+      @Override
+      public void setByteProperty(String arg0, byte arg1) throws JMSException
+      {
+      }
+
+      @Override
+      public void setShortProperty(String arg0, short arg1) throws JMSException
+      {
+      }
+
+      @Override
+      public void setIntProperty(String arg0, int arg1) throws JMSException
+      {
+      }
+
+      @Override
+      public void setLongProperty(String arg0, long arg1) throws JMSException
+      {
+      }
+
+      @Override
+      public void setFloatProperty(String arg0, float arg1) throws JMSException
+      {
+      }
+
+      @Override
+      public void setDoubleProperty(String arg0, double arg1) throws JMSException
+      {
+      }
+
+      @Override
+      public void setStringProperty(String arg0, String arg1) throws JMSException
+      {
+         props.put(arg0, arg1);
+      }
+
+      @Override
+      public void setObjectProperty(String arg0, Object arg1) throws JMSException
+      {
+         props.put(arg0, arg1);
+      }
+
+      @Override
+      public void acknowledge() throws JMSException
+      {
+      }
+
+      @Override
+      public void clearBody() throws JMSException
+      {
+      }
+
+      @Override
+      public void setText(String arg0) throws JMSException
+      {
+         text = arg0;
+      }
+
+      @Override
+      public String getText() throws JMSException
+      {
+         return text;
+      }
+
+      @Override
+      public <T> T getBody(Class<T> arg0) throws JMSException
+      {
+         // TODO Auto-generated method stub
+         return null;
+      }
+
+      @Override
+      public long getJMSDeliveryTime() throws JMSException
+      {
+         // TODO Auto-generated method stub
+         return 0;
+      }
+
+      @Override
+      public boolean isBodyAssignableTo(Class arg0) throws JMSException
+      {
+         // TODO Auto-generated method stub
+         return false;
+      }
+
+      @Override
+      public void setJMSDeliveryTime(long arg0) throws JMSException
+      {
+         // TODO Auto-generated method stub
+      }
+   }
+
+   @Test
+   public void testForeignMessage() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      // Send the message.
+      {
+         ForeignMessage message = new ForeignMessage();
+         message.text = "Hello";
+         message.setStringProperty("test", "value");
+         long timeToLive = 10000L;
+         long start = System.currentTimeMillis();
+         producer.send(message, Session.AUTO_ACKNOWLEDGE, 7, timeToLive);
+         long end = System.currentTimeMillis();
+
+         // validate jms spec 1.1 section 3.4.11 table 3.1
+         // JMSDestination, JMSDeliveryMode, JMSExpiration, JMSPriority,
+         // JMSMessageID, and JMSTimestamp
+         // must be set by sending a message.
+
+         assertNotNull(message.getJMSDestination());
+         assertEquals(Session.AUTO_ACKNOWLEDGE, message.getJMSDeliveryMode());
+         assertTrue(start + timeToLive <= message.getJMSExpiration());
+         assertTrue(end + timeToLive >= message.getJMSExpiration());
+         assertEquals(7, message.getJMSPriority());
+         assertNotNull(message.getJMSMessageID());
+         assertTrue(start <= message.getJMSTimestamp());
+         assertTrue(end >= message.getJMSTimestamp());
+      }
+
+      // Validate message is OK.
+      {
+         TextMessage message = (TextMessage) consumer.receive(1000);
+         assertNotNull(message);
+         assertEquals("Hello", message.getText());
+         assertEquals("value", message.getStringProperty("test"));
+      }
+
+      assertNull(consumer.receiveNoWait());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSQueueRedeliverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSQueueRedeliverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSQueueRedeliverTest.java
new file mode 100644
index 0000000..fb975b8
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSQueueRedeliverTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import org.junit.Before;
+
+/**
+ * adapted from: org.apache.activemq.JMSQueueRedeliverTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JMSQueueRedeliverTest extends JmsTopicRedeliverTest
+{
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      topic = false;
+      super.setUp();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecase1Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecase1Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecase1Test.java
new file mode 100644
index 0000000..ae28baf
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecase1Test.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ActiveMQMessage;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSUsecaseTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSUsecase1Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public byte destinationType;
+
+   public JMSUsecase1Test(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testSendReceive() throws Exception
+   {
+      // Send a message to the broker.
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session, destinationType);
+      System.out.println("destionation: " + destination);
+      MessageProducer producer = session.createProducer(destination);
+      producer.setDeliveryMode(this.deliveryMode);
+      MessageConsumer consumer = session.createConsumer(destination);
+      ActiveMQMessage message = new ActiveMQMessage();
+      producer.send(message);
+
+      // Make sure only 1 message was delivered.
+      assertNotNull(consumer.receive(1000));
+      assertNull(consumer.receiveNoWait());
+   }
+
+   @Test
+   public void testSendReceiveTransacted() throws Exception
+   {
+      // Send a message to the broker.
+      connection.start();
+      Session session = connection.createSession(true,
+            Session.SESSION_TRANSACTED);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageProducer producer = session.createProducer(destination);
+      producer.setDeliveryMode(this.deliveryMode);
+      MessageConsumer consumer = session.createConsumer(destination);
+      producer.send(session.createTextMessage("test"));
+
+      // Message should not be delivered until commit.
+      assertNull(consumer.receiveNoWait());
+      session.commit();
+
+      // Make sure only 1 message was delivered.
+      Message message = consumer.receive(1000);
+      assertNotNull(message);
+      assertFalse(message.getJMSRedelivered());
+      assertNull(consumer.receiveNoWait());
+
+      // Message should be redelivered is rollback is used.
+      session.rollback();
+
+      // Make sure only 1 message was delivered.
+      message = consumer.receive(2000);
+      assertNotNull(message);
+      assertTrue(message.getJMSRedelivered());
+      assertNull(consumer.receiveNoWait());
+
+      // If we commit now, the message should not be redelivered.
+      session.commit();
+      assertNull(consumer.receiveNoWait());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecaseTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecaseTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecaseTest.java
new file mode 100644
index 0000000..9d25feb
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSUsecaseTest.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Enumeration;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.QueueBrowser;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSUsecaseTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSUsecaseTest extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public byte destinationType;
+
+   public JMSUsecaseTest(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testQueueBrowser() throws Exception
+   {
+      // Send a message to the broker.
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session, destinationType);
+      MessageProducer producer = session.createProducer(destination);
+      producer.setDeliveryMode(this.deliveryMode);
+      sendMessages(session, producer, 5);
+      producer.close();
+
+      QueueBrowser browser = session.createBrowser((Queue) destination);
+      Enumeration<?> enumeration = browser.getEnumeration();
+      for (int i = 0; i < 5; i++)
+      {
+         Thread.sleep(100);
+         assertTrue(enumeration.hasMoreElements());
+         Message m = (Message) enumeration.nextElement();
+         assertNotNull(m);
+         assertEquals("" + i, ((TextMessage) m).getText());
+      }
+      assertFalse(enumeration.hasMoreElements());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckListenerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckListenerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckListenerTest.java
new file mode 100644
index 0000000..8cd09cf
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckListenerTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JmsAutoAckListenerTest
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsAutoAckListenerTest extends BasicOpenWireTest implements MessageListener
+{
+   private final CountDownLatch latch = new CountDownLatch(1);
+
+   @Test
+   public void testAckedMessageAreConsumed() throws Exception
+   {
+      connection.start();
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      Queue queue = session.createQueue(queueName);
+      MessageProducer producer = session.createProducer(queue);
+      producer.send(session.createTextMessage("Hello"));
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      consumer.setMessageListener(this);
+
+      latch.await(10, TimeUnit.SECONDS);
+      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      // Attempt to Consume the message...check if message was acknowledge
+      consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNull(msg);
+
+      session.close();
+   }
+
+   public void onMessage(Message message)
+   {
+      System.out.println("Received message: " + message);
+      assertNotNull(message);
+      latch.countDown();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckTest.java
new file mode 100644
index 0000000..0e766e1
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsAutoAckTest.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JmsAutoAckTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsAutoAckTest extends BasicOpenWireTest
+{
+   /**
+    * Tests if acknowleged messages are being consumed.
+    *
+    * @throws javax.jms.JMSException
+    */
+   @Test
+   public void testAckedMessageAreConsumed() throws JMSException
+   {
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      Queue queue = session.createQueue(queueName);
+      MessageProducer producer = session.createProducer(queue);
+      producer.send(session.createTextMessage("Hello"));
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNotNull(msg);
+
+      // Reset the session.
+      session.close();
+      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+      // Attempt to Consume the message...
+      consumer = session.createConsumer(queue);
+      msg = consumer.receive(1000);
+      assertNull(msg);
+
+      session.close();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsClientAckTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsClientAckTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsClientAckTest.java
new file mode 100644
index 0000000..9e7d042
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsClientAckTest.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JmsClientAckTest
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsClientAckTest extends BasicOpenWireTest
+{
+   /**
+    * Tests if acknowledged messages are being consumed.
+    *
+    * @throws JMSException
+    */
+   @Test
+   public void testAckedMessageAreConsumed() throws JMSException
+   {
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      Queue queue = session.createQueue(getQueueName());
+      MessageProducer producer = session.createProducer(queue);
+      producer.send(session.createTextMessage("Hello"));
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg.acknowledge();
+
+      // Reset the session.
+      session.close();
+      session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
+
+      // Attempt to Consume the message...
+      consumer = session.createConsumer(queue);
+      msg = consumer.receive(1000);
+      assertNull(msg);
+
+      session.close();
+   }
+
+   /**
+    * Tests if acknowledged messages are being consumed.
+    *
+    * @throws JMSException
+    */
+   @Test
+   public void testLastMessageAcked() throws JMSException
+   {
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      Queue queue = session.createQueue(getQueueName());
+      MessageProducer producer = session.createProducer(queue);
+      producer.send(session.createTextMessage("Hello"));
+      producer.send(session.createTextMessage("Hello2"));
+      producer.send(session.createTextMessage("Hello3"));
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg = consumer.receive(1000);
+      assertNotNull(msg);
+      msg.acknowledge();
+
+      // Reset the session.
+      session.close();
+      session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
+
+      // Attempt to Consume the message...
+      consumer = session.createConsumer(queue);
+      msg = consumer.receive(1000);
+      assertNull(msg);
+
+      session.close();
+   }
+
+   /**
+    * Tests if unacknowledged messages are being re-delivered when the consumer connects again.
+    *
+    * @throws JMSException
+    */
+   @Test
+   public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException
+   {
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      Queue queue = session.createQueue(getQueueName());
+      MessageProducer producer = session.createProducer(queue);
+      producer.send(session.createTextMessage("Hello"));
+
+      // Consume the message...
+      MessageConsumer consumer = session.createConsumer(queue);
+      Message msg = consumer.receive(1000);
+      assertNotNull(msg);
+      // Don't ack the message.
+
+      // Reset the session. This should cause the unacknowledged message to be
+      // re-delivered.
+      session.close();
+      session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
+
+      // Attempt to Consume the message...
+      consumer = session.createConsumer(queue);
+      msg = consumer.receive(2000);
+      assertNotNull(msg);
+      msg.acknowledge();
+
+      session.close();
+   }
+
+   protected String getQueueName()
+   {
+      return queueName;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConnectionStartStopTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConnectionStartStopTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConnectionStartStopTest.java
new file mode 100644
index 0000000..b8d237f
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConnectionStartStopTest.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Random;
+import java.util.Vector;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+import javax.jms.Topic;
+
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JmsConnectionStartStopTest
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsConnectionStartStopTest extends BasicOpenWireTest
+{
+   private Connection startedConnection;
+   private Connection stoppedConnection;
+
+   @Before
+   public void setUp() throws Exception
+   {
+      super.setUp();
+      startedConnection = factory.createConnection();
+      startedConnection.start();
+      stoppedConnection = factory.createConnection();
+   }
+
+   /**
+    * @see junit.framework.TestCase#tearDown()
+    */
+   @After
+   public void tearDown() throws Exception
+   {
+      stoppedConnection.close();
+      startedConnection.close();
+      super.tearDown();
+   }
+
+   /**
+    * Tests if the consumer receives the messages that were sent before the
+    * connection was started.
+    *
+    * @throws JMSException
+    */
+   @Test
+   public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException
+   {
+      Session startedSession = startedConnection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      Session stoppedSession = stoppedConnection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+
+      // Setup the consumers.
+      Topic topic = startedSession.createTopic("test");
+      MessageConsumer startedConsumer = startedSession.createConsumer(topic);
+      MessageConsumer stoppedConsumer = stoppedSession.createConsumer(topic);
+
+      // Send the message.
+      MessageProducer producer = startedSession.createProducer(topic);
+      TextMessage message = startedSession.createTextMessage("Hello");
+      producer.send(message);
+
+      // Test the assertions.
+      Message m = startedConsumer.receive(1000);
+      assertNotNull(m);
+
+      m = stoppedConsumer.receive(1000);
+      assertNull(m);
+
+      stoppedConnection.start();
+      m = stoppedConsumer.receive(5000);
+      assertNotNull(m);
+
+      startedSession.close();
+      stoppedSession.close();
+   }
+
+   /**
+    * Tests if the consumer is able to receive messages eveb when the
+    * connecction restarts multiple times.
+    *
+    * @throws Exception
+    */
+   @Test
+   public void testMultipleConnectionStops() throws Exception
+   {
+      testStoppedConsumerHoldsMessagesTillStarted();
+      stoppedConnection.stop();
+      testStoppedConsumerHoldsMessagesTillStarted();
+      stoppedConnection.stop();
+      testStoppedConsumerHoldsMessagesTillStarted();
+   }
+
+   @Test
+   public void testConcurrentSessionCreateWithStart() throws Exception
+   {
+      ThreadPoolExecutor executor = new ThreadPoolExecutor(50,
+            Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
+            new SynchronousQueue<Runnable>());
+      final Vector<Throwable> exceptions = new Vector<Throwable>();
+      final AtomicInteger counter = new AtomicInteger(0);
+      final Random rand = new Random();
+      Runnable createSessionTask = new Runnable()
+      {
+         @Override
+         public void run()
+         {
+            try
+            {
+               TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
+               stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+               counter.incrementAndGet();
+            }
+            catch (Exception e)
+            {
+               exceptions.add(e);
+            }
+            catch (Throwable t)
+            {
+            }
+         }
+      };
+
+      Runnable startStopTask = new Runnable()
+      {
+         @Override
+         public void run()
+         {
+            try
+            {
+               TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
+               stoppedConnection.start();
+               stoppedConnection.stop();
+            }
+            catch (Exception e)
+            {
+               exceptions.add(e);
+            }
+            catch (Throwable t)
+            {
+            }
+         }
+      };
+
+      for (int i = 0; i < 1000; i++)
+      {
+         executor.execute(createSessionTask);
+         executor.execute(startStopTask);
+      }
+
+      executor.shutdown();
+
+      assertTrue("executor terminated",
+            executor.awaitTermination(30, TimeUnit.SECONDS));
+      assertTrue("no exceptions: " + exceptions, exceptions.isEmpty());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java
new file mode 100644
index 0000000..d3bd648
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsConsumerResetActiveListenerTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Vector;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JmsConsumerResetActiveListenerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsConsumerResetActiveListenerTest extends BasicOpenWireTest
+{
+
+   /**
+    * verify the (undefined by spec) behaviour of setting a listener while
+    * receiving a message.
+    *
+    * @throws Exception
+    */
+   @Test
+   public void testSetListenerFromListener() throws Exception
+   {
+      Session session = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      Destination dest = session.createQueue(queueName);
+      final MessageConsumer consumer = session.createConsumer(dest);
+
+      final CountDownLatch latch = new CountDownLatch(2);
+      final AtomicBoolean first = new AtomicBoolean(true);
+      final Vector<Object> results = new Vector<Object>();
+      consumer.setMessageListener(new MessageListener()
+      {
+
+         public void onMessage(Message message)
+         {
+            if (first.compareAndSet(true, false))
+            {
+               try
+               {
+                  consumer.setMessageListener(this);
+                  results.add(message);
+               }
+               catch (JMSException e)
+               {
+                  results.add(e);
+               }
+            }
+            else
+            {
+               results.add(message);
+            }
+            latch.countDown();
+         }
+      });
+
+      connection.start();
+
+      MessageProducer producer = session.createProducer(dest);
+      producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
+      producer.send(session.createTextMessage("First"));
+      producer.send(session.createTextMessage("Second"));
+
+      assertTrue("we did not timeout", latch.await(5, TimeUnit.SECONDS));
+
+      assertEquals("we have a result", 2, results.size());
+      Object result = results.get(0);
+      assertTrue(result instanceof TextMessage);
+      assertEquals("result is first", "First", ((TextMessage) result).getText());
+      result = results.get(1);
+      assertTrue(result instanceof TextMessage);
+      assertEquals("result is first", "Second",
+            ((TextMessage) result).getText());
+   }
+
+   /**
+    * and a listener on a new consumer, just in case.
+    *
+    * @throws Exception
+    */
+   @Test
+   public void testNewConsumerSetListenerFromListener() throws Exception
+   {
+      final Session session = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      final Destination dest = session.createQueue(queueName);
+      final MessageConsumer consumer = session.createConsumer(dest);
+
+      final CountDownLatch latch = new CountDownLatch(2);
+      final AtomicBoolean first = new AtomicBoolean(true);
+      final Vector<Object> results = new Vector<Object>();
+      consumer.setMessageListener(new MessageListener()
+      {
+
+         public void onMessage(Message message)
+         {
+            if (first.compareAndSet(true, false))
+            {
+               try
+               {
+                  MessageConsumer anotherConsumer = session
+                        .createConsumer(dest);
+                  anotherConsumer.setMessageListener(this);
+                  results.add(message);
+               }
+               catch (JMSException e)
+               {
+                  results.add(e);
+               }
+            }
+            else
+            {
+               results.add(message);
+            }
+            latch.countDown();
+         }
+      });
+
+      connection.start();
+
+      MessageProducer producer = session.createProducer(dest);
+      producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
+      producer.send(session.createTextMessage("First"));
+      producer.send(session.createTextMessage("Second"));
+
+      assertTrue("we did not timeout", latch.await(5, TimeUnit.SECONDS));
+
+      assertEquals("we have a result", 2, results.size());
+      Object result = results.get(0);
+      assertTrue(result instanceof TextMessage);
+      assertEquals("result is first", "First", ((TextMessage) result).getText());
+      result = results.get(1);
+      assertTrue(result instanceof TextMessage);
+      assertEquals("result is first", "Second",
+            ((TextMessage) result).getText());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java
new file mode 100644
index 0000000..fec6c79
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsCreateConsumerInOnMessageTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.Topic;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JmsCreateConsumerInOnMessageTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsCreateConsumerInOnMessageTest extends BasicOpenWireTest implements MessageListener
+{
+   private Session publisherSession;
+   private Session consumerSession;
+   private MessageConsumer consumer;
+   private MessageConsumer testConsumer;
+   private MessageProducer producer;
+   private Topic topic;
+   private Object lock = new Object();
+
+   /**
+    * Tests if a consumer can be created asynchronusly
+    *
+    * @throws Exception
+    */
+   @Test
+   public void testCreateConsumer() throws Exception
+   {
+      connection.setClientID("connection:" + "JmsCreateConsumerInOnMessageTest");
+      publisherSession = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      consumerSession = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      topic = (Topic) super.createDestination(consumerSession,
+            ActiveMQDestination.TOPIC_TYPE);
+      consumer = consumerSession.createConsumer(topic);
+      consumer.setMessageListener(this);
+      producer = publisherSession.createProducer(topic);
+      connection.start();
+      Message msg = publisherSession.createMessage();
+      producer.send(msg);
+
+      System.out.println("message sent: " + msg);
+      if (testConsumer == null)
+      {
+         synchronized (lock)
+         {
+            lock.wait(3000);
+         }
+      }
+      assertTrue(testConsumer != null);
+   }
+
+   /**
+    * Use the asynchronous subscription mechanism
+    *
+    * @param message
+    */
+   public void onMessage(Message message)
+   {
+      System.out.println("____________onmessage " + message);
+      try
+      {
+         testConsumer = consumerSession.createConsumer(topic);
+         consumerSession.createProducer(topic);
+         synchronized (lock)
+         {
+            lock.notify();
+         }
+      }
+      catch (Exception ex)
+      {
+         ex.printStackTrace();
+         assertTrue(false);
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java
new file mode 100644
index 0000000..823e6e6
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableQueueWildcardSendReceiveTest.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import javax.jms.DeliveryMode;
+
+/**
+ * adapted from: org.apache.activemq.JmsDurableQueueWildcardSendReceiveTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsDurableQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest
+{
+   public void setUp() throws Exception
+   {
+      topic = false;
+      deliveryMode = DeliveryMode.PERSISTENT;
+      super.setUp();
+   }
+
+   @Override
+   protected String getConsumerSubject()
+   {
+      return "FOO.>";
+   }
+
+   @Override
+   protected String getProducerSubject()
+   {
+      return "FOO.BAR.HUMBUG";
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java
new file mode 100644
index 0000000..71dc288
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JmsDurableTopicSelectorTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import org.junit.Before;
+
+/**
+ * adapted from: org.apache.activemq.JmsDurableTopicSelectorTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JmsDurableTopicSelectorTest extends JmsTopicSelectorTest
+{
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      durable = true;
+      super.setUp();
+   }
+
+}


[32/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestinationStatistics.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestinationStatistics.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestinationStatistics.java
new file mode 100644
index 0000000..035db4e
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestinationStatistics.java
@@ -0,0 +1,228 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.management.CountStatisticImpl;
+import org.apache.activemq.management.PollCountStatisticImpl;
+import org.apache.activemq.management.SizeStatisticImpl;
+import org.apache.activemq.management.StatsImpl;
+import org.apache.activemq.management.TimeStatisticImpl;
+
+public class AMQDestinationStatistics extends StatsImpl
+{
+
+   protected CountStatisticImpl enqueues;
+   protected CountStatisticImpl dequeues;
+   protected CountStatisticImpl consumers;
+   protected CountStatisticImpl producers;
+   protected CountStatisticImpl messages;
+   protected PollCountStatisticImpl messagesCached;
+   protected CountStatisticImpl dispatched;
+   protected CountStatisticImpl inflight;
+   protected CountStatisticImpl expired;
+   protected TimeStatisticImpl processTime;
+   protected CountStatisticImpl blockedSends;
+   protected TimeStatisticImpl blockedTime;
+   protected SizeStatisticImpl messageSize;
+
+   public AMQDestinationStatistics()
+   {
+
+      enqueues = new CountStatisticImpl("enqueues",
+            "The number of messages that have been sent to the destination");
+      dispatched = new CountStatisticImpl("dispatched",
+            "The number of messages that have been dispatched from the destination");
+      dequeues = new CountStatisticImpl("dequeues",
+            "The number of messages that have been acknowledged from the destination");
+      inflight = new CountStatisticImpl("inflight",
+            "The number of messages dispatched but awaiting acknowledgement");
+      expired = new CountStatisticImpl("expired",
+            "The number of messages that have expired");
+
+      consumers = new CountStatisticImpl(
+            "consumers",
+            "The number of consumers that that are subscribing to messages from the destination");
+      consumers.setDoReset(false);
+      producers = new CountStatisticImpl("producers",
+            "The number of producers that that are publishing messages to the destination");
+      producers.setDoReset(false);
+      messages = new CountStatisticImpl("messages",
+            "The number of messages that that are being held by the destination");
+      messages.setDoReset(false);
+      messagesCached = new PollCountStatisticImpl("messagesCached",
+            "The number of messages that are held in the destination's memory cache");
+      processTime = new TimeStatisticImpl("processTime",
+            "information around length of time messages are held by a destination");
+      blockedSends = new CountStatisticImpl("blockedSends",
+            "number of messages that have to wait for flow control");
+      blockedTime = new TimeStatisticImpl("blockedTime",
+            "amount of time messages are blocked for flow control");
+      messageSize = new SizeStatisticImpl("messageSize",
+            "Size of messages passing through the destination");
+      addStatistic("enqueues", enqueues);
+      addStatistic("dispatched", dispatched);
+      addStatistic("dequeues", dequeues);
+      addStatistic("inflight", inflight);
+      addStatistic("expired", expired);
+      addStatistic("consumers", consumers);
+      addStatistic("producers", producers);
+      addStatistic("messages", messages);
+      addStatistic("messagesCached", messagesCached);
+      addStatistic("processTime", processTime);
+      addStatistic("blockedSends", blockedSends);
+      addStatistic("blockedTime", blockedTime);
+      addStatistic("messageSize", messageSize);
+   }
+
+   public CountStatisticImpl getEnqueues()
+   {
+      return enqueues;
+   }
+
+   public CountStatisticImpl getDequeues()
+   {
+      return dequeues;
+   }
+
+   public CountStatisticImpl getInflight()
+   {
+      return inflight;
+   }
+
+   public CountStatisticImpl getExpired()
+   {
+      return expired;
+   }
+
+   public CountStatisticImpl getConsumers()
+   {
+      return consumers;
+   }
+
+   public CountStatisticImpl getProducers()
+   {
+      return producers;
+   }
+
+   public PollCountStatisticImpl getMessagesCached()
+   {
+      return messagesCached;
+   }
+
+   public CountStatisticImpl getMessages()
+   {
+      return messages;
+   }
+
+   public void setMessagesCached(PollCountStatisticImpl messagesCached)
+   {
+      this.messagesCached = messagesCached;
+   }
+
+   public CountStatisticImpl getDispatched()
+   {
+      return dispatched;
+   }
+
+   public TimeStatisticImpl getProcessTime()
+   {
+      return this.processTime;
+   }
+
+   public CountStatisticImpl getBlockedSends()
+   {
+      return this.blockedSends;
+   }
+
+   public TimeStatisticImpl getBlockedTime()
+   {
+      return this.blockedTime;
+   }
+
+   public SizeStatisticImpl getMessageSize()
+   {
+      return this.messageSize;
+   }
+
+   public void reset()
+   {
+      if (this.isDoReset())
+      {
+         super.reset();
+         enqueues.reset();
+         dequeues.reset();
+         dispatched.reset();
+         inflight.reset();
+         expired.reset();
+         blockedSends.reset();
+         blockedTime.reset();
+         messageSize.reset();
+      }
+   }
+
+   public void setEnabled(boolean enabled)
+   {
+      super.setEnabled(enabled);
+      enqueues.setEnabled(enabled);
+      dispatched.setEnabled(enabled);
+      dequeues.setEnabled(enabled);
+      inflight.setEnabled(enabled);
+      expired.setEnabled(true);
+      consumers.setEnabled(enabled);
+      producers.setEnabled(enabled);
+      messages.setEnabled(enabled);
+      messagesCached.setEnabled(enabled);
+      processTime.setEnabled(enabled);
+      blockedSends.setEnabled(enabled);
+      blockedTime.setEnabled(enabled);
+      messageSize.setEnabled(enabled);
+
+   }
+
+   public void setParent(AMQDestinationStatistics parent)
+   {
+      if (parent != null)
+      {
+         enqueues.setParent(parent.enqueues);
+         dispatched.setParent(parent.dispatched);
+         dequeues.setParent(parent.dequeues);
+         inflight.setParent(parent.inflight);
+         expired.setParent(parent.expired);
+         consumers.setParent(parent.consumers);
+         producers.setParent(parent.producers);
+         messagesCached.setParent(parent.messagesCached);
+         messages.setParent(parent.messages);
+         processTime.setParent(parent.processTime);
+         blockedSends.setParent(parent.blockedSends);
+         blockedTime.setParent(parent.blockedTime);
+         messageSize.setParent(parent.messageSize);
+      }
+      else
+      {
+         enqueues.setParent(null);
+         dispatched.setParent(null);
+         dequeues.setParent(null);
+         inflight.setParent(null);
+         expired.setParent(null);
+         consumers.setParent(null);
+         producers.setParent(null);
+         messagesCached.setParent(null);
+         messages.setParent(null);
+         processTime.setParent(null);
+         blockedSends.setParent(null);
+         blockedTime.setParent(null);
+         messageSize.setParent(null);
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMapTransportConnectionStateRegister.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMapTransportConnectionStateRegister.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMapTransportConnectionStateRegister.java
new file mode 100644
index 0000000..d9c4495
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMapTransportConnectionStateRegister.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.activemq.command.ConnectionId;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.ProducerId;
+import org.apache.activemq.command.SessionId;
+
+public class AMQMapTransportConnectionStateRegister implements
+      AMQTransportConnectionStateRegister
+{
+
+   private Map<ConnectionId, AMQTransportConnectionState> connectionStates = new ConcurrentHashMap<ConnectionId, AMQTransportConnectionState>();
+
+   public AMQTransportConnectionState registerConnectionState(
+         ConnectionId connectionId, AMQTransportConnectionState state)
+   {
+      AMQTransportConnectionState rc = connectionStates
+            .put(connectionId, state);
+      return rc;
+   }
+
+   public AMQTransportConnectionState unregisterConnectionState(
+         ConnectionId connectionId)
+   {
+      AMQTransportConnectionState rc = connectionStates.remove(connectionId);
+      if (rc.getReferenceCounter().get() > 1)
+      {
+         rc.decrementReference();
+         connectionStates.put(connectionId, rc);
+      }
+      return rc;
+   }
+
+   public List<AMQTransportConnectionState> listConnectionStates()
+   {
+
+      List<AMQTransportConnectionState> rc = new ArrayList<AMQTransportConnectionState>();
+      rc.addAll(connectionStates.values());
+      return rc;
+   }
+
+   public AMQTransportConnectionState lookupConnectionState(String connectionId)
+   {
+      return connectionStates.get(new ConnectionId(connectionId));
+   }
+
+   public AMQTransportConnectionState lookupConnectionState(ConsumerId id)
+   {
+      AMQTransportConnectionState cs = lookupConnectionState(id
+            .getConnectionId());
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a consumer from a connection that had not been registered: "
+                     + id.getParentId().getParentId());
+      }
+      return cs;
+   }
+
+   public AMQTransportConnectionState lookupConnectionState(ProducerId id)
+   {
+      AMQTransportConnectionState cs = lookupConnectionState(id
+            .getConnectionId());
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a producer from a connection that had not been registered: "
+                     + id.getParentId().getParentId());
+      }
+      return cs;
+   }
+
+   public AMQTransportConnectionState lookupConnectionState(SessionId id)
+   {
+      AMQTransportConnectionState cs = lookupConnectionState(id
+            .getConnectionId());
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a session from a connection that had not been registered: "
+                     + id.getParentId());
+      }
+      return cs;
+   }
+
+   public AMQTransportConnectionState lookupConnectionState(
+         ConnectionId connectionId)
+   {
+      AMQTransportConnectionState cs = connectionStates.get(connectionId);
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a connection that had not been registered: "
+                     + connectionId);
+      }
+      return cs;
+   }
+
+   public boolean doesHandleMultipleConnectionStates()
+   {
+      return true;
+   }
+
+   public boolean isEmpty()
+   {
+      return connectionStates.isEmpty();
+   }
+
+   public void clear()
+   {
+      connectionStates.clear();
+
+   }
+
+   public void intialize(AMQTransportConnectionStateRegister other)
+   {
+      connectionStates.clear();
+      connectionStates.putAll(other.mapStates());
+
+   }
+
+   public Map<ConnectionId, AMQTransportConnectionState> mapStates()
+   {
+      HashMap<ConnectionId, AMQTransportConnectionState> map = new HashMap<ConnectionId, AMQTransportConnectionState>(
+            connectionStates);
+      return map;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java
new file mode 100644
index 0000000..6cdd593
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageAuthorizationPolicy.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.command.Message;
+
+public interface AMQMessageAuthorizationPolicy
+{
+
+   /**
+    * Returns true if the given message is able to be dispatched to the connection
+    * performing any user
+    *
+    * @return true if the context is allowed to consume the message
+    */
+   boolean isAllowedToConsume(AMQConnectionContext context, Message message);
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageStore.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageStore.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageStore.java
new file mode 100644
index 0000000..df62d62
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQMessageStore.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+public interface AMQMessageStore
+{
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQPersistenceAdapter.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQPersistenceAdapter.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQPersistenceAdapter.java
new file mode 100644
index 0000000..f717c59
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQPersistenceAdapter.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.io.IOException;
+import java.util.Set;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ActiveMQQueue;
+import org.apache.activemq.command.ProducerId;
+
+public class AMQPersistenceAdapter
+{
+
+   /**
+    * Returns a set of all the {@link org.apache.activemq.command.ActiveMQDestination}
+    * objects that the persistence store is aware exist.
+    *
+    * @return active destinations
+    */
+   Set<ActiveMQDestination> getDestinations()
+   {
+      return null;
+   }
+
+   /**
+    * Factory method to create a new queue message store with the given destination name
+    * @param destination
+    * @return the message store
+    * @throws IOException
+    */
+   AMQMessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException
+   {
+      return null;
+   }
+
+   /**
+    * return the last stored producer sequenceId for this producer Id
+    * used to suppress duplicate sends on failover reconnect at the transport
+    * when a reconnect occurs
+    * @param id the producerId to find a sequenceId for
+    * @return the last stored sequence id or -1 if no suppression needed
+    */
+   public long getLastProducerSequenceId(ProducerId id)
+   {
+      return 0;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducer.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducer.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducer.java
new file mode 100644
index 0000000..16fcf74
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducer.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.command.ProducerInfo;
+
+public class AMQProducer
+{
+   private AMQSession amqSession;
+   private ProducerInfo info;
+
+   public AMQProducer(AMQSession amqSession, ProducerInfo info)
+   {
+      this.amqSession = amqSession;
+      this.info = info;
+   }
+
+   public void init()
+   {
+      //hornetq doesn't have producer at server.
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducerBrokerExchange.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducerBrokerExchange.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducerBrokerExchange.java
new file mode 100644
index 0000000..9191ee1
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQProducerBrokerExchange.java
@@ -0,0 +1,264 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.activemq.command.Message;
+import org.apache.activemq.command.MessageId;
+import org.apache.activemq.state.ProducerState;
+
+public class AMQProducerBrokerExchange
+{
+   private AMQConnectionContext connectionContext;
+   private AMQDestination regionDestination;
+   private ProducerState producerState;
+   private boolean mutable = true;
+   private AtomicLong lastSendSequenceNumber = new AtomicLong(-1);
+   private boolean auditProducerSequenceIds;
+   private boolean isNetworkProducer;
+   private final FlowControlInfo flowControlInfo = new FlowControlInfo();
+
+   public AMQProducerBrokerExchange()
+   {
+   }
+
+   public AMQProducerBrokerExchange copy()
+   {
+      AMQProducerBrokerExchange rc = new AMQProducerBrokerExchange();
+      rc.connectionContext = connectionContext.copy();
+      rc.regionDestination = regionDestination;
+      rc.producerState = producerState;
+      rc.mutable = mutable;
+      return rc;
+   }
+
+   /**
+    * @return the connectionContext
+    */
+   public AMQConnectionContext getConnectionContext()
+   {
+      return this.connectionContext;
+   }
+
+   /**
+    * @param connectionContext
+    *           the connectionContext to set
+    */
+   public void setConnectionContext(AMQConnectionContext connectionContext)
+   {
+      this.connectionContext = connectionContext;
+   }
+
+   /**
+    * @return the mutable
+    */
+   public boolean isMutable()
+   {
+      return this.mutable;
+   }
+
+   /**
+    * @param mutable
+    *           the mutable to set
+    */
+   public void setMutable(boolean mutable)
+   {
+      this.mutable = mutable;
+   }
+
+   /**
+    * @return the regionDestination
+    */
+   public AMQDestination getRegionDestination()
+   {
+      return this.regionDestination;
+   }
+
+   /**
+    * @param regionDestination
+    *           the regionDestination to set
+    */
+   public void setRegionDestination(AMQDestination regionDestination)
+   {
+      this.regionDestination = regionDestination;
+   }
+
+   /**
+    * @return the producerState
+    */
+   public ProducerState getProducerState()
+   {
+      return this.producerState;
+   }
+
+   /**
+    * @param producerState
+    *           the producerState to set
+    */
+   public void setProducerState(ProducerState producerState)
+   {
+      this.producerState = producerState;
+   }
+
+   /**
+    * Enforce duplicate suppression using info from persistence adapter
+    *
+    * @return false if message should be ignored as a duplicate
+    */
+   public boolean canDispatch(Message messageSend)
+   {
+      boolean canDispatch = true;
+      if (auditProducerSequenceIds && messageSend.isPersistent())
+      {
+         final long producerSequenceId = messageSend.getMessageId()
+               .getProducerSequenceId();
+         if (isNetworkProducer)
+         {
+            // messages are multiplexed on this producer so we need to query the
+            // persistenceAdapter
+            long lastStoredForMessageProducer = getStoredSequenceIdForMessage(messageSend
+                  .getMessageId());
+            if (producerSequenceId <= lastStoredForMessageProducer)
+            {
+               canDispatch = false;
+            }
+         }
+         else if (producerSequenceId <= lastSendSequenceNumber.get())
+         {
+            canDispatch = false;
+            if (messageSend.isInTransaction())
+            {
+            }
+            else
+            {
+            }
+         }
+         else
+         {
+            // track current so we can suppress duplicates later in the stream
+            lastSendSequenceNumber.set(producerSequenceId);
+         }
+      }
+      return canDispatch;
+   }
+
+   private long getStoredSequenceIdForMessage(MessageId messageId)
+   {
+      return -1;
+   }
+
+   public void setLastStoredSequenceId(long l)
+   {
+   }
+
+   public void incrementSend()
+   {
+      flowControlInfo.incrementSend();
+   }
+
+   public void blockingOnFlowControl(boolean blockingOnFlowControl)
+   {
+      flowControlInfo.setBlockingOnFlowControl(blockingOnFlowControl);
+   }
+
+   public void incrementTimeBlocked(AMQDestination destination, long timeBlocked)
+   {
+      flowControlInfo.incrementTimeBlocked(timeBlocked);
+   }
+
+   public boolean isBlockedForFlowControl()
+   {
+      return flowControlInfo.isBlockingOnFlowControl();
+   }
+
+   public void resetFlowControl()
+   {
+      flowControlInfo.reset();
+   }
+
+   public long getTotalTimeBlocked()
+   {
+      return flowControlInfo.getTotalTimeBlocked();
+   }
+
+   public int getPercentageBlocked()
+   {
+      double value = flowControlInfo.getSendsBlocked()
+            / flowControlInfo.getTotalSends();
+      return (int) value * 100;
+   }
+
+   public static class FlowControlInfo
+   {
+      private AtomicBoolean blockingOnFlowControl = new AtomicBoolean();
+      private AtomicLong totalSends = new AtomicLong();
+      private AtomicLong sendsBlocked = new AtomicLong();
+      private AtomicLong totalTimeBlocked = new AtomicLong();
+
+      public boolean isBlockingOnFlowControl()
+      {
+         return blockingOnFlowControl.get();
+      }
+
+      public void setBlockingOnFlowControl(boolean blockingOnFlowControl)
+      {
+         this.blockingOnFlowControl.set(blockingOnFlowControl);
+         if (blockingOnFlowControl)
+         {
+            incrementSendBlocked();
+         }
+      }
+
+      public long getTotalSends()
+      {
+         return totalSends.get();
+      }
+
+      public void incrementSend()
+      {
+         this.totalSends.incrementAndGet();
+      }
+
+      public long getSendsBlocked()
+      {
+         return sendsBlocked.get();
+      }
+
+      public void incrementSendBlocked()
+      {
+         this.sendsBlocked.incrementAndGet();
+      }
+
+      public long getTotalTimeBlocked()
+      {
+         return totalTimeBlocked.get();
+      }
+
+      public void incrementTimeBlocked(long time)
+      {
+         this.totalTimeBlocked.addAndGet(time);
+      }
+
+      public void reset()
+      {
+         blockingOnFlowControl.set(false);
+         totalSends.set(0);
+         sendsBlocked.set(0);
+         totalTimeBlocked.set(0);
+
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSecurityContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSecurityContext.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSecurityContext.java
new file mode 100644
index 0000000..7efd30b
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSecurityContext.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.security.Principal;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.activemq.command.ActiveMQDestination;
+
+public abstract class AMQSecurityContext
+{
+
+   public static final AMQSecurityContext BROKER_SECURITY_CONTEXT = new AMQSecurityContext(
+         "ActiveMQBroker")
+   {
+      @Override
+      public boolean isBrokerContext()
+      {
+         return true;
+      }
+
+      public Set<Principal> getPrincipals()
+      {
+         return Collections.emptySet();
+      }
+   };
+
+   final String userName;
+
+   final ConcurrentHashMap<ActiveMQDestination, ActiveMQDestination> authorizedReadDests = new ConcurrentHashMap<ActiveMQDestination, ActiveMQDestination>();
+   final ConcurrentHashMap<ActiveMQDestination, ActiveMQDestination> authorizedWriteDests = new ConcurrentHashMap<ActiveMQDestination, ActiveMQDestination>();
+
+   public AMQSecurityContext(String userName)
+   {
+      this.userName = userName;
+   }
+
+   public boolean isInOneOf(Set<?> allowedPrincipals)
+   {
+      Iterator<?> allowedIter = allowedPrincipals.iterator();
+      HashSet<?> userPrincipals = new HashSet<Object>(getPrincipals());
+      while (allowedIter.hasNext())
+      {
+         Iterator<?> userIter = userPrincipals.iterator();
+         Object allowedPrincipal = allowedIter.next();
+         while (userIter.hasNext())
+         {
+            if (allowedPrincipal.equals(userIter.next()))
+               return true;
+         }
+      }
+      return false;
+   }
+
+   public abstract Set<Principal> getPrincipals();
+
+   public String getUserName()
+   {
+      return userName;
+   }
+
+   public ConcurrentHashMap<ActiveMQDestination, ActiveMQDestination> getAuthorizedReadDests()
+   {
+      return authorizedReadDests;
+   }
+
+   public ConcurrentHashMap<ActiveMQDestination, ActiveMQDestination> getAuthorizedWriteDests()
+   {
+      return authorizedWriteDests;
+   }
+
+   public boolean isBrokerContext()
+   {
+      return false;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerConsumer.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerConsumer.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerConsumer.java
new file mode 100644
index 0000000..2954142
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerConsumer.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.util.List;
+
+import org.hornetq.core.filter.Filter;
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.postoffice.QueueBinding;
+import org.hornetq.core.protocol.openwire.OpenWireMessageConverter;
+import org.hornetq.core.server.HandleStatus;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.MessageReference;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.impl.QueueImpl;
+import org.hornetq.core.server.impl.ServerConsumerImpl;
+import org.hornetq.core.server.management.ManagementService;
+import org.hornetq.spi.core.protocol.SessionCallback;
+
+public class AMQServerConsumer extends ServerConsumerImpl
+{
+
+   public AMQServerConsumer(long consumerID, AMQServerSession serverSession,
+         QueueBinding binding, Filter filter, boolean started,
+         boolean browseOnly, StorageManager storageManager,
+         SessionCallback callback, boolean preAcknowledge,
+         boolean strictUpdateDeliveryCount,
+         ManagementService managementService, boolean supportLargeMessage,
+         Integer credits) throws Exception
+   {
+      super(consumerID, serverSession, binding, filter, started, browseOnly, storageManager,
+            callback, preAcknowledge, strictUpdateDeliveryCount, managementService,
+            supportLargeMessage, credits);
+   }
+
+   public void setBrowserListener(BrowserListener listener)
+   {
+      AMQBrowserDeliverer newBrowserDeliverer = new AMQBrowserDeliverer(this.browserDeliverer);
+      newBrowserDeliverer.listener = listener;
+      this.browserDeliverer = newBrowserDeliverer;
+   }
+
+   private class AMQBrowserDeliverer extends BrowserDeliverer
+   {
+      private BrowserListener listener = null;
+
+      public AMQBrowserDeliverer(final BrowserDeliverer other)
+      {
+         super(other.iterator);
+      }
+
+      @Override
+      public synchronized void run()
+      {
+         // if the reference was busy during the previous iteration, handle it now
+         if (current != null)
+         {
+            try
+            {
+               HandleStatus status = handle(current);
+
+               if (status == HandleStatus.BUSY)
+               {
+                  return;
+               }
+
+               if (status == HandleStatus.HANDLED)
+               {
+                  proceedDeliver(current);
+               }
+
+               current = null;
+            }
+            catch (Exception e)
+            {
+               HornetQServerLogger.LOGGER.errorBrowserHandlingMessage(e, current);
+               return;
+            }
+         }
+
+         MessageReference ref = null;
+         HandleStatus status;
+
+         while (true)
+         {
+            try
+            {
+               ref = null;
+               synchronized (messageQueue)
+               {
+                  if (!iterator.hasNext())
+                  {
+                     //here we need to send a null for amq browsers
+                     if (listener != null)
+                     {
+                        listener.browseFinished();
+                     }
+                     break;
+                  }
+
+                  ref = iterator.next();
+
+                  status = handle(ref);
+               }
+
+               if (status == HandleStatus.HANDLED)
+               {
+                  proceedDeliver(ref);
+               }
+               else if (status == HandleStatus.BUSY)
+               {
+                  // keep a reference on the current message reference
+                  // to handle it next time the browser deliverer is executed
+                  current = ref;
+                  break;
+               }
+            }
+            catch (Exception e)
+            {
+               HornetQServerLogger.LOGGER.errorBrowserHandlingMessage(e, ref);
+               break;
+            }
+         }
+      }
+   }
+
+   public void amqPutBackToDeliveringList(final List<MessageReference> refs)
+   {
+      synchronized (this.deliveringRefs)
+      {
+         for (MessageReference ref : refs)
+         {
+            ref.incrementDeliveryCount();
+            deliveringRefs.add(ref);
+         }
+         //adjust the order. Suppose deliveringRefs has 2 existing
+         //refs m1, m2, and refs has 3 m3, m4, m5
+         //new order must be m3, m4, m5, m1, m2
+         if (refs.size() > 0)
+         {
+            long first = refs.get(0).getMessage().getMessageID();
+            MessageReference m = deliveringRefs.peek();
+            while (m.getMessage().getMessageID() != first)
+            {
+               deliveringRefs.poll();
+               deliveringRefs.add(m);
+               m = deliveringRefs.peek();
+            }
+         }
+      }
+   }
+
+   public void moveToDeadLetterAddress(long mid, Throwable cause) throws Exception
+   {
+      MessageReference ref = removeReferenceByID(mid);
+
+      if (ref == null)
+      {
+         throw new IllegalStateException("Cannot find ref to ack " + mid);
+      }
+
+      ServerMessage coreMsg = ref.getMessage();
+      coreMsg.putStringProperty(OpenWireMessageConverter.AMQ_MSG_DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY, cause.toString());
+
+      QueueImpl queue = (QueueImpl)ref.getQueue();
+      synchronized (queue)
+      {
+         queue.sendToDeadLetterAddress(ref);
+         queue.decDelivering();
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSession.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSession.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSession.java
new file mode 100644
index 0000000..0711f01
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSession.java
@@ -0,0 +1,451 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.hornetq.api.core.Pair;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
+import org.hornetq.api.core.management.ManagementHelper;
+import org.hornetq.core.filter.Filter;
+import org.hornetq.core.filter.impl.FilterImpl;
+import org.hornetq.core.persistence.OperationContext;
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.postoffice.Binding;
+import org.hornetq.core.postoffice.BindingType;
+import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.postoffice.QueueBinding;
+import org.hornetq.core.protocol.openwire.AMQTransactionImpl;
+import org.hornetq.core.security.SecurityStore;
+import org.hornetq.core.server.HornetQMessageBundle;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.MessageReference;
+import org.hornetq.core.server.Queue;
+import org.hornetq.core.server.ServerConsumer;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.RefsOperation;
+import org.hornetq.core.server.impl.ServerConsumerImpl;
+import org.hornetq.core.server.impl.ServerSessionImpl;
+import org.hornetq.core.server.management.ManagementService;
+import org.hornetq.core.server.management.Notification;
+import org.hornetq.core.transaction.ResourceManager;
+import org.hornetq.core.transaction.TransactionPropertyIndexes;
+import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.protocol.SessionCallback;
+import org.hornetq.utils.TypedProperties;
+import org.hornetq.utils.UUID;
+
+public class AMQServerSession extends ServerSessionImpl
+{
+   private boolean internal;
+
+   public AMQServerSession(String name, String username, String password,
+         int minLargeMessageSize, boolean autoCommitSends,
+         boolean autoCommitAcks, boolean preAcknowledge,
+         boolean persistDeliveryCountBeforeDelivery, boolean xa,
+         RemotingConnection connection, StorageManager storageManager,
+         PostOffice postOffice, ResourceManager resourceManager,
+         SecurityStore securityStore, ManagementService managementService,
+         HornetQServerImpl hornetQServerImpl, SimpleString managementAddress,
+         SimpleString simpleString, SessionCallback callback,
+         OperationContext context) throws Exception
+   {
+      super(name, username, password,
+         minLargeMessageSize, autoCommitSends,
+         autoCommitAcks, preAcknowledge,
+         persistDeliveryCountBeforeDelivery, xa,
+         connection, storageManager,
+         postOffice, resourceManager,
+         securityStore, managementService,
+         hornetQServerImpl, managementAddress,
+         simpleString, callback,
+         context, new AMQTransactionFactory());
+   }
+
+   //create a fake session just for security check
+   public AMQServerSession(String user, String pass)
+   {
+      super(user, pass);
+   }
+
+   protected void doClose(final boolean failed) throws Exception
+   {
+      synchronized (this)
+      {
+         if (tx != null && tx.getXid() == null)
+         {
+            ((AMQTransactionImpl)tx).setRollbackForClose();
+         }
+      }
+      super.doClose(failed);
+   }
+
+   public AtomicInteger getConsumerCredits(final long consumerID)
+   {
+      ServerConsumer consumer = consumers.get(consumerID);
+
+      if (consumer == null)
+      {
+         HornetQServerLogger.LOGGER.debug("There is no consumer with id " + consumerID);
+
+         return null;
+      }
+
+      return ((ServerConsumerImpl)consumer).getAvailableCredits();
+   }
+
+   public void enableXA() throws Exception
+   {
+      if (!this.xa)
+      {
+         if (this.tx != null)
+         {
+            //that's not expected, maybe a warning.
+            this.tx.rollback();
+            this.tx = null;
+         }
+
+         this.autoCommitAcks = false;
+         this.autoCommitSends = false;
+
+         this.xa = true;
+      }
+   }
+
+   public void enableTx() throws Exception
+   {
+      if (this.xa)
+      {
+         throw new IllegalStateException("Session is XA");
+      }
+
+      this.autoCommitAcks = false;
+      this.autoCommitSends = false;
+
+      if (this.tx != null)
+      {
+         //that's not expected, maybe a warning.
+         this.tx.rollback();
+         this.tx = null;
+      }
+
+      this.tx = newTransaction();
+   }
+
+   //amq specific behavior
+   public void amqRollback(Set<Long> acked) throws Exception
+   {
+      if (tx == null)
+      {
+         // Might be null if XA
+
+         tx = newTransaction();
+      }
+
+      RefsOperation oper = (RefsOperation) tx.getProperty(TransactionPropertyIndexes.REFS_OPERATION);
+
+      if (oper != null)
+      {
+         List<MessageReference> ackRefs = oper.getReferencesToAcknowledge();
+         Map<Long, List<MessageReference>> toAcks = new HashMap<Long, List<MessageReference>>();
+         for (MessageReference ref : ackRefs)
+         {
+            Long consumerId = ref.getConsumerId();
+
+            if (this.consumers.containsKey(consumerId))
+            {
+               if (acked.contains(ref.getMessage().getMessageID()))
+               {
+                  List<MessageReference> ackList = toAcks.get(consumerId);
+                  if (ackList == null)
+                  {
+                     ackList = new ArrayList<MessageReference>();
+                     toAcks.put(consumerId, ackList);
+                  }
+                  ackList.add(ref);
+               }
+            }
+            else
+            {
+               //consumer must have been closed, cancel to queue
+               ref.getQueue().cancel(tx, ref);
+            }
+         }
+         //iterate consumers
+         if (toAcks.size() > 0)
+         {
+            Iterator<Entry<Long, List<MessageReference>>> iter = toAcks.entrySet().iterator();
+            while (iter.hasNext())
+            {
+               Entry<Long, List<MessageReference>> entry = iter.next();
+               ServerConsumer consumer = consumers.get(entry.getKey());
+               ((AMQServerConsumer)consumer).amqPutBackToDeliveringList(entry.getValue());
+            }
+         }
+      }
+
+      tx.rollback();
+
+      if (xa)
+      {
+         tx = null;
+      }
+      else
+      {
+         tx = newTransaction();
+      }
+
+   }
+
+   /**
+    * The failed flag is used here to control delivery count.
+    * If set to true the delivery count won't decrement.
+    */
+   public void amqCloseConsumer(long consumerID, boolean failed) throws Exception
+   {
+      final ServerConsumer consumer = consumers.get(consumerID);
+
+      if (consumer != null)
+      {
+         consumer.close(failed);
+      }
+      else
+      {
+         HornetQServerLogger.LOGGER.cannotFindConsumer(consumerID);
+      }
+   }
+
+   @Override
+   public ServerConsumer createConsumer(final long consumerID,
+                              final SimpleString queueName,
+                              final SimpleString filterString,
+                              final boolean browseOnly,
+                              final boolean supportLargeMessage,
+                              final Integer credits) throws Exception
+   {
+      if (this.internal)
+      {
+         //internal sessions doesn't check security
+
+         Binding binding = postOffice.getBinding(queueName);
+
+         if (binding == null || binding.getType() != BindingType.LOCAL_QUEUE)
+         {
+            throw HornetQMessageBundle.BUNDLE.noSuchQueue(queueName);
+         }
+
+         Filter filter = FilterImpl.createFilter(filterString);
+
+         ServerConsumer consumer = newConsumer(consumerID, this,
+               (QueueBinding) binding, filter, started, browseOnly,
+               storageManager, callback, preAcknowledge,
+               strictUpdateDeliveryCount, managementService,
+               supportLargeMessage, credits);
+         consumers.put(consumer.getID(), consumer);
+
+         if (!browseOnly)
+         {
+            TypedProperties props = new TypedProperties();
+
+            props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS,
+                  binding.getAddress());
+
+            props.putSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME,
+                  binding.getClusterName());
+
+            props.putSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME,
+                  binding.getRoutingName());
+
+            props.putIntProperty(ManagementHelper.HDR_DISTANCE,
+                  binding.getDistance());
+
+            Queue theQueue = (Queue) binding.getBindable();
+
+            props.putIntProperty(ManagementHelper.HDR_CONSUMER_COUNT,
+                  theQueue.getConsumerCount());
+
+            // HORNETQ-946
+            props.putSimpleStringProperty(ManagementHelper.HDR_USER,
+                  SimpleString.toSimpleString(username));
+
+            props.putSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS,
+                  SimpleString.toSimpleString(this.remotingConnection
+                        .getRemoteAddress()));
+
+            props.putSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME,
+                  SimpleString.toSimpleString(name));
+
+            if (filterString != null)
+            {
+               props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING,
+                     filterString);
+            }
+
+            Notification notification = new Notification(null,
+                  CoreNotificationType.CONSUMER_CREATED, props);
+
+            if (HornetQServerLogger.LOGGER.isDebugEnabled())
+            {
+               HornetQServerLogger.LOGGER.debug("Session with user=" + username
+                     + ", connection=" + this.remotingConnection
+                     + " created a consumer on queue " + queueName
+                     + ", filter = " + filterString);
+            }
+
+            managementService.sendNotification(notification);
+         }
+
+         return consumer;
+      }
+      else
+      {
+         return super.createConsumer(consumerID, queueName, filterString, browseOnly, supportLargeMessage, credits);
+      }
+   }
+
+   @Override
+   public void createQueue(final SimpleString address,
+                           final SimpleString name,
+                           final SimpleString filterString,
+                           final boolean temporary,
+                           final boolean durable) throws Exception
+   {
+      if (!this.internal)
+      {
+         super.createQueue(address, name, filterString, temporary, durable);
+         return;
+      }
+
+      server.createQueue(address, name, filterString, durable, temporary);
+
+      if (temporary)
+      {
+         // Temporary queue in core simply means the queue will be deleted if
+         // the remoting connection
+         // dies. It does not mean it will get deleted automatically when the
+         // session is closed.
+         // It is up to the user to delete the queue when finished with it
+
+         TempQueueCleanerUpper cleaner = new TempQueueCleanerUpper(server, name);
+
+         remotingConnection.addCloseListener(cleaner);
+         remotingConnection.addFailureListener(cleaner);
+
+         tempQueueCleannerUppers.put(name, cleaner);
+      }
+
+      if (HornetQServerLogger.LOGGER.isDebugEnabled())
+      {
+         HornetQServerLogger.LOGGER.debug("Queue " + name + " created on address " + name +
+                                             " with filter=" + filterString + " temporary = " +
+                                             temporary + " durable=" + durable + " on session user=" + this.username + ", connection=" + this.remotingConnection);
+      }
+
+   }
+
+   @Override
+   protected void doSend(final ServerMessage msg, final boolean direct) throws Exception
+   {
+      if (!this.internal)
+      {
+         super.doSend(msg, direct);
+         return;
+      }
+
+      //bypass security check for internal sessions
+      if (tx == null || autoCommitSends)
+      {
+      }
+      else
+      {
+         routingContext.setTransaction(tx);
+      }
+
+      try
+      {
+         postOffice.route(msg, routingContext, direct);
+
+         Pair<UUID, AtomicLong> value = targetAddressInfos.get(msg.getAddress());
+
+         if (value == null)
+         {
+            targetAddressInfos.put(msg.getAddress(), new Pair<UUID, AtomicLong>(msg.getUserID(), new AtomicLong(1)));
+         }
+         else
+         {
+            value.setA(msg.getUserID());
+            value.getB().incrementAndGet();
+         }
+      }
+      finally
+      {
+         routingContext.clear();
+      }
+   }
+
+   @Override
+   protected ServerConsumer newConsumer(long consumerID,
+         ServerSessionImpl serverSessionImpl, QueueBinding binding,
+         Filter filter, boolean started2, boolean browseOnly,
+         StorageManager storageManager2, SessionCallback callback2,
+         boolean preAcknowledge2, boolean strictUpdateDeliveryCount2,
+         ManagementService managementService2, boolean supportLargeMessage,
+         Integer credits) throws Exception
+   {
+      return new AMQServerConsumer(consumerID,
+            this,
+            (QueueBinding) binding,
+            filter,
+            started,
+            browseOnly,
+            storageManager,
+            callback,
+            preAcknowledge,
+            strictUpdateDeliveryCount,
+            managementService,
+            supportLargeMessage,
+            credits);
+   }
+
+   public AMQServerConsumer getConsumer(long nativeId)
+   {
+      return (AMQServerConsumer) this.consumers.get(nativeId);
+   }
+
+   public void setInternal(boolean internal)
+   {
+      this.internal = internal;
+   }
+
+   public boolean isInternal()
+   {
+      return this.internal;
+   }
+
+   public void moveToDeadLetterAddress(long consumerId, long mid, Throwable cause) throws Exception
+   {
+      AMQServerConsumer consumer = getConsumer(consumerId);
+      consumer.moveToDeadLetterAddress(mid, cause);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSessionFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSessionFactory.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSessionFactory.java
new file mode 100644
index 0000000..db044a0
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQServerSessionFactory.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.persistence.OperationContext;
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.security.SecurityStore;
+import org.hornetq.core.server.ServerSessionFactory;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.ServerSessionImpl;
+import org.hornetq.core.server.management.ManagementService;
+import org.hornetq.core.transaction.ResourceManager;
+import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.protocol.SessionCallback;
+
+public class AMQServerSessionFactory implements ServerSessionFactory
+{
+
+   @Override
+   public ServerSessionImpl createCoreSession(String name, String username,
+         String password, int minLargeMessageSize, boolean autoCommitSends,
+         boolean autoCommitAcks, boolean preAcknowledge,
+         boolean persistDeliveryCountBeforeDelivery, boolean xa,
+         RemotingConnection connection, StorageManager storageManager,
+         PostOffice postOffice, ResourceManager resourceManager,
+         SecurityStore securityStore, ManagementService managementService,
+         HornetQServerImpl hornetQServerImpl, SimpleString managementAddress,
+         SimpleString simpleString, SessionCallback callback,
+         OperationContext context) throws Exception
+   {
+      return new AMQServerSession(name, username, password, minLargeMessageSize, autoCommitSends,
+            autoCommitAcks, preAcknowledge, persistDeliveryCountBeforeDelivery, xa,
+            connection, storageManager, postOffice, resourceManager, securityStore,
+            managementService, hornetQServerImpl, managementAddress, simpleString, callback,
+            context);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSession.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSession.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSession.java
new file mode 100644
index 0000000..34f0ff4
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSession.java
@@ -0,0 +1,590 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.transaction.xa.Xid;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ConnectionInfo;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.ConsumerInfo;
+import org.apache.activemq.command.ExceptionResponse;
+import org.apache.activemq.command.Message;
+import org.apache.activemq.command.MessageAck;
+import org.apache.activemq.command.MessageDispatch;
+import org.apache.activemq.command.ProducerAck;
+import org.apache.activemq.command.ProducerId;
+import org.apache.activemq.command.ProducerInfo;
+import org.apache.activemq.command.Response;
+import org.apache.activemq.command.SessionInfo;
+import org.apache.activemq.command.TransactionId;
+import org.apache.activemq.command.TransactionInfo;
+import org.apache.activemq.command.XATransactionId;
+import org.apache.activemq.wireformat.WireFormat;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.paging.impl.PagingStoreImpl;
+import org.hornetq.core.protocol.openwire.OpenWireConnection;
+import org.hornetq.core.protocol.openwire.OpenWireMessageConverter;
+import org.hornetq.core.protocol.openwire.OpenWireProtocolManager;
+import org.hornetq.core.protocol.openwire.OpenWireUtil;
+import org.hornetq.core.protocol.openwire.SendingResult;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.ServerConsumer;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.impl.ServerMessageImpl;
+import org.hornetq.core.transaction.impl.XidImpl;
+import org.hornetq.spi.core.protocol.SessionCallback;
+import org.hornetq.spi.core.remoting.ReadyListener;
+
+public class AMQSession implements SessionCallback
+{
+   private AMQServerSession coreSession;
+   private ConnectionInfo connInfo;
+   private SessionInfo sessInfo;
+   private HornetQServer server;
+   private OpenWireConnection connection;
+   //native id -> consumer
+   private Map<Long, AMQConsumer> consumers = new ConcurrentHashMap<Long, AMQConsumer>();
+   //amq id -> native id
+   private Map<Long, Long> consumerIdMap = new HashMap<Long, Long>();
+
+   private Map<Long, AMQProducer> producers = new HashMap<Long, AMQProducer>();
+
+   private AtomicBoolean started = new AtomicBoolean(false);
+
+   private TransactionId txId = null;
+
+   private boolean isTx;
+
+   private OpenWireProtocolManager manager;
+
+   public AMQSession(ConnectionInfo connInfo, SessionInfo sessInfo,
+         HornetQServer server, OpenWireConnection connection, OpenWireProtocolManager manager)
+   {
+      this.connInfo = connInfo;
+      this.sessInfo = sessInfo;
+      this.server = server;
+      this.connection = connection;
+      this.manager = manager;
+   }
+
+   public void initialize()
+   {
+      String name = sessInfo.getSessionId().toString();
+      String username = connInfo.getUserName();
+      String password = connInfo.getPassword();
+
+      int minLargeMessageSize = Integer.MAX_VALUE; // disable
+                                                   // minLargeMessageSize for
+                                                   // now
+
+      try
+      {
+         coreSession = (AMQServerSession) server.createSession(name, username, password,
+               minLargeMessageSize, connection, true, false, false, false,
+               null, this, new AMQServerSessionFactory());
+
+         long sessionId = sessInfo.getSessionId().getValue();
+         if (sessionId == -1)
+         {
+            this.connection.setAdvisorySession(this);
+         }
+      }
+      catch (Exception e)
+      {
+         HornetQServerLogger.LOGGER.error("error init session", e);
+      }
+
+   }
+
+   public void createConsumer(ConsumerInfo info) throws Exception
+   {
+      //check destination
+      ActiveMQDestination dest = info.getDestination();
+      ActiveMQDestination[] dests = null;
+      if (dest.isComposite())
+      {
+         dests = dest.getCompositeDestinations();
+      }
+      else
+      {
+         dests = new ActiveMQDestination[] {dest};
+      }
+
+      for (ActiveMQDestination d : dests)
+      {
+         AMQConsumer consumer = new AMQConsumer(this, d, info);
+         consumer.init();
+         consumers.put(consumer.getNativeId(), consumer);
+         this.consumerIdMap.put(info.getConsumerId().getValue(), consumer.getNativeId());
+      }
+      coreSession.start();
+      started.set(true);
+   }
+
+   @Override
+   public void sendProducerCreditsMessage(int credits, SimpleString address)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public void sendProducerCreditsFailMessage(int credits, SimpleString address)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public int sendMessage(ServerMessage message, ServerConsumer consumerID, int deliveryCount)
+   {
+      AMQConsumer consumer = consumers.get(consumerID.getID());
+      return consumer.handleDeliver(message, deliveryCount);
+   }
+
+   @Override
+   public int sendLargeMessage(ServerMessage message, ServerConsumer consumerID,
+         long bodySize, int deliveryCount)
+   {
+      // TODO Auto-generated method stub
+      return 0;
+   }
+
+   @Override
+   public int sendLargeMessageContinuation(ServerConsumer consumerID, byte[] body,
+         boolean continues, boolean requiresResponse)
+   {
+      // TODO Auto-generated method stub
+      return 0;
+   }
+
+   @Override
+   public void closed()
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public void addReadyListener(ReadyListener listener)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public void removeReadyListener(ReadyListener listener)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public boolean hasCredits(ServerConsumer consumerID)
+   {
+      return true;
+   }
+
+   @Override
+   public void disconnect(ServerConsumer consumerId, String queueName)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   public AMQServerSession getCoreSession()
+   {
+      return this.coreSession;
+   }
+
+   public HornetQServer getCoreServer()
+   {
+      return this.server;
+   }
+
+   public void removeConsumer(ConsumerInfo info) throws Exception
+   {
+      long consumerId = info.getConsumerId().getValue();
+      long nativeId = this.consumerIdMap.remove(consumerId);
+      if (this.txId != null || this.isTx)
+      {
+         ((AMQServerSession)coreSession).amqCloseConsumer(nativeId, false);
+      }
+      else
+      {
+         ((AMQServerSession)coreSession).amqCloseConsumer(nativeId, true);
+      }
+      AMQConsumer consumer = consumers.remove(nativeId);
+   }
+
+   public void createProducer(ProducerInfo info)
+   {
+      AMQProducer producer = new AMQProducer(this, info);
+      producer.init();
+      producers.put(info.getProducerId().getValue(), producer);
+   }
+
+   public void removeProducer(ProducerInfo info)
+   {
+      removeProducer(info.getProducerId());
+   }
+
+   public void removeProducer(ProducerId id)
+   {
+      producers.remove(id.getValue());
+   }
+
+   public SendingResult send(AMQProducerBrokerExchange producerExchange,
+         Message messageSend, boolean sendProducerAck) throws Exception
+   {
+      SendingResult result = new SendingResult();
+      TransactionId tid = messageSend.getTransactionId();
+      if (tid != null)
+      {
+         resetSessionTx(tid);
+      }
+
+      messageSend.setBrokerInTime(System.currentTimeMillis());
+
+      ActiveMQDestination destination = messageSend.getDestination();
+      ActiveMQDestination[] actualDestinations = null;
+      if (destination.isComposite())
+      {
+         actualDestinations = destination.getCompositeDestinations();
+      }
+      else
+      {
+         actualDestinations = new ActiveMQDestination[] {destination};
+      }
+
+      for (ActiveMQDestination dest : actualDestinations)
+      {
+         ServerMessageImpl coreMsg = new ServerMessageImpl(-1, 1024);
+         OpenWireMessageConverter.toCoreMessage(coreMsg, messageSend, connection.getMarshaller());
+         SimpleString address = OpenWireUtil.toCoreAddress(dest);
+         coreMsg.setAddress(address);
+
+         PagingStoreImpl store = (PagingStoreImpl)server.getPagingManager().getPageStore(address);
+         if (store.isFull())
+         {
+            result.setBlockNextSend(true);
+            result.setBlockPagingStore(store);
+            result.setBlockingAddress(address);
+            //now we hold this message send until the store has space.
+            //we do this by put it in a scheduled task
+            ScheduledExecutorService scheduler = server.getScheduledPool();
+            Runnable sendRetryTask = new SendRetryTask(coreMsg, producerExchange, sendProducerAck,
+                                                       messageSend.getSize(), messageSend.getCommandId());
+            scheduler.schedule(sendRetryTask, 10, TimeUnit.MILLISECONDS);
+         }
+         else
+         {
+            coreSession.send(coreMsg, false);
+         }
+      }
+      return result;
+   }
+
+   public WireFormat getMarshaller()
+   {
+      return this.connection.getMarshaller();
+   }
+
+   public void acknowledge(MessageAck ack) throws Exception
+   {
+      TransactionId tid = ack.getTransactionId();
+      if (tid != null)
+      {
+         this.resetSessionTx(ack.getTransactionId());
+      }
+      ConsumerId consumerId = ack.getConsumerId();
+      long nativeConsumerId = consumerIdMap.get(consumerId.getValue());
+      AMQConsumer consumer = consumers.get(nativeConsumerId);
+      consumer.acknowledge(ack);
+
+      if (tid == null && ack.getAckType() == MessageAck.STANDARD_ACK_TYPE)
+      {
+         this.coreSession.commit();
+      }
+   }
+
+   //AMQ session and transactions are create separately. Whether a session
+   //is transactional or not is known only when a TransactionInfo command
+   //comes in.
+   public void resetSessionTx(TransactionId xid) throws Exception
+   {
+      if ((this.txId != null) && (!this.txId.equals(xid)))
+      {
+         throw new IllegalStateException("Session already associated with a tx");
+      }
+
+      this.isTx = true;
+      if (this.txId == null)
+      {
+         //now reset session
+         this.txId = xid;
+
+         if (xid.isXATransaction())
+         {
+            XATransactionId xaXid = (XATransactionId)xid;
+            coreSession.enableXA();
+            XidImpl coreXid = new XidImpl(xaXid.getBranchQualifier(), xaXid.getFormatId(), xaXid.getGlobalTransactionId());
+            coreSession.xaStart(coreXid);
+         }
+         else
+         {
+            coreSession.enableTx();
+         }
+
+         this.manager.registerTx(this.txId, this);
+      }
+   }
+
+   private void checkTx(TransactionId inId)
+   {
+      if (this.txId == null)
+      {
+         throw new IllegalStateException("Session has no transaction associated with it");
+      }
+
+      if (!this.txId.equals(inId))
+      {
+         throw new IllegalStateException("Session already associated with another tx");
+      }
+
+      this.isTx = true;
+   }
+
+   public void commitOnePhase(TransactionInfo info) throws Exception
+   {
+      checkTx(info.getTransactionId());
+
+      if (txId.isXATransaction())
+      {
+         XATransactionId xid = (XATransactionId) txId;
+         XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId());
+         this.coreSession.xaCommit(coreXid, true);
+      }
+      else
+      {
+         Iterator<AMQConsumer> iter = consumers.values().iterator();
+         while (iter.hasNext())
+         {
+            AMQConsumer consumer = iter.next();
+            consumer.finishTx();
+         }
+         this.coreSession.commit();
+      }
+
+      this.txId = null;
+   }
+
+   public void prepareTransaction(XATransactionId xid) throws Exception
+   {
+      checkTx(xid);
+      XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId());
+      this.coreSession.xaPrepare(coreXid);
+   }
+
+   public void commitTwoPhase(XATransactionId xid) throws Exception
+   {
+      checkTx(xid);
+      XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId());
+      this.coreSession.xaCommit(coreXid, false);
+
+      this.txId = null;
+   }
+
+   public void rollback(TransactionInfo info) throws Exception
+   {
+      checkTx(info.getTransactionId());
+      if (this.txId.isXATransaction())
+      {
+         XATransactionId xid = (XATransactionId) txId;
+         XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId());
+         this.coreSession.xaRollback(coreXid);
+      }
+      else
+      {
+         Iterator<AMQConsumer> iter = consumers.values().iterator();
+         Set<Long> acked = new HashSet<Long>();
+         while (iter.hasNext())
+         {
+            AMQConsumer consumer = iter.next();
+            consumer.rollbackTx(acked);
+         }
+         //on local rollback, amq broker doesn't do anything about the delivered
+         //messages, which stay at clients until next time
+         this.coreSession.amqRollback(acked);
+      }
+
+      this.txId = null;
+   }
+
+   public void recover(List<TransactionId> recovered)
+   {
+      List<Xid> xids = this.coreSession.xaGetInDoubtXids();
+      for (Xid xid : xids)
+      {
+         XATransactionId amqXid = new XATransactionId(xid);
+         recovered.add(amqXid);
+      }
+   }
+
+   public void forget(final TransactionId tid) throws Exception
+   {
+      checkTx(tid);
+      XATransactionId xid = (XATransactionId) tid;
+      XidImpl coreXid = new XidImpl(xid.getBranchQualifier(), xid.getFormatId(), xid.getGlobalTransactionId());
+      this.coreSession.xaForget(coreXid);
+      this.txId = null;
+   }
+
+   public ConnectionInfo getConnectionInfo()
+   {
+      return this.connInfo;
+   }
+
+   public void setInternal(boolean internal)
+   {
+      this.coreSession.setInternal(internal);
+   }
+
+   public boolean isInternal()
+   {
+      return this.coreSession.isInternal();
+   }
+
+   public void deliverMessage(MessageDispatch dispatch)
+   {
+      this.connection.deliverMessage(dispatch);
+   }
+
+   public void close() throws Exception
+   {
+      this.coreSession.close(false);
+   }
+
+   private class SendRetryTask implements Runnable
+   {
+      private ServerMessage coreMsg;
+      private AMQProducerBrokerExchange producerExchange;
+      private boolean sendProducerAck;
+      private int msgSize;
+      private int commandId;
+
+      public SendRetryTask(ServerMessage coreMsg, AMQProducerBrokerExchange producerExchange,
+            boolean sendProducerAck, int msgSize, int commandId)
+      {
+         this.coreMsg = coreMsg;
+         this.producerExchange = producerExchange;
+         this.sendProducerAck = sendProducerAck;
+         this.msgSize = msgSize;
+         this.commandId = commandId;
+      }
+
+      @Override
+      public void run()
+      {
+         synchronized (AMQSession.this)
+         {
+            try
+            {
+               // check pageStore
+               SimpleString address = coreMsg.getAddress();
+               PagingStoreImpl store = (PagingStoreImpl) server
+                     .getPagingManager().getPageStore(address);
+               if (store.isFull())
+               {
+                  // if store is still full, schedule another
+                  server.getScheduledPool().schedule(this, 10, TimeUnit.MILLISECONDS);
+               }
+               else
+               {
+                  // now send the message again.
+                  coreSession.send(coreMsg, false);
+
+                  if (sendProducerAck)
+                  {
+                     ProducerInfo producerInfo = producerExchange
+                           .getProducerState().getInfo();
+                     ProducerAck ack = new ProducerAck(
+                           producerInfo.getProducerId(), msgSize);
+                     connection.dispatchAsync(ack);
+                  }
+                  else
+                  {
+                     Response response = new Response();
+                     response.setCorrelationId(commandId);
+                     connection.dispatchAsync(response);
+                  }
+               }
+            }
+            catch (Exception e)
+            {
+               ExceptionResponse response = new ExceptionResponse(e);
+               response.setCorrelationId(commandId);
+               connection.dispatchAsync(response);
+            }
+         }
+
+      }
+   }
+
+   public void blockingWaitForSpace(AMQProducerBrokerExchange producerExchange, SendingResult result) throws IOException
+   {
+      long start = System.currentTimeMillis();
+      long nextWarn = start;
+      producerExchange.blockingOnFlowControl(true);
+
+      AMQConnectionContext context = producerExchange.getConnectionContext();
+      PagingStoreImpl store = result.getBlockPagingStore();
+
+      //Destination.DEFAULT_BLOCKED_PRODUCER_WARNING_INTERVAL
+      long blockedProducerWarningInterval = 30000;
+      ProducerId producerId = producerExchange.getProducerState().getInfo().getProducerId();
+
+      while (store.isFull())
+      {
+         if (context.getStopping().get())
+         {
+            throw new IOException("Connection closed, send aborted.");
+         }
+
+         long now = System.currentTimeMillis();
+         if (now >= nextWarn)
+         {
+            HornetQServerLogger.LOGGER.warn("Memory Limit reached. Producer (" + producerId + ") stopped to prevent flooding "
+                               + result.getBlockingAddress()
+                               + " See http://activemq.apache.org/producer-flow-control.html for more info"
+                               + " (blocking for " + ((now - start) / 1000) + "s");
+            nextWarn = now + blockedProducerWarningInterval;
+         }
+      }
+      producerExchange.blockingOnFlowControl(false);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java
new file mode 100644
index 0000000..d62956b
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSharedDeadLetterStrategy.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ActiveMQQueue;
+import org.apache.activemq.command.Message;
+
+public class AMQSharedDeadLetterStrategy extends AMQAbstractDeadLetterStrategy
+{
+   public static final String DEFAULT_DEAD_LETTER_QUEUE_NAME = "ActiveMQ.DLQ";
+
+   private ActiveMQDestination deadLetterQueue = new ActiveMQQueue(
+         DEFAULT_DEAD_LETTER_QUEUE_NAME);
+
+   public ActiveMQDestination getDeadLetterQueueFor(Message message,
+         AMQSubscription subscription)
+   {
+      return deadLetterQueue;
+   }
+
+   public ActiveMQDestination getDeadLetterQueue()
+   {
+      return deadLetterQueue;
+   }
+
+   public void setDeadLetterQueue(ActiveMQDestination deadLetterQueue)
+   {
+      this.deadLetterQueue = deadLetterQueue;
+   }
+
+   @Override
+   public boolean isDLQ(ActiveMQDestination destination)
+   {
+      if (destination.equals(deadLetterQueue))
+      {
+         return true;
+      }
+      else
+      {
+         return false;
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSingleTransportConnectionStateRegister.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSingleTransportConnectionStateRegister.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSingleTransportConnectionStateRegister.java
new file mode 100644
index 0000000..5ffe1ac
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSingleTransportConnectionStateRegister.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.activemq.command.ConnectionId;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.ProducerId;
+import org.apache.activemq.command.SessionId;
+
+/**
+ * We just copy this structure from amq, but what's the purpose
+ * and can it be removed ?
+ *
+ * @author howard
+ *
+ */
+public class AMQSingleTransportConnectionStateRegister implements
+      AMQTransportConnectionStateRegister
+{
+
+   private AMQTransportConnectionState connectionState;
+   private ConnectionId connectionId;
+
+   public AMQTransportConnectionState registerConnectionState(
+         ConnectionId connectionId, AMQTransportConnectionState state)
+   {
+      AMQTransportConnectionState rc = connectionState;
+      connectionState = state;
+      this.connectionId = connectionId;
+      return rc;
+   }
+
+   public synchronized AMQTransportConnectionState unregisterConnectionState(
+         ConnectionId connectionId)
+   {
+      AMQTransportConnectionState rc = null;
+
+      if (connectionId != null && connectionState != null
+            && this.connectionId != null)
+      {
+         if (this.connectionId.equals(connectionId))
+         {
+            rc = connectionState;
+            connectionState = null;
+            connectionId = null;
+         }
+      }
+      return rc;
+   }
+
+   public synchronized List<AMQTransportConnectionState> listConnectionStates()
+   {
+      List<AMQTransportConnectionState> rc = new ArrayList<AMQTransportConnectionState>();
+      if (connectionState != null)
+      {
+         rc.add(connectionState);
+      }
+      return rc;
+   }
+
+   public synchronized AMQTransportConnectionState lookupConnectionState(
+         String connectionId)
+   {
+      AMQTransportConnectionState cs = connectionState;
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a connectionId for a connection that had not been registered: "
+                     + connectionId);
+      }
+      return cs;
+   }
+
+   public synchronized AMQTransportConnectionState lookupConnectionState(
+         ConsumerId id)
+   {
+      AMQTransportConnectionState cs = connectionState;
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a consumer from a connection that had not been registered: "
+                     + id.getParentId().getParentId());
+      }
+      return cs;
+   }
+
+   public synchronized AMQTransportConnectionState lookupConnectionState(
+         ProducerId id)
+   {
+      AMQTransportConnectionState cs = connectionState;
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a producer from a connection that had not been registered: "
+                     + id.getParentId().getParentId());
+      }
+      return cs;
+   }
+
+   public synchronized AMQTransportConnectionState lookupConnectionState(
+         SessionId id)
+   {
+      AMQTransportConnectionState cs = connectionState;
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot lookup a session from a connection that had not been registered: "
+                     + id.getParentId());
+      }
+      return cs;
+   }
+
+   public synchronized AMQTransportConnectionState lookupConnectionState(
+         ConnectionId connectionId)
+   {
+      AMQTransportConnectionState cs = connectionState;
+      return cs;
+   }
+
+   public synchronized boolean doesHandleMultipleConnectionStates()
+   {
+      return false;
+   }
+
+   public synchronized boolean isEmpty()
+   {
+      return connectionState == null;
+   }
+
+   public void intialize(AMQTransportConnectionStateRegister other)
+   {
+
+      if (other.isEmpty())
+      {
+         clear();
+      }
+      else
+      {
+         Map map = other.mapStates();
+         Iterator i = map.entrySet().iterator();
+         Map.Entry<ConnectionId, AMQTransportConnectionState> entry = (Entry<ConnectionId, AMQTransportConnectionState>) i
+               .next();
+         connectionId = entry.getKey();
+         connectionState = entry.getValue();
+      }
+
+   }
+
+   public Map<ConnectionId, AMQTransportConnectionState> mapStates()
+   {
+      Map<ConnectionId, AMQTransportConnectionState> map = new HashMap<ConnectionId, AMQTransportConnectionState>();
+      if (!isEmpty())
+      {
+         map.put(connectionId, connectionState);
+      }
+      return map;
+   }
+
+   public void clear()
+   {
+      connectionState = null;
+      connectionId = null;
+
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java
new file mode 100644
index 0000000..71c0952
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSlowConsumerStrategy.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+public interface AMQSlowConsumerStrategy
+{
+
+   /**
+    * Slow consumer event.
+    *
+    * @param context
+    *      Connection context of the subscription.
+    * @param subs
+    *      The subscription object for the slow consumer.
+    */
+   void slowConsumer(AMQConnectionContext context, AMQSubscription subs);
+
+   /**
+    * For Strategies that need to examine assigned destination for slow consumers
+    * periodically the destination is assigned here.
+    *
+    * If the strategy doesn't is event driven it can just ignore assigned destination.
+    *
+    * @param destination
+    *      A destination to add to a watch list.
+    */
+   void addDestination(AMQDestination destination);
+
+}


[30/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java
new file mode 100644
index 0000000..95a7f61
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContext.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.client;
+
+import org.apache.qpid.proton.engine.Link;
+import org.apache.qpid.proton.engine.Session;
+import org.proton.plug.AMQPClientConnectionContext;
+import org.proton.plug.AMQPClientSessionContext;
+import org.proton.plug.ClientSASL;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.context.ProtonInitializable;
+import org.proton.plug.util.FutureRunnable;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonClientConnectionContext extends AbstractConnectionContext implements AMQPClientConnectionContext
+{
+   public ProtonClientConnectionContext(AMQPConnectionCallback connectionCallback)
+   {
+      super(connectionCallback);
+   }
+
+   // Maybe a client interface?
+   public void clientOpen(ClientSASL sasl) throws Exception
+   {
+      FutureRunnable future = new FutureRunnable(1);
+      synchronized (handler.getLock())
+      {
+         this.afterInit(future);
+         if (sasl != null)
+         {
+            handler.createClientSasl(sasl);
+         }
+         handler.getConnection().open();
+      }
+
+      flush();
+
+      waitWithTimeout(future);
+   }
+
+   public AMQPClientSessionContext createClientSession() throws HornetQAMQPException
+   {
+
+      FutureRunnable futureRunnable = new FutureRunnable(1);
+      ProtonClientSessionContext sessionImpl;
+      synchronized (handler.getLock())
+      {
+         Session session = handler.getConnection().session();
+         sessionImpl = (ProtonClientSessionContext) getSessionExtension(session);
+         sessionImpl.afterInit(futureRunnable);
+         session.open();
+      }
+
+      flush();
+      waitWithTimeout(futureRunnable);
+
+      return sessionImpl;
+   }
+
+   @Override
+   protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws HornetQAMQPException
+   {
+      AMQPSessionCallback sessionSPI = connectionCallback.createSessionCallback(this);
+      AbstractProtonSessionContext protonSession = new ProtonClientSessionContext(sessionSPI, this, realSession);
+
+      return protonSession;
+
+   }
+
+   @Override
+   protected void remoteLinkOpened(Link link) throws Exception
+   {
+      Object context = link.getContext();
+      if (context != null && context instanceof ProtonInitializable)
+      {
+         ((ProtonInitializable) context).initialise();
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java
new file mode 100644
index 0000000..11f8709
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.client;
+
+import org.proton.plug.AMQPConnectionContext;
+import org.proton.plug.AMQPConnectionContextFactory;
+import org.proton.plug.AMQPConnectionCallback;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonClientConnectionContextFactory extends AMQPConnectionContextFactory
+{
+   private static final AMQPConnectionContextFactory theInstance = new ProtonClientConnectionContextFactory();
+
+   public static AMQPConnectionContextFactory getFactory()
+   {
+      return theInstance;
+   }
+
+   public AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback)
+   {
+      return new ProtonClientConnectionContext(connectionCallback);
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java
new file mode 100644
index 0000000..f0dc46a
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientContext.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.client;
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.qpid.proton.amqp.messaging.Accepted;
+import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Sender;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.proton.plug.AMQPClientSenderContext;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonContextSender;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.util.FutureRunnable;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonClientContext extends AbstractProtonContextSender implements AMQPClientSenderContext
+{
+
+   FutureRunnable catchUpRunnable = new FutureRunnable();
+
+   public ProtonClientContext(AbstractConnectionContext connection, Sender sender, AbstractProtonSessionContext protonSession, AMQPSessionCallback server)
+   {
+      super(connection, sender, protonSession, server);
+   }
+
+
+   @Override
+   public void onMessage(Delivery delivery) throws HornetQAMQPException
+   {
+      if (delivery.getRemoteState() instanceof Accepted)
+      {
+         if (delivery.getContext() instanceof FutureRunnable)
+         {
+            ((FutureRunnable) delivery.getContext()).countDown();
+         }
+      }
+   }
+
+   public void send(ProtonJMessage message)
+   {
+      if (sender.getSenderSettleMode() != SenderSettleMode.SETTLED)
+      {
+         catchUpRunnable.countUp();
+      }
+      performSend(message, catchUpRunnable);
+   }
+
+
+   public boolean sync(long timeout, TimeUnit unit)
+   {
+      try
+      {
+         return catchUpRunnable.await(timeout, unit);
+      }
+      catch (InterruptedException e)
+      {
+         Thread.currentThread().interrupt();
+         return false;
+      }
+
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java
new file mode 100644
index 0000000..ebf7f7d
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientReceiverContext.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.client;
+
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.PooledByteBufAllocator;
+import org.apache.qpid.proton.amqp.messaging.Accepted;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.apache.qpid.proton.message.impl.MessageImpl;
+import org.proton.plug.AMQPClientReceiverContext;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonReceiverContext;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+import static org.proton.plug.util.DeliveryUtil.readDelivery;
+import static org.proton.plug.util.DeliveryUtil.decodeMessageImpl;
+
+/**
+ * @author Clebert Suconic
+ */
+public class ProtonClientReceiverContext extends AbstractProtonReceiverContext implements AMQPClientReceiverContext
+{
+   public ProtonClientReceiverContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, AbstractProtonSessionContext protonSession, Receiver receiver)
+   {
+      super(sessionSPI, connection, protonSession, receiver);
+   }
+
+   public void onFlow(int credits)
+   {
+   }
+
+   LinkedBlockingDeque<MessageImpl> queues = new LinkedBlockingDeque<>();
+
+   /*
+   * called when Proton receives a message to be delivered via a Delivery.
+   *
+   * This may be called more than once per deliver so we have to cache the buffer until we have received it all.
+   *
+   * */
+   public void onMessage(Delivery delivery) throws HornetQAMQPException
+   {
+      ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
+      try
+      {
+         synchronized (connection.getLock())
+         {
+            readDelivery(receiver, buffer);
+            MessageImpl clientMessage = decodeMessageImpl(buffer);
+
+            // This second method could be better
+//            clientMessage.decode(buffer.nioBuffer());
+
+            receiver.advance();
+            delivery.disposition(Accepted.getInstance());
+            queues.add(clientMessage);
+
+         }
+      }
+      finally
+      {
+         buffer.release();
+      }
+   }
+
+
+   @Override
+   public ProtonJMessage receiveMessage(int time, TimeUnit unit) throws Exception
+   {
+      return queues.poll(time, unit);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java
new file mode 100644
index 0000000..e888ea9
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientSessionContext.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.client;
+
+import org.apache.qpid.proton.amqp.messaging.Source;
+import org.apache.qpid.proton.amqp.messaging.Target;
+import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.engine.Sender;
+import org.apache.qpid.proton.engine.Session;
+import org.proton.plug.AMQPClientReceiverContext;
+import org.proton.plug.AMQPClientSenderContext;
+import org.proton.plug.AMQPClientSessionContext;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.util.FutureRunnable;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonClientSessionContext extends AbstractProtonSessionContext implements AMQPClientSessionContext
+{
+   public ProtonClientSessionContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, Session session)
+   {
+      super(sessionSPI, connection, session);
+   }
+
+   public AMQPClientSenderContext createSender(String address, boolean preSettled) throws HornetQAMQPException
+   {
+      FutureRunnable futureRunnable = new FutureRunnable(1);
+
+      ProtonClientContext amqpSender;
+      synchronized (connection.getLock())
+      {
+         Sender sender = session.sender(address);
+         sender.setSenderSettleMode(SenderSettleMode.SETTLED);
+         Target target = new Target();
+         target.setAddress(address);
+         sender.setTarget(target);
+         amqpSender = new ProtonClientContext(connection, sender, this, sessionSPI);
+         amqpSender.afterInit(futureRunnable);
+         sender.setContext(amqpSender);
+         sender.open();
+      }
+
+      connection.flush();
+
+      waitWithTimeout(futureRunnable);
+      return amqpSender;
+   }
+
+   public AMQPClientReceiverContext createReceiver(String address) throws HornetQAMQPException
+   {
+      FutureRunnable futureRunnable = new FutureRunnable(1);
+
+      ProtonClientReceiverContext amqpReceiver;
+
+      synchronized (connection.getLock())
+      {
+         Receiver receiver = session.receiver(address);
+         Source source = new Source();
+         source.setAddress(address);
+         receiver.setSource(source);
+         amqpReceiver = new ProtonClientReceiverContext(sessionSPI, connection, this, receiver);
+         receiver.setContext(amqpReceiver);
+         amqpReceiver.afterInit(futureRunnable);
+         receiver.open();
+      }
+
+      connection.flush();
+
+      waitWithTimeout(futureRunnable);
+
+      return amqpReceiver;
+
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java
new file mode 100644
index 0000000..1d83e54
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContext.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.server;
+
+import org.apache.qpid.proton.amqp.transaction.Coordinator;
+import org.apache.qpid.proton.engine.Link;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.engine.Sender;
+import org.apache.qpid.proton.engine.Session;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPServerConnectionContext;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonServerConnectionContext extends AbstractConnectionContext implements AMQPServerConnectionContext
+{
+   public ProtonServerConnectionContext(AMQPConnectionCallback connectionSP)
+   {
+      super(connectionSP);
+   }
+
+   protected AbstractProtonSessionContext newSessionExtension(Session realSession) throws HornetQAMQPException
+   {
+      AMQPSessionCallback sessionSPI = connectionCallback.createSessionCallback(this);
+      AbstractProtonSessionContext protonSession = new ProtonServerSessionContext(sessionSPI, this, realSession);
+
+      return protonSession;
+   }
+
+   protected void remoteLinkOpened(Link link) throws Exception
+   {
+
+      ProtonServerSessionContext protonSession = (ProtonServerSessionContext) getSessionExtension(link.getSession());
+
+      link.setSource(link.getRemoteSource());
+      link.setTarget(link.getRemoteTarget());
+      if (link instanceof Receiver)
+      {
+         Receiver receiver = (Receiver) link;
+         if (link.getRemoteTarget() instanceof Coordinator)
+         {
+            Coordinator coordinator = (Coordinator) link.getRemoteTarget();
+            protonSession.addTransactionHandler(coordinator, receiver);
+         }
+         else
+         {
+            protonSession.addReceiver(receiver);
+            receiver.flow(100);
+         }
+      }
+      else
+      {
+         Sender sender = (Sender) link;
+         protonSession.addSender(sender);
+         sender.offer(1);
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java
new file mode 100644
index 0000000..22e3675
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerConnectionContextFactory.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.server;
+
+import org.proton.plug.AMQPConnectionContextFactory;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPServerConnectionContext;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonServerConnectionContextFactory extends AMQPConnectionContextFactory
+{
+   private static final ProtonServerConnectionContextFactory theInstance = new ProtonServerConnectionContextFactory();
+
+   public static ProtonServerConnectionContextFactory getFactory()
+   {
+      return theInstance;
+   }
+
+   public AMQPServerConnectionContext createConnection(AMQPConnectionCallback connectionCallback)
+   {
+      ProtonServerConnectionContext connection = new ProtonServerConnectionContext(connectionCallback);
+      return connection;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java
new file mode 100644
index 0000000..21ca2bc
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerReceiverContext.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.server;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.PooledByteBufAllocator;
+import org.apache.qpid.proton.amqp.Symbol;
+import org.apache.qpid.proton.amqp.messaging.Accepted;
+import org.apache.qpid.proton.amqp.messaging.Rejected;
+import org.apache.qpid.proton.amqp.transport.ErrorCondition;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Receiver;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonReceiverContext;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.exceptions.HornetQAMQPInternalErrorException;
+import org.proton.plug.logger.HornetQAMQPProtocolMessageBundle;
+
+import static org.proton.plug.util.DeliveryUtil.readDelivery;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonServerReceiverContext extends AbstractProtonReceiverContext
+{
+
+   private final int numberOfCredits = 100;
+
+   public ProtonServerReceiverContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, AbstractProtonSessionContext protonSession, Receiver receiver)
+   {
+      super(sessionSPI, connection, protonSession, receiver);
+   }
+
+   public void onFlow(int credits)
+   {
+   }
+
+
+   @Override
+   public void initialise() throws Exception
+   {
+      super.initialise();
+      org.apache.qpid.proton.amqp.messaging.Target target = (org.apache.qpid.proton.amqp.messaging.Target) receiver.getRemoteTarget();
+
+      if (target != null)
+      {
+         if (target.getDynamic())
+         {
+            //if dynamic we have to create the node (queue) and set the address on the target, the node is temporary and
+            // will be deleted on closing of the session
+            String queue = sessionSPI.tempQueueName();
+
+
+            try
+            {
+               sessionSPI.createTemporaryQueue(queue);
+            }
+            catch (Exception e)
+            {
+               throw new HornetQAMQPInternalErrorException(e.getMessage(), e);
+            }
+            target.setAddress(queue.toString());
+         }
+         else
+         {
+            //if not dynamic then we use the targets address as the address to forward the messages to, however there has to
+            //be a queue bound to it so we nee to check this.
+            String address = target.getAddress();
+            if (address == null)
+            {
+               throw HornetQAMQPProtocolMessageBundle.BUNDLE.targetAddressNotSet();
+            }
+            try
+            {
+               if (!sessionSPI.queueQuery(address))
+               {
+                  throw HornetQAMQPProtocolMessageBundle.BUNDLE.addressDoesntExist();
+               }
+            }
+            catch (Exception e)
+            {
+               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorFindingTemporaryQueue(e.getMessage());
+            }
+         }
+      }
+
+      flow(numberOfCredits);
+   }
+
+   /*
+   * called when Proton receives a message to be delivered via a Delivery.
+   *
+   * This may be called more than once per deliver so we have to cache the buffer until we have received it all.
+   *
+   * */
+   public void onMessage(Delivery delivery) throws HornetQAMQPException
+   {
+      Receiver receiver;
+      try
+      {
+         receiver = ((Receiver) delivery.getLink());
+
+         if (!delivery.isReadable())
+         {
+            System.err.println("!!!!! Readable!!!!!!!");
+            return;
+         }
+
+         ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(10 * 1024);
+         try
+         {
+            synchronized (connection.getLock())
+            {
+               readDelivery(receiver, buffer);
+
+               receiver.advance();
+
+               sessionSPI.serverSend(receiver, delivery, address, delivery.getMessageFormat(), buffer);
+               delivery.disposition(Accepted.getInstance());
+               delivery.settle();
+
+               if (receiver.getRemoteCredit() < numberOfCredits / 2)
+               {
+                  flow(numberOfCredits);
+               }
+            }
+         }
+         finally
+         {
+            buffer.release();
+         }
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+         Rejected rejected = new Rejected();
+         ErrorCondition condition = new ErrorCondition();
+         condition.setCondition(Symbol.valueOf("failed"));
+         condition.setDescription(e.getMessage());
+         rejected.setError(condition);
+         delivery.disposition(rejected);
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java
new file mode 100644
index 0000000..9b66de0
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSenderContext.java
@@ -0,0 +1,283 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.server;
+
+import java.util.Map;
+
+import org.apache.qpid.proton.amqp.DescribedType;
+import org.apache.qpid.proton.amqp.Symbol;
+import org.apache.qpid.proton.amqp.messaging.Accepted;
+import org.apache.qpid.proton.amqp.messaging.Modified;
+import org.apache.qpid.proton.amqp.messaging.Rejected;
+import org.apache.qpid.proton.amqp.messaging.Released;
+import org.apache.qpid.proton.amqp.transport.DeliveryState;
+import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Sender;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonContextSender;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.exceptions.HornetQAMQPInternalErrorException;
+import org.proton.plug.logger.HornetQAMQPProtocolMessageBundle;
+import org.proton.plug.context.ProtonPlugSender;
+import org.apache.qpid.proton.amqp.messaging.Source;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonServerSenderContext extends AbstractProtonContextSender implements ProtonPlugSender
+{
+
+   private static final Symbol SELECTOR = Symbol.getSymbol("jms-selector");
+   private static final Symbol COPY = Symbol.valueOf("copy");
+
+   private Object brokerConsumer;
+
+   public ProtonServerSenderContext(AbstractConnectionContext connection, Sender sender, AbstractProtonSessionContext protonSession, AMQPSessionCallback server)
+   {
+      super(connection, sender, protonSession, server);
+   }
+
+   public Object getBrokerConsumer()
+   {
+      return brokerConsumer;
+   }
+
+   public void onFlow(int currentCredits)
+   {
+      super.onFlow(currentCredits);
+      sessionSPI.onFlowConsumer(brokerConsumer, currentCredits);
+   }
+
+   /*
+* start the session
+* */
+   public void start() throws HornetQAMQPException
+   {
+      super.start();
+      // protonSession.getServerSession().start();
+
+      //todo add flow control
+      try
+      {
+         // to do whatever you need to make the broker start sending messages to the consumer
+         sessionSPI.startSender(brokerConsumer);
+         //protonSession.getServerSession().receiveConsumerCredits(consumerID, -1);
+      }
+      catch (Exception e)
+      {
+         throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorStartingConsumer(e.getMessage());
+      }
+   }
+
+   /**
+    * create the actual underlying HornetQ Server Consumer
+    */
+   @Override
+   public void initialise() throws Exception
+   {
+      super.initialise();
+
+      Source source = (Source) sender.getRemoteSource();
+
+      String queue;
+
+      String selector = null;
+      Map filter = source == null ? null : source.getFilter();
+      if (filter != null)
+      {
+         DescribedType value = (DescribedType) filter.get(SELECTOR);
+         if (value != null)
+         {
+            selector = value.getDescribed().toString();
+         }
+      }
+
+      if (source != null)
+      {
+         if (source.getDynamic())
+         {
+            //if dynamic we have to create the node (queue) and set the address on the target, the node is temporary and
+            // will be deleted on closing of the session
+            queue = java.util.UUID.randomUUID().toString();
+            try
+            {
+               sessionSPI.createTemporaryQueue(queue);
+               //protonSession.getServerSession().createQueue(queue, queue, null, true, false);
+            }
+            catch (Exception e)
+            {
+               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCreatingTemporaryQueue(e.getMessage());
+            }
+            source.setAddress(queue);
+         }
+         else
+         {
+            //if not dynamic then we use the targets address as the address to forward the messages to, however there has to
+            //be a queue bound to it so we nee to check this.
+            queue = source.getAddress();
+            if (queue == null)
+            {
+               throw HornetQAMQPProtocolMessageBundle.BUNDLE.sourceAddressNotSet();
+            }
+
+            try
+            {
+               if (!sessionSPI.queueQuery(queue))
+               {
+                  throw HornetQAMQPProtocolMessageBundle.BUNDLE.sourceAddressDoesntExist();
+               }
+            }
+            catch (Exception e)
+            {
+               throw new HornetQAMQPInternalErrorException(e.getMessage(), e);
+            }
+         }
+
+         boolean browseOnly = source.getDistributionMode() != null && source.getDistributionMode().equals(COPY);
+         try
+         {
+            brokerConsumer = sessionSPI.createSender(this, queue, selector, browseOnly);
+         }
+         catch (Exception e)
+         {
+            throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCreatingHornetQConsumer(e.getMessage());
+         }
+      }
+   }
+
+   /*
+   * close the session
+   * */
+   public void close() throws HornetQAMQPException
+   {
+      super.close();
+      try
+      {
+         sessionSPI.closeSender(brokerConsumer);
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+         throw new HornetQAMQPInternalErrorException(e.getMessage());
+      }
+   }
+
+
+   public void onMessage(Delivery delivery) throws HornetQAMQPException
+   {
+      Object message = delivery.getContext();
+
+      boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;
+
+
+      DeliveryState remoteState = delivery.getRemoteState();
+
+      if (remoteState != null)
+      {
+         if (remoteState instanceof Accepted)
+         {
+            //we have to individual ack as we can't guarantee we will get the delivery updates (including acks) in order
+            // from dealer, a perf hit but a must
+            try
+            {
+               sessionSPI.ack(brokerConsumer, message);
+            }
+            catch (Exception e)
+            {
+               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorAcknowledgingMessage(message.toString(), e.getMessage());
+            }
+         }
+         else if (remoteState instanceof Released)
+         {
+            try
+            {
+               sessionSPI.cancel(brokerConsumer, message, false);
+            }
+            catch (Exception e)
+            {
+               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCancellingMessage(message.toString(), e.getMessage());
+            }
+         }
+         else if (remoteState instanceof Rejected || remoteState instanceof Modified)
+         {
+            try
+            {
+               sessionSPI.cancel(brokerConsumer, message, true);
+            }
+            catch (Exception e)
+            {
+               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCancellingMessage(message.toString(), e.getMessage());
+            }
+         }
+         //todo add tag caching
+         if (!preSettle)
+         {
+            protonSession.replaceTag(delivery.getTag());
+         }
+
+         synchronized (connection.getLock())
+         {
+            delivery.settle();
+            sender.offer(1);
+         }
+
+      }
+      else
+      {
+         //todo not sure if we need to do anything here
+      }
+   }
+
+   @Override
+   public synchronized void checkState()
+   {
+      super.checkState();
+      sessionSPI.resumeDelivery(brokerConsumer);
+   }
+
+
+   /**
+    * handle an out going message from HornetQ, send via the Proton Sender
+    */
+   public int deliverMessage(Object message, int deliveryCount) throws Exception
+   {
+      if (closed)
+      {
+         System.err.println("Message can't be delivered as it's closed");
+         return 0;
+      }
+
+      //encode the message
+      ProtonJMessage serverMessage;
+      try
+      {
+         // This can be done a lot better here
+         serverMessage = sessionSPI.encodeMessage(message, deliveryCount);
+      }
+      catch (Throwable e)
+      {
+         e.printStackTrace();
+         throw new HornetQAMQPInternalErrorException(e.getMessage(), e);
+      }
+
+      return performSend(serverMessage, message);
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java
new file mode 100644
index 0000000..1860c90
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/server/ProtonServerSessionContext.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context.server;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.qpid.proton.amqp.transaction.Coordinator;
+import org.apache.qpid.proton.amqp.transport.ErrorCondition;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.engine.Sender;
+import org.apache.qpid.proton.engine.Session;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.context.AbstractConnectionContext;
+import org.proton.plug.context.AbstractProtonContextSender;
+import org.proton.plug.context.AbstractProtonReceiverContext;
+import org.proton.plug.context.AbstractProtonSessionContext;
+import org.proton.plug.context.ProtonTransactionHandler;
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonServerSessionContext extends AbstractProtonSessionContext
+{
+
+   public ProtonServerSessionContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, Session session)
+   {
+      super(sessionSPI, connection, session);
+   }
+
+   protected Map<Object, AbstractProtonContextSender> serverSenders = new HashMap<Object, AbstractProtonContextSender>();
+
+
+   /**
+    * The consumer object from the broker or the key used to store the sender
+    *
+    * @param message
+    * @param consumer
+    * @param deliveryCount
+    * @return the number of bytes sent
+    */
+   public int serverDelivery(Object message, Object consumer, int deliveryCount) throws Exception
+   {
+      ProtonServerSenderContext protonSender = (ProtonServerSenderContext) serverSenders.get(consumer);
+      if (protonSender != null)
+      {
+         return protonSender.deliverMessage(message, deliveryCount);
+      }
+      return 0;
+   }
+
+   public void addTransactionHandler(Coordinator coordinator, Receiver receiver)
+   {
+      ProtonTransactionHandler transactionHandler = new ProtonTransactionHandler(sessionSPI);
+      receiver.setContext(transactionHandler);
+      receiver.open();
+      receiver.flow(100);
+   }
+
+   public void addSender(Sender sender) throws Exception
+   {
+      ProtonServerSenderContext protonSender = new ProtonServerSenderContext(connection, sender, this, sessionSPI);
+
+      try
+      {
+         protonSender.initialise();
+         senders.put(sender, protonSender);
+         serverSenders.put(protonSender.getBrokerConsumer(), protonSender);
+         sender.setContext(protonSender);
+         sender.open();
+         protonSender.start();
+      }
+      catch (HornetQAMQPException e)
+      {
+         senders.remove(sender);
+         sender.setSource(null);
+         sender.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
+         sender.close();
+      }
+   }
+
+   public void removeSender(Sender sender) throws HornetQAMQPException
+   {
+      ProtonServerSenderContext senderRemoved = (ProtonServerSenderContext) senders.remove(sender);
+      if (senderRemoved != null)
+      {
+         serverSenders.remove(senderRemoved.getBrokerConsumer());
+      }
+   }
+
+
+   public void addReceiver(Receiver receiver) throws Exception
+   {
+      try
+      {
+         AbstractProtonReceiverContext protonReceiver = new ProtonServerReceiverContext(sessionSPI, connection, this, receiver);
+         protonReceiver.initialise();
+         receivers.put(receiver, protonReceiver);
+         receiver.setContext(protonReceiver);
+         receiver.open();
+      }
+      catch (HornetQAMQPException e)
+      {
+         receivers.remove(receiver);
+         receiver.setTarget(null);
+         receiver.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
+         receiver.close();
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPException.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPException.java
new file mode 100644
index 0000000..0a3c68a
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPException.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.exceptions;
+
+import org.apache.qpid.proton.amqp.Symbol;
+
+/**
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ *         6/6/13
+ */
+public class HornetQAMQPException extends Exception
+{
+
+   private static final String ERROR_PREFIX = "amqp:";
+
+   public Symbol getAmqpError()
+   {
+      return amqpError;
+   }
+
+   private final Symbol amqpError;
+
+   public HornetQAMQPException(Symbol amqpError, String message, Throwable e)
+   {
+      super(message, e);
+      this.amqpError = amqpError;
+   }
+
+   public HornetQAMQPException(Symbol amqpError, String message)
+   {
+      super(message);
+      this.amqpError = amqpError;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPIllegalStateException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPIllegalStateException.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPIllegalStateException.java
new file mode 100644
index 0000000..f3e3b38
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPIllegalStateException.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.exceptions;
+
+import org.apache.qpid.proton.amqp.transport.AmqpError;
+
+/**
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ *         6/6/13
+ */
+public class HornetQAMQPIllegalStateException extends HornetQAMQPException
+{
+   public HornetQAMQPIllegalStateException(String message)
+   {
+      super(AmqpError.ILLEGAL_STATE, message);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInternalErrorException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInternalErrorException.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInternalErrorException.java
new file mode 100644
index 0000000..7db34a7
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInternalErrorException.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.exceptions;
+
+import org.apache.qpid.proton.amqp.transport.AmqpError;
+
+/**
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ *         6/6/13
+ */
+public class HornetQAMQPInternalErrorException extends HornetQAMQPException
+{
+   public HornetQAMQPInternalErrorException(String message, Throwable e)
+   {
+      super(AmqpError.INTERNAL_ERROR, message, e);
+   }
+
+   public HornetQAMQPInternalErrorException(String message)
+   {
+      super(AmqpError.INTERNAL_ERROR, message);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInvalidFieldException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInvalidFieldException.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInvalidFieldException.java
new file mode 100644
index 0000000..2f73de8
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPInvalidFieldException.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.exceptions;
+
+import org.apache.qpid.proton.amqp.transport.AmqpError;
+
+/**
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ *         6/6/13
+ */
+public class HornetQAMQPInvalidFieldException extends HornetQAMQPException
+{
+   public HornetQAMQPInvalidFieldException(String message)
+   {
+      super(AmqpError.INVALID_FIELD, message);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPNotImplementedException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPNotImplementedException.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPNotImplementedException.java
new file mode 100644
index 0000000..35a2143
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPNotImplementedException.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.exceptions;
+
+import org.apache.qpid.proton.amqp.transport.AmqpError;
+
+/**
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ *         6/19/13
+ */
+public class HornetQAMQPNotImplementedException extends HornetQAMQPException
+{
+   public HornetQAMQPNotImplementedException(String message)
+   {
+      super(AmqpError.NOT_IMPLEMENTED, message);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPTimeoutException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPTimeoutException.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPTimeoutException.java
new file mode 100644
index 0000000..50d72d8
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/exceptions/HornetQAMQPTimeoutException.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.exceptions;
+
+import org.apache.qpid.proton.amqp.transport.AmqpError;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class HornetQAMQPTimeoutException extends HornetQAMQPException
+{
+   public HornetQAMQPTimeoutException(String message)
+   {
+      super(AmqpError.ILLEGAL_STATE, message);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java
new file mode 100644
index 0000000..482821a
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/EventHandler.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.handler;
+
+import org.apache.qpid.proton.engine.Connection;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Link;
+import org.apache.qpid.proton.engine.Session;
+import org.apache.qpid.proton.engine.Transport;
+
+/**
+ * EventHandler
+ * <p/>
+ *
+ * @author rhs
+ */
+
+public interface EventHandler
+{
+
+   void onSASLInit(ProtonHandler handler, Connection connection);
+
+   void onInit(Connection connection) throws Exception;
+
+   void onLocalOpen(Connection connection) throws Exception;
+
+   void onRemoteOpen(Connection connection) throws Exception;
+
+   void onLocalClose(Connection connection) throws Exception;
+
+   void onRemoteClose(Connection connection) throws Exception;
+
+   void onFinal(Connection connection) throws Exception;
+
+   void onInit(Session session) throws Exception;
+
+   void onLocalOpen(Session session) throws Exception;
+
+   void onRemoteOpen(Session session) throws Exception;
+
+   void onLocalClose(Session session) throws Exception;
+
+   void onRemoteClose(Session session) throws Exception;
+
+   void onFinal(Session session) throws Exception;
+
+   void onInit(Link link) throws Exception;
+
+   void onLocalOpen(Link link) throws Exception;
+
+   void onRemoteOpen(Link link) throws Exception;
+
+   void onLocalClose(Link link) throws Exception;
+
+   void onRemoteClose(Link link) throws Exception;
+
+   void onFlow(Link link) throws Exception;
+
+   void onFinal(Link link) throws Exception;
+
+   void onRemoteDetach(Link link) throws Exception;
+
+   void onDetach(Link link) throws Exception;
+
+   void onDelivery(Delivery delivery) throws Exception;
+
+   void onTransport(Transport transport) throws Exception;
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/Events.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/Events.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/Events.java
new file mode 100644
index 0000000..4d58aa1
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/Events.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.handler;
+
+import org.apache.qpid.proton.engine.Event;
+import org.apache.qpid.proton.engine.Transport;
+
+/**
+ * TODO : this needs a better home
+ *
+ * @author rhs
+ */
+
+public final class Events
+{
+
+   public static void dispatchTransport(Transport transport, EventHandler handler) throws Exception
+   {
+      handler.onTransport(transport);
+   }
+
+   public static void dispatch(Event event, EventHandler handler) throws Exception
+   {
+      switch (event.getType())
+      {
+         case CONNECTION_INIT:
+            handler.onInit(event.getConnection());
+            break;
+         case CONNECTION_LOCAL_OPEN:
+            handler.onLocalOpen(event.getConnection());
+            break;
+         case CONNECTION_REMOTE_OPEN:
+            handler.onRemoteOpen(event.getConnection());
+            break;
+         case CONNECTION_LOCAL_CLOSE:
+            handler.onLocalClose(event.getConnection());
+            break;
+         case CONNECTION_REMOTE_CLOSE:
+            handler.onRemoteClose(event.getConnection());
+            break;
+         case CONNECTION_FINAL:
+            handler.onFinal(event.getConnection());
+            break;
+         case SESSION_INIT:
+            handler.onInit(event.getSession());
+            break;
+         case SESSION_LOCAL_OPEN:
+            handler.onLocalOpen(event.getSession());
+            break;
+         case SESSION_REMOTE_OPEN:
+            handler.onRemoteOpen(event.getSession());
+            break;
+         case SESSION_LOCAL_CLOSE:
+            handler.onLocalClose(event.getSession());
+            break;
+         case SESSION_REMOTE_CLOSE:
+            handler.onRemoteClose(event.getSession());
+            break;
+         case SESSION_FINAL:
+            handler.onFinal(event.getSession());
+            break;
+         case LINK_INIT:
+            handler.onInit(event.getLink());
+            break;
+         case LINK_LOCAL_OPEN:
+            handler.onLocalOpen(event.getLink());
+            break;
+         case LINK_REMOTE_OPEN:
+            handler.onRemoteOpen(event.getLink());
+            break;
+         case LINK_LOCAL_CLOSE:
+            handler.onLocalClose(event.getLink());
+            break;
+         case LINK_REMOTE_CLOSE:
+            handler.onRemoteClose(event.getLink());
+            break;
+         case LINK_FLOW:
+            handler.onFlow(event.getLink());
+            break;
+         case LINK_FINAL:
+            handler.onFinal(event.getLink());
+            break;
+         case LINK_LOCAL_DETACH:
+            handler.onDetach(event.getLink());
+            break;
+         case LINK_REMOTE_DETACH:
+            handler.onRemoteDetach(event.getLink());
+            break;
+         case TRANSPORT:
+            handler.onTransport(event.getTransport());
+            break;
+         case DELIVERY:
+            handler.onDelivery(event.getDelivery());
+            break;
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java
new file mode 100644
index 0000000..99f4658
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/ProtonHandler.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.handler;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.qpid.proton.engine.Connection;
+import org.apache.qpid.proton.engine.Transport;
+import org.proton.plug.ClientSASL;
+import org.proton.plug.ServerSASL;
+import org.proton.plug.SASLResult;
+import org.proton.plug.handler.impl.ProtonHandlerImpl;
+
+/**
+ * This is a definition of the public interface for {@link org.proton.plug.handler.impl.ProtonHandlerImpl}
+ *
+ * @author Clebert Suconic
+ */
+
+public interface ProtonHandler
+{
+
+   public static final class Factory
+   {
+      public static ProtonHandler create()
+      {
+         return new ProtonHandlerImpl();
+      }
+   }
+
+
+   /**
+    * It returns true if the transport connection has any capacity available
+    *
+    * @return
+    */
+   int capacity();
+
+   Transport getTransport();
+
+   Connection getConnection();
+
+   /**
+    * Add an event handler to the chain
+    *
+    * @param handler
+    * @return
+    */
+   ProtonHandler addEventHandler(EventHandler handler);
+
+   void createClientSasl(ClientSASL clientSASL);
+
+   /**
+    * To be used on server connections. To define SASL integration.
+    *
+    * @param handlers
+    */
+   void createServerSASL(ServerSASL[] handlers);
+
+   /**
+    * To return the SASL Mechanism that was successful with the connection.
+    * This should contain any state such as user and password
+    *
+    * @return
+    */
+   SASLResult getSASLResult();
+
+   /**
+    * The input on the Handler.
+    * Notice that buffer will be positioned up to where we needed
+    *
+    * @param buffer
+    */
+   void inputBuffer(ByteBuf buffer);
+
+   /**
+    * To be used at your discretion to verify if the client was active since you last checked
+    * it can be used to implement server TTL cleanup and verifications
+    *
+    * @return
+    */
+   boolean checkDataReceived();
+
+   /**
+    * Return the creation time of the handler
+    *
+    * @return
+    */
+   long getCreationTime();
+
+   /**
+    * To be called after you used the outputBuffer
+    *
+    * @param bytes number of bytes you used already on the output
+    */
+   void outputDone(int bytes);
+
+   /**
+    * it will return pending bytes you have on the Transport
+    * after you are done with it you must call {@link #outputDone(int)}
+    *
+    * @return
+    */
+   ByteBuf outputBuffer();
+
+   /**
+    * It will process the transport and cause events to be called
+    */
+   void flush();
+
+   /**
+    * It will close the connection and flush events
+    */
+   void close();
+
+
+   /**
+    * Get the object used to lock transport, connection and events operations
+    *
+    * @return
+    */
+   Object getLock();
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java
new file mode 100644
index 0000000..2e1be00
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/DefaultEventHandler.java
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.handler.impl;
+
+import org.apache.qpid.proton.engine.Connection;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Link;
+import org.apache.qpid.proton.engine.Session;
+import org.apache.qpid.proton.engine.Transport;
+import org.proton.plug.handler.EventHandler;
+
+/**
+ * This is useful for cases where you only want to implement a few methods
+ *
+ * @author Clebert Suconic
+ */
+public abstract class DefaultEventHandler implements EventHandler
+{
+   @Override
+   public void onInit(Connection connection) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onLocalOpen(Connection connection) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onRemoteOpen(Connection connection) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onLocalClose(Connection connection) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onRemoteClose(Connection connection) throws Exception
+   {
+   }
+
+   @Override
+   public void onFinal(Connection connection) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onInit(Session session) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onLocalOpen(Session session) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onRemoteOpen(Session session) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onLocalClose(Session session) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onRemoteClose(Session session) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onFinal(Session session) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onInit(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onLocalOpen(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onRemoteOpen(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onLocalClose(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onRemoteClose(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onFlow(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onFinal(Link link) throws Exception
+   {
+
+   }
+
+
+   @Override
+   public void onRemoteDetach(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onDetach(Link link) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onDelivery(Delivery delivery) throws Exception
+   {
+
+   }
+
+   @Override
+   public void onTransport(Transport transport) throws Exception
+   {
+
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java
new file mode 100644
index 0000000..3eb7093
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/handler/impl/ProtonHandlerImpl.java
@@ -0,0 +1,423 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.handler.impl;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.PooledByteBufAllocator;
+import org.apache.qpid.proton.Proton;
+import org.apache.qpid.proton.amqp.transport.ErrorCondition;
+import org.apache.qpid.proton.engine.Collector;
+import org.apache.qpid.proton.engine.Connection;
+import org.apache.qpid.proton.engine.Event;
+import org.apache.qpid.proton.engine.Sasl;
+import org.apache.qpid.proton.engine.Transport;
+import org.proton.plug.ClientSASL;
+import org.proton.plug.ServerSASL;
+import org.proton.plug.handler.EventHandler;
+import org.proton.plug.handler.Events;
+import org.proton.plug.handler.ProtonHandler;
+import org.proton.plug.context.ProtonInitializable;
+import org.proton.plug.SASLResult;
+import org.proton.plug.util.ByteUtil;
+import org.proton.plug.util.DebugInfo;
+
+/**
+ * Clebert Suconic
+ */
+public class ProtonHandlerImpl extends ProtonInitializable implements ProtonHandler
+{
+   private final Transport transport = Proton.transport();
+
+   private final Connection connection = Proton.connection();
+
+   private final Collector collector = Proton.collector();
+
+   private ArrayList<EventHandler> handlers = new ArrayList<>();
+
+   private Sasl serverSasl;
+
+   private Sasl clientSasl;
+
+   private final Object lock = new Object();
+
+   private final long creationTime;
+
+   private Map<String, ServerSASL> saslHandlers;
+
+   private SASLResult saslResult;
+
+   /**
+    * If dispatching a dispatch call is ignored to avoid infinite stack loop
+    */
+   private boolean dispatching = false;
+
+   protected volatile boolean dataReceived;
+
+   protected boolean receivedFirstPacket = false;
+
+   private int offset = 0;
+
+   public ProtonHandlerImpl()
+   {
+      this.creationTime = System.currentTimeMillis();
+      transport.bind(connection);
+      connection.collect(collector);
+   }
+
+   @Override
+   public int capacity()
+   {
+      synchronized (lock)
+      {
+         return transport.capacity();
+      }
+   }
+
+   public Object getLock()
+   {
+      return lock;
+   }
+
+   @Override
+   public Transport getTransport()
+   {
+      return transport;
+   }
+
+   @Override
+   public Connection getConnection()
+   {
+      return connection;
+   }
+
+   @Override
+   public ProtonHandler addEventHandler(EventHandler handler)
+   {
+      handlers.add(handler);
+      return this;
+   }
+
+   @Override
+   public void createServerSASL(ServerSASL[] handlers)
+   {
+      this.serverSasl = transport.sasl();
+      saslHandlers = new HashMap<>();
+      String[] names = new String[handlers.length];
+      int count = 0;
+      for (ServerSASL handler : handlers)
+      {
+         saslHandlers.put(handler.getName(), handler);
+         names[count++] = handler.getName();
+      }
+      this.serverSasl.server();
+      serverSasl.setMechanisms(names);
+
+   }
+
+   @Override
+   public SASLResult getSASLResult()
+   {
+      return saslResult;
+   }
+
+   @Override
+   public void inputBuffer(ByteBuf buffer)
+   {
+      dataReceived = true;
+      synchronized (lock)
+      {
+         while (buffer.readableBytes() > 0)
+         {
+            int capacity = transport.capacity();
+
+            if (!receivedFirstPacket)
+            {
+               try
+               {
+                  if (buffer.getByte(4) == 0x03)
+                  {
+                     dispatchSASL();
+                  }
+               }
+               catch (Throwable ignored)
+               {
+                  ignored.printStackTrace();
+               }
+
+               receivedFirstPacket = true;
+            }
+
+
+            if (capacity > 0)
+            {
+               ByteBuffer tail = transport.tail();
+               int min = Math.min(capacity, buffer.readableBytes());
+               tail.limit(min);
+               buffer.readBytes(tail);
+
+
+               flush();
+            }
+            else
+            {
+               if (capacity == 0)
+               {
+                  System.out.println("abandoning: " + buffer.readableBytes());
+               }
+               else
+               {
+                  System.out.println("transport closed, discarding: " + buffer.readableBytes() + " capacity = " + transport.capacity());
+               }
+               break;
+            }
+         }
+      }
+   }
+
+
+   @Override
+   public boolean checkDataReceived()
+   {
+      boolean res = dataReceived;
+
+      dataReceived = false;
+
+      return res;
+   }
+
+   @Override
+   public long getCreationTime()
+   {
+      return creationTime;
+   }
+
+   @Override
+   public void outputDone(int bytes)
+   {
+      synchronized (lock)
+      {
+         transport.pop(bytes);
+         offset -= bytes;
+
+         if (offset < 0)
+         {
+            throw new IllegalStateException("You called outputDone for more bytes than you actually received. numberOfBytes=" + bytes +
+                                               ", outcome result=" + offset);
+         }
+      }
+
+      flush();
+   }
+
+   @Override
+   public ByteBuf outputBuffer()
+   {
+
+      synchronized (lock)
+      {
+         int pending = transport.pending();
+
+         if (pending < 0)
+         {
+            return null;//throw new IllegalStateException("xxx need to close the connection");
+         }
+
+         int size = pending - offset;
+
+         if (size < 0)
+         {
+            throw new IllegalStateException("negative size: " + pending);
+         }
+
+         if (size == 0)
+         {
+            return null;
+         }
+
+         // For returning PooledBytes
+         ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer(size);
+         ByteBuffer head = transport.head();
+         head.position(offset);
+         buffer.writeBytes(head);
+         offset += size; // incrementing offset for future calls
+         return buffer;
+      }
+   }
+
+   public void createClientSasl(ClientSASL clientSASL)
+   {
+      if (clientSASL != null)
+      {
+         clientSasl = transport.sasl();
+         clientSasl.setMechanisms(clientSASL.getName());
+         byte[] initialSasl = clientSASL.getBytes();
+         clientSasl.send(initialSasl, 0, initialSasl.length);
+      }
+   }
+
+
+   @Override
+   public void flush()
+   {
+      synchronized (lock)
+      {
+         transport.process();
+
+         checkServerSASL();
+
+         if (dispatching)
+         {
+            return;
+         }
+
+         dispatching = true;
+
+      }
+
+      try
+      {
+         dispatch();
+      }
+      finally
+      {
+         dispatching = false;
+      }
+   }
+
+   @Override
+   public void close()
+   {
+      synchronized (lock)
+      {
+         connection.close();
+      }
+      flush();
+   }
+
+   protected void checkServerSASL()
+   {
+      if (serverSasl != null && serverSasl.getRemoteMechanisms().length > 0)
+      {
+         // TODO: should we look at the first only?
+         ServerSASL mechanism = saslHandlers.get(serverSasl.getRemoteMechanisms()[0]);
+         if (mechanism != null)
+         {
+
+            byte[] dataSASL = new byte[serverSasl.pending()];
+            serverSasl.recv(dataSASL, 0, dataSASL.length);
+
+            if (DebugInfo.debug)
+            {
+               System.out.println("Working on sasl::" + ByteUtil.bytesToHex(dataSASL, 2));
+            }
+
+            saslResult = mechanism.processSASL(dataSASL);
+
+            if (saslResult != null && saslResult.isSuccess())
+            {
+               serverSasl.done(Sasl.SaslOutcome.PN_SASL_OK);
+               serverSasl = null;
+               saslHandlers.clear();
+               saslHandlers = null;
+            }
+            else
+            {
+               serverSasl.done(Sasl.SaslOutcome.PN_SASL_AUTH);
+            }
+            serverSasl = null;
+         }
+         else
+         {
+            // no auth available, system error
+            serverSasl.done(Sasl.SaslOutcome.PN_SASL_SYS);
+         }
+      }
+   }
+
+   private Event popEvent()
+   {
+      synchronized (lock)
+      {
+         Event ev = collector.peek();
+         if (ev != null)
+         {
+            // pop will invalidate the event
+            // for that reason we make a new one
+            // Events are reused inside the collector, so we need to make a new one here
+            ev = ev.copy();
+            collector.pop();
+         }
+         return ev;
+      }
+   }
+
+   private void dispatchSASL()
+   {
+      for (EventHandler h: handlers)
+      {
+         h.onSASLInit(this, getConnection());
+      }
+   }
+
+
+   private void dispatch()
+   {
+      Event ev;
+      // We don't hold a lock on the entire event processing
+      // because we could have a distributed deadlock
+      // while processing events (for instance onTransport)
+      // while a client is also trying to write here
+      while ((ev = popEvent()) != null)
+      {
+         for (EventHandler h : handlers)
+         {
+            if (DebugInfo.debug)
+            {
+               System.out.println("Handling " + ev + " towards " + h);
+            }
+            try
+            {
+               Events.dispatch(ev, h);
+            }
+            catch (Exception e)
+            {
+               // TODO: logs
+               e.printStackTrace();
+               connection.setCondition(new ErrorCondition());
+            }
+         }
+      }
+
+      for (EventHandler h : handlers)
+      {
+         try
+         {
+            h.onTransport(transport);
+         }
+         catch (Exception e)
+         {
+            // TODO: logs
+            e.printStackTrace();
+            connection.setCondition(new ErrorCondition());
+         }
+      }
+
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/logger/HornetQAMQPProtocolMessageBundle.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/logger/HornetQAMQPProtocolMessageBundle.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/logger/HornetQAMQPProtocolMessageBundle.java
new file mode 100644
index 0000000..c4c22c8
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/logger/HornetQAMQPProtocolMessageBundle.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.proton.plug.logger;
+
+import org.proton.plug.exceptions.HornetQAMQPIllegalStateException;
+import org.proton.plug.exceptions.HornetQAMQPInternalErrorException;
+import org.proton.plug.exceptions.HornetQAMQPInvalidFieldException;
+import org.jboss.logging.annotations.Message;
+import org.jboss.logging.annotations.MessageBundle;
+import org.jboss.logging.Messages;
+
+/**
+ * Logger Code 11
+ * <p/>
+ * Each message id must be 6 digits long starting with 10, the 3rd digit should be 9. So the range
+ * is from 219000 to 119999.
+ * <p/>
+ * Once released, methods should not be deleted as they may be referenced by knowledge base
+ * articles. Unused methods should be marked as deprecated.
+ *
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ */
+@MessageBundle(projectCode = "HQ")
+public interface HornetQAMQPProtocolMessageBundle
+{
+   HornetQAMQPProtocolMessageBundle BUNDLE = Messages.getBundle(HornetQAMQPProtocolMessageBundle.class);
+
+
+   @Message(id = 219000, value = "target address not set", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPInvalidFieldException targetAddressNotSet();
+
+   @Message(id = 219001, value = "error creating temporary queue, {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPInternalErrorException errorCreatingTemporaryQueue(String message);
+
+   @Message(id = 219002, value = "target address does not exist", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPIllegalStateException addressDoesntExist();
+
+   @Message(id = 219003, value = "error finding temporary queue, {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPInternalErrorException errorFindingTemporaryQueue(String message);
+
+   @Message(id = 219004, value = "error creating HornetQ Session, {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPInternalErrorException errorCreatingHornetQSession(String message);
+
+   @Message(id = 219005, value = "error creating HornetQ Consumer, {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPInternalErrorException errorCreatingHornetQConsumer(String message);
+
+   @Message(id = 219006, value = "error starting HornetQ Consumer, {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPIllegalStateException errorStartingConsumer(String message);
+
+   @Message(id = 219007, value = "error acknowledging message {0}, {1}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPIllegalStateException errorAcknowledgingMessage(String messageID, String message);
+
+   @Message(id = 219008, value = "error cancelling message {0}, {1}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPIllegalStateException errorCancellingMessage(String messageID, String message);
+
+   @Message(id = 219009, value = "error closing consumer {0}, {1}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPIllegalStateException errorClosingConsumer(long consumerID, String message);
+
+   @Message(id = 219010, value = "source address does not exist", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPInvalidFieldException sourceAddressDoesntExist();
+
+   @Message(id = 219011, value = "source address not set", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPInvalidFieldException sourceAddressNotSet();
+
+   @Message(id = 219012, value = "error rolling back coordinator: {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPIllegalStateException errorRollingbackCoordinator(String message);
+
+   @Message(id = 219013, value = "error committing coordinator: {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQAMQPIllegalStateException errorCommittingCoordinator(String message);
+
+   @Message(id = 219015, value = "error decoding AMQP frame", format = Message.Format.MESSAGE_FORMAT)
+   String decodeError();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java
new file mode 100644
index 0000000..be05f37
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/AnonymousServerSASL.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.sasl;
+
+import org.proton.plug.SASLResult;
+import org.proton.plug.ServerSASL;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class AnonymousServerSASL implements ServerSASL
+{
+   public AnonymousServerSASL()
+   {
+   }
+
+   @Override
+   public String getName()
+   {
+      return "ANONYMOUS";
+   }
+
+   @Override
+   public SASLResult processSASL(byte[] bytes)
+   {
+      return new PlainSASLResult(true, null, null);
+   }
+}
+


[22/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/HornetQMessageBundle.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/HornetQMessageBundle.java b/hornetq-server/src/main/java/org/hornetq/core/server/HornetQMessageBundle.java
index 8b609e8..2034b61 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/HornetQMessageBundle.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/HornetQMessageBundle.java
@@ -356,4 +356,16 @@ public interface HornetQMessageBundle
 
    @Message(id = 119105, value = "Server will not accept create session request since scale down has not occurred", format = Message.Format.MESSAGE_FORMAT)
    HornetQSessionCreationException sessionNotFailedOver();
+
+   @Message(id = 119106, value = "Invalid slow consumer policy type {0}", format = Message.Format.MESSAGE_FORMAT)
+   IllegalArgumentException invalidSlowConsumerPolicyType(String val);
+
+   @Message(id = 119107, value = "consumer connections for address {0} closed by management", format = Message.Format.MESSAGE_FORMAT)
+   HornetQInternalErrorException consumerConnectionsClosedByManagement(String address);
+
+   @Message(id = 119108, value = "connections for user {0} closed by management", format = Message.Format.MESSAGE_FORMAT)
+   HornetQInternalErrorException connectionsForUserClosedByManagement(String userName);
+
+   @Message(id = 119109, value = "unsupported HA Policy Configuration {0}", format = Message.Format.MESSAGE_FORMAT)
+   HornetQIllegalStateException unsupportedHAPolicyConfiguration(Object o);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServer.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServer.java b/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServer.java
index 56bbc4a..7e9ee28 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServer.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServer.java
@@ -16,11 +16,7 @@ import java.util.List;
 import java.util.Set;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
-
-import org.hornetq.api.core.HornetQException;
-import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
-import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.config.BridgeConfiguration;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.DivertConfiguration;
@@ -28,14 +24,14 @@ import org.hornetq.core.management.impl.HornetQServerControlImpl;
 import org.hornetq.core.paging.PagingManager;
 import org.hornetq.core.persistence.StorageManager;
 import org.hornetq.core.postoffice.PostOffice;
-import org.hornetq.core.protocol.core.CoreRemotingConnection;
 import org.hornetq.core.remoting.server.RemotingService;
-import org.hornetq.core.replication.ReplicationEndpoint;
 import org.hornetq.core.replication.ReplicationManager;
 import org.hornetq.core.security.Role;
-import org.hornetq.core.server.cluster.ClusterConnection;
+import org.hornetq.core.security.SecurityStore;
 import org.hornetq.core.server.cluster.ClusterManager;
+import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.group.GroupingHandler;
+import org.hornetq.core.server.impl.Activation;
 import org.hornetq.core.server.impl.ConnectorsService;
 import org.hornetq.core.server.management.ManagementService;
 import org.hornetq.core.settings.HierarchicalRepository;
@@ -112,7 +108,10 @@ public interface HornetQServer extends HornetQComponent
                                boolean preAcknowledge,
                                boolean xa,
                                String defaultAddress,
-                               SessionCallback callback) throws Exception;
+                               SessionCallback callback,
+                               ServerSessionFactory sessionFactory) throws Exception;
+
+   SecurityStore getSecurityStore();
 
    void removeSession(String name) throws Exception;
 
@@ -153,17 +152,6 @@ public interface HornetQServer extends HornetQComponent
    boolean waitForActivation(long timeout, TimeUnit unit) throws InterruptedException;
 
    /**
-    * Wait for backup synchronization when using synchronization
-    * @param timeout
-    * @param unit
-    * @see CountDownLatch#await(long, TimeUnit)
-    * @return {@code true} if the server was already initialized or if it was initialized within the
-    *         timeout period, {@code false} otherwise.
-    * @throws InterruptedException
-    */
-   boolean waitForBackupSync(long timeout, TimeUnit unit) throws InterruptedException;
-
-   /**
     * Creates a shared queue. if non durable it will exist as long as there are consumers.
     *
     * Notice: the queue won't be deleted until the first consumer arrives.
@@ -211,8 +199,6 @@ public interface HornetQServer extends HornetQComponent
 
    GroupingHandler getGroupingHandler();
 
-   ReplicationEndpoint getReplicationEndpoint();
-
    ReplicationManager getReplicationManager();
 
    void deployDivert(DivertConfiguration config) throws Exception;
@@ -238,21 +224,6 @@ public interface HornetQServer extends HornetQComponent
 
    void stop(boolean failoverOnServerShutdown) throws Exception;
 
-   /**
-    * Starts replication.
-    * <p>
-    * This will spawn a new thread that will sync all persistent data with the new backup. This
-    * method may also trigger fail-back if the backup asks for it and the server configuration
-    * allows.
-    * @param rc
-    * @param pair
-    * @param clusterConnection
-    * @throws HornetQAlreadyReplicatingException if replication is already taking place
-    * @throws HornetQException
-    */
-   void startReplication(CoreRemotingConnection rc, ClusterConnection clusterConnection,
-                         Pair<TransportConfiguration, TransportConfiguration> pair, boolean failBackRequest) throws HornetQException;
-
    /*
    * add a ProtocolManagerFactory to be used. Note if @see Configuration#isResolveProtocols is tur then this factory will
    * replace any factories with the same protocol
@@ -269,4 +240,10 @@ public interface HornetQServer extends HornetQComponent
    void addScaledDownNode(SimpleString scaledDownNodeId);
 
    boolean hasScaledDown(SimpleString scaledDownNodeId);
+
+   Activation getActivation();
+
+   HAPolicy getHAPolicy();
+
+   void setHAPolicy(HAPolicy haPolicy);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServerLogger.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServerLogger.java b/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServerLogger.java
index cdeb3d1..3309946 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServerLogger.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/HornetQServerLogger.java
@@ -58,6 +58,7 @@ import org.hornetq.core.server.cluster.impl.BridgeImpl;
 import org.hornetq.core.server.cluster.impl.ClusterConnectionImpl;
 import org.hornetq.core.server.impl.HornetQServerImpl;
 import org.hornetq.core.server.impl.ServerSessionImpl;
+import org.hornetq.core.server.management.Notification;
 import org.hornetq.utils.FutureLatch;
 import org.jboss.logging.BasicLogger;
 import org.jboss.logging.annotations.Cause;
@@ -279,6 +280,18 @@ public interface HornetQServerLogger extends BasicLogger
    @Message(id = 221047, value = "Backup Server has scaled down to live server", format = Message.Format.MESSAGE_FORMAT)
    void backupServerScaledDown();
 
+   @LogMessage(level = Logger.Level.INFO)
+   @Message(id = 221048, value = "Consumer {0}:{1} attached to queue ''{2}'' from {3} identified as ''slow.'' Expected consumption rate: {4} msgs/second; actual consumption rate: {5} msgs/second.", format = Message.Format.MESSAGE_FORMAT)
+   void slowConsumerDetected(String sessionID, long consumerID, String queueName, String remoteAddress, float slowConsumerThreshold, float consumerRate);
+
+   @LogMessage(level = Logger.Level.INFO)
+   @Message(id = 221049, value = "Activating Replica for node: {0}", format = Message.Format.MESSAGE_FORMAT)
+   void activatingReplica(SimpleString nodeID);
+
+   @LogMessage(level = Logger.Level.INFO)
+   @Message(id = 221050, value = "Activating Shared Store Slave", format = Message.Format.MESSAGE_FORMAT)
+   void activatingSharedStoreSlave();
+
    @LogMessage(level = Logger.Level.WARN)
    @Message(id = 222000, value = "HornetQServer is being finalized and has not been stopped. Please remember to stop the server before letting it go out of scope",
             format = Message.Format.MESSAGE_FORMAT)
@@ -555,11 +568,6 @@ public interface HornetQServerLogger extends BasicLogger
    void errorProcessingIOCallback(Integer errorCode, String errorMessage);
 
    @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 222064, value = "Client with version {0} and address {1} is not compatible with server version {2}. Please ensure all clients and servers are upgraded to the same version for them to interoperate properly",
-            format = Message.Format.MESSAGE_FORMAT)
-   void incompatibleVersion(Integer version, String remoteAddress, String fullVersion);
-
-   @LogMessage(level = Logger.Level.WARN)
    @Message(id = 222065, value = "Client is not being consistent on the request versioning. It just sent a version id={0} while it informed {1} previously", format = Message.Format.MESSAGE_FORMAT)
    void incompatibleVersionAfterConnect(int version, int clientVersion);
 
@@ -1082,7 +1090,7 @@ public interface HornetQServerLogger extends BasicLogger
 
    @LogMessage(level = Logger.Level.WARN)
    @Message(id = 222187,
-          value = "Failed to activate replicated backup",
+          value = "Failed to activate replicata",
           format = Message.Format.MESSAGE_FORMAT)
    void activateReplicatedBackupFailed(@Cause Throwable e);
 
@@ -1092,6 +1100,12 @@ public interface HornetQServerLogger extends BasicLogger
           format = Message.Format.MESSAGE_FORMAT)
    void unableToFindTargetQueue(String targetNodeID);
 
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 222189,
+         value = "Failed to activate shared store slave",
+         format = Message.Format.MESSAGE_FORMAT)
+   void activateSharedStoreSlaveFailed(@Cause Throwable e);
+
    @LogMessage(level = Logger.Level.ERROR)
    @Message(id = 224000, value = "Failure in initialisation", format = Message.Format.MESSAGE_FORMAT)
    void initializationError(@Cause Throwable e);
@@ -1330,4 +1344,17 @@ public interface HornetQServerLogger extends BasicLogger
    @LogMessage(level = Logger.Level.ERROR)
    @Message(id = 224061, value = "Setting both <{0}> and <ha-policy> is invalid. Please use <ha-policy> exclusively as <{0}> is deprecated. Ignoring <{0}> value.", format = Message.Format.MESSAGE_FORMAT)
    void incompatibleWithHAPolicy(String parameter);
+
+   @LogMessage(level = Logger.Level.ERROR)
+   @Message(id = 224062, value = "Failed to send SLOW_CONSUMER notification: {0}", format = Message.Format.MESSAGE_FORMAT)
+   void failedToSendSlowConsumerNotification(Notification notification, @Cause Exception e);
+
+   @LogMessage(level = Logger.Level.ERROR)
+   @Message(id = 224063, value = "Failed to close consumer connections for address {0}", format = Message.Format.MESSAGE_FORMAT)
+   void failedToCloseConsumerConnectionsForAddress(String address, @Cause Exception e);
+
+   @LogMessage(level = Logger.Level.ERROR)
+   @Message(id = 224064, value = "Setting <{0}> is invalid with this HA Policy Configuration. Please use <ha-policy> exclusively or remove. Ignoring <{0}> value.", format = Message.Format.MESSAGE_FORMAT)
+   void incompatibleWithHAPolicyChosen(String parameter);
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/NodeManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/NodeManager.java b/hornetq-server/src/main/java/org/hornetq/core/server/NodeManager.java
index 2fe948b..049a3a6 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/NodeManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/NodeManager.java
@@ -39,7 +39,6 @@ public abstract class NodeManager implements HornetQComponent
    private final Object nodeIDGuard = new Object();
    private SimpleString nodeID;
    private UUID uuid;
-   private String nodeGroupName;
    private boolean isStarted = false;
 
    protected FileChannel channel;
@@ -122,16 +121,6 @@ public abstract class NodeManager implements HornetQComponent
       }
    }
 
-   public void setNodeGroupName(String nodeGroupName)
-   {
-      this.nodeGroupName = nodeGroupName;
-   }
-
-   public String getNodeGroupName()
-   {
-      return nodeGroupName;
-   }
-
    public abstract boolean isAwaitingFailback() throws Exception;
 
    public abstract boolean isBackupLive() throws Exception;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/Queue.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/Queue.java b/hornetq-server/src/main/java/org/hornetq/core/server/Queue.java
index 7526b44..afa03ff 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/Queue.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/Queue.java
@@ -99,28 +99,8 @@ public interface Queue extends Bindable
 
    void destroyPaging() throws Exception;
 
-   /**
-    * It will wait for up to 10 seconds for a flush on the executors and return the number of messages added.
-    * if the executor is busy for any reason (say an unbehaved consumer) we will just return the current value.
-    *
-    * @return
-    */
    long getMessageCount();
 
-   /**
-    * This method will return the messages added after waiting some time on the flush executors.
-    * If the executor couldn't be flushed within the timeout we will just return the current value without any warn
-    *
-    * @param timeout Time to wait for current executors to finish in milliseconds.
-    * @return
-    */
-   long getMessageCount(long timeout);
-
-   /**
-    * Return the current message count without waiting for scheduled executors to finish
-    */
-   long getInstantMessageCount();
-
    int getDeliveringCount();
 
    void referenceHandled();
@@ -137,24 +117,9 @@ public interface Queue extends Bindable
     */
    Map<String, List<MessageReference>> getDeliveringMessages();
 
-   /**
-    * It will wait for up to 10 seconds for a flush on the executors and return the number of messages added.
-    * if the executor is busy for any reason (say an unbehaved consumer) we will just return the current value.
-    *
-    * @return
-    */
    long getMessagesAdded();
 
-   /**
-    * This method will return the messages added after waiting some time on the flush executors.
-    * If the executor couldn't be flushed within the timeout we will just return the current value without any warn
-    *
-    * @param timeout Time to wait for current executors to finish in milliseconds.
-    * @return
-    */
-   long getMessagesAdded(long timeout);
-
-   long getInstantMessagesAdded();
+   long getMessagesAcknowledged();
 
    MessageReference removeReferenceWithID(long id) throws Exception;
 
@@ -255,7 +220,13 @@ public interface Queue extends Bindable
 
    void resetMessagesAdded();
 
+   void resetMessagesAcknowledged();
+
    void incrementMesssagesAdded();
 
    List<MessageReference> cancelScheduledMessages();
+
+   void postAcknowledge(MessageReference ref);
+
+   float getRate();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/ServerConsumer.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/ServerConsumer.java b/hornetq-server/src/main/java/org/hornetq/core/server/ServerConsumer.java
index 279cff7..6d94d01 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/ServerConsumer.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/ServerConsumer.java
@@ -25,25 +25,45 @@ import org.hornetq.core.transaction.Transaction;
  */
 public interface ServerConsumer extends Consumer
 {
+   /**
+    * @see #getProtocolContext()
+    * @param protocolContext
+    */
+   void setProtocolContext(Object protocolContext);
+
+   /**
+    * An object set by the Protocol implementation.
+    * it could be anything pre-determined by the implementation
+    */
+   Object getProtocolContext();
+
    long getID();
 
    Object getConnectionID();
 
    void close(boolean failed) throws Exception;
 
+   /**
+    * This method is just to remove itself from Queues.
+    * If for any reason during a close an exception occurred, the exception treatment
+    * will call removeItself what should take the consumer out of any queues.
+    * @throws Exception
+    */
+   void removeItself() throws Exception;
+
    List<MessageReference> cancelRefs(boolean failed, boolean lastConsumedAsDelivered, Transaction tx) throws Exception;
 
    void setStarted(boolean started);
 
-   void receiveCredits(int credits) throws Exception;
+   void receiveCredits(int credits);
 
    Queue getQueue();
 
    MessageReference removeReferenceByID(long messageID) throws Exception;
 
-   void acknowledge(boolean autoCommitAcks, Transaction tx, long messageID) throws Exception;
+   void acknowledge(Transaction tx, long messageID) throws Exception;
 
-   void individualAcknowledge(boolean autoCommitAcks, Transaction tx, long messageID) throws Exception;
+   void individualAcknowledge(Transaction tx, long messageID) throws Exception;
 
    void individualCancel(final long messageID, boolean failed) throws Exception;
 
@@ -56,6 +76,8 @@ public interface ServerConsumer extends Consumer
    long getCreationTime();
 
    String getSessionID();
+
+   void promptDelivery();
 }
 
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/ServerMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/ServerMessage.java b/hornetq-server/src/main/java/org/hornetq/core/server/ServerMessage.java
index cdbc028..6d84a3d 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/ServerMessage.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/ServerMessage.java
@@ -27,7 +27,7 @@ import org.hornetq.core.paging.PagingStore;
  */
 public interface ServerMessage extends MessageInternal, EncodingSupport
 {
-   void setMessageID(long id);
+   ServerMessage setMessageID(long id);
 
    MessageReference createReference(Queue queue);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/ServerSession.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/ServerSession.java b/hornetq-server/src/main/java/org/hornetq/core/server/ServerSession.java
index 2fc4cb3..e8d523e 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/ServerSession.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/ServerSession.java
@@ -43,7 +43,7 @@ public interface ServerSession
 
    RemotingConnection getRemotingConnection();
 
-   void removeConsumer(long consumerID) throws Exception;
+   boolean removeConsumer(long consumerID) throws Exception;
 
    void acknowledge(long consumerID, long messageID) throws Exception;
 
@@ -95,7 +95,7 @@ public interface ServerSession
 
    void deleteQueue(SimpleString name) throws Exception;
 
-   void createConsumer(long consumerID, SimpleString queueName, SimpleString filterString, boolean browseOnly) throws Exception;
+   ServerConsumer createConsumer(long consumerID, SimpleString queueName, SimpleString filterString, boolean browseOnly) throws Exception;
 
    QueueQueryResult executeQueueQuery(SimpleString name) throws Exception;
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/ServerSessionFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/ServerSessionFactory.java b/hornetq-server/src/main/java/org/hornetq/core/server/ServerSessionFactory.java
new file mode 100644
index 0000000..8a752e8
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/ServerSessionFactory.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.persistence.OperationContext;
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.security.SecurityStore;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.ServerSessionImpl;
+import org.hornetq.core.server.management.ManagementService;
+import org.hornetq.core.transaction.ResourceManager;
+import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.protocol.SessionCallback;
+
+public interface ServerSessionFactory
+{
+
+   ServerSessionImpl createCoreSession(String name, String username, String password,
+         int minLargeMessageSize, boolean autoCommitSends,
+         boolean autoCommitAcks, boolean preAcknowledge,
+         boolean persistDeliveryCountBeforeDelivery, boolean xa,
+         RemotingConnection connection, StorageManager storageManager,
+         PostOffice postOffice, ResourceManager resourceManager,
+         SecurityStore securityStore, ManagementService managementService,
+         HornetQServerImpl hornetQServerImpl, SimpleString managementAddress,
+         SimpleString simpleString, SessionCallback callback,
+         OperationContext context) throws Exception;
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/BackupManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/BackupManager.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/BackupManager.java
index e313fab..37cdea5 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/BackupManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/BackupManager.java
@@ -29,7 +29,6 @@ import org.hornetq.core.client.impl.ServerLocatorInternal;
 import org.hornetq.core.client.impl.Topology;
 import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
-import org.hornetq.core.protocol.ServerPacketDecoder;
 import org.hornetq.core.server.HornetQComponent;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
@@ -80,7 +79,7 @@ public class BackupManager implements HornetQComponent
       for (BackupConnector conn : backupConnectors)
       {
          conn.start();
-         if (configuration.getHAPolicy().isBackup() && configuration.getHAPolicy().isSharedStore())
+         if (server.getHAPolicy().isBackup() && server.getHAPolicy().isSharedStore())
          {
             conn.informTopology();
             conn.announceBackup();
@@ -219,7 +218,7 @@ public class BackupManager implements HornetQComponent
             backupServerLocator.setIdentity("backupLocatorFor='" + server + "'");
             backupServerLocator.setReconnectAttempts(-1);
             backupServerLocator.setInitialConnectAttempts(-1);
-            backupServerLocator.setPacketDecoder(ServerPacketDecoder.INSTANCE);
+            backupServerLocator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
          }
       }
 
@@ -260,8 +259,8 @@ public class BackupManager implements HornetQComponent
                      clusterControl.authorize();
                      clusterControl.sendNodeAnnounce(System.currentTimeMillis(),
                                                       nodeManager.getNodeId().toString(),
-                                                      configuration.getHAPolicy().getBackupGroupName(),
-                                                      configuration.getHAPolicy().getScaleDownClustername(),
+                                                      server.getHAPolicy().getBackupGroupName(),
+                                                      server.getHAPolicy().getScaleDownClustername(),
                                                       true,
                                                       connector,
                                                       null);
@@ -372,7 +371,7 @@ public class BackupManager implements HornetQComponent
             }
             ServerLocatorImpl locator = new ServerLocatorImpl(topology, true, tcConfigs);
             locator.setClusterConnection(true);
-            locator.setPacketDecoder(ServerPacketDecoder.INSTANCE);
+            locator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
             return locator;
          }
          return null;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterControl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterControl.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterControl.java
index d3907f9..0ace46c 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterControl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterControl.java
@@ -92,10 +92,10 @@ public class ClusterControl implements AutoCloseable
     *                           server.
     * @throws org.hornetq.api.core.HornetQException
     */
-   public void announceReplicatingBackupToLive(final boolean attemptingFailBack) throws HornetQException
+   public void announceReplicatingBackupToLive(final boolean attemptingFailBack, String replicationClusterName) throws HornetQException
    {
 
-      ClusterConnectionConfiguration config = ConfigurationUtils.getReplicationClusterConfiguration(server.getConfiguration());
+      ClusterConnectionConfiguration config = ConfigurationUtils.getReplicationClusterConfiguration(server.getConfiguration(), replicationClusterName);
       if (config == null)
       {
          HornetQServerLogger.LOGGER.announceBackupNoClusterConnections();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterController.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterController.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterController.java
index 6d7abca..8c028fe 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterController.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterController.java
@@ -21,7 +21,6 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
 import org.hornetq.api.core.DiscoveryGroupConfiguration;
-import org.hornetq.api.core.HornetQAlreadyReplicatingException;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Interceptor;
 import org.hornetq.api.core.Pair;
@@ -34,16 +33,11 @@ import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorImpl;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
 import org.hornetq.core.client.impl.Topology;
-import org.hornetq.core.protocol.ServerPacketDecoder;
 import org.hornetq.core.protocol.core.Channel;
 import org.hornetq.core.protocol.core.ChannelHandler;
 import org.hornetq.core.protocol.core.CoreRemotingConnection;
 import org.hornetq.core.protocol.core.Packet;
 import org.hornetq.core.protocol.core.impl.PacketImpl;
-import org.hornetq.core.protocol.core.impl.wireformat.BackupRegistrationMessage;
-import org.hornetq.core.protocol.core.impl.wireformat.BackupReplicationStartFailedMessage;
-import org.hornetq.core.protocol.core.impl.wireformat.BackupRequestMessage;
-import org.hornetq.core.protocol.core.impl.wireformat.BackupResponseMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.ClusterConnectMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.ClusterConnectReplyMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.NodeAnnounceMessage;
@@ -53,10 +47,10 @@ import org.hornetq.core.protocol.core.impl.wireformat.ScaleDownAnnounceMessage;
 import org.hornetq.core.server.HornetQComponent;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.cluster.qourum.QuorumManager;
 import org.hornetq.core.server.cluster.qourum.QuorumVoteHandler;
 import org.hornetq.core.server.cluster.qourum.Vote;
+import org.hornetq.core.server.impl.Activation;
 import org.hornetq.spi.core.remoting.Acceptor;
 
 /**
@@ -83,6 +77,7 @@ public class ClusterController implements HornetQComponent
    private CountDownLatch replicationClusterConnectedLatch;
 
    private boolean started;
+   private SimpleString replicatedClusterName;
 
    public ClusterController(HornetQServer server, ScheduledExecutorService scheduledExecutor)
    {
@@ -99,9 +94,9 @@ public class ClusterController implements HornetQComponent
       //set the default locator that will be used to connecting to the default cluster.
       defaultLocator = locators.get(defaultClusterConnectionName);
       //create a locator for replication, either the default or the specified if not set
-      if (server.getConfiguration().getHAPolicy().getReplicationClustername() != null && !server.getConfiguration().getHAPolicy().getReplicationClustername().equals(defaultClusterConnectionName.toString()))
+      if (replicatedClusterName != null && !replicatedClusterName.equals(defaultClusterConnectionName))
       {
-         replicationLocator = locators.get(server.getConfiguration().getHAPolicy().getReplicationClustername());
+         replicationLocator = locators.get(replicatedClusterName);
          if (replicationLocator == null)
          {
             HornetQServerLogger.LOGGER.noClusterConnectionForReplicationCluster();
@@ -172,7 +167,7 @@ public class ClusterController implements HornetQComponent
       serverLocator.setReconnectAttempts(-1);
       serverLocator.setInitialConnectAttempts(-1);
       //this is used for replication so need to use the server packet decoder
-      serverLocator.setPacketDecoder(ServerPacketDecoder.INSTANCE);
+      serverLocator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
       locators.put(name, serverLocator);
    }
 
@@ -189,7 +184,7 @@ public class ClusterController implements HornetQComponent
       serverLocator.setReconnectAttempts(-1);
       serverLocator.setInitialConnectAttempts(-1);
       //this is used for replication so need to use the server packet decoder
-      serverLocator.setPacketDecoder(ServerPacketDecoder.INSTANCE);
+      serverLocator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
       locators.put(name, serverLocator);
    }
 
@@ -253,7 +248,7 @@ public class ClusterController implements HornetQComponent
     */
    public ClusterControl connectToNodeInCluster(ClientSessionFactoryInternal sf)
    {
-      ((ServerLocatorInternal)sf.getServerLocator()).setPacketDecoder(ServerPacketDecoder.INSTANCE);
+      sf.getServerLocator().setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
       return new ClusterControl(sf, server);
    }
 
@@ -280,14 +275,14 @@ public class ClusterController implements HornetQComponent
 
    /**
     * used to set a channel handler on the connection that can be used by the cluster control
-    *
-    * @param channel the channel to set the handler
+    *  @param channel the channel to set the handler
     * @param acceptorUsed the acceptor used for connection
     * @param remotingConnection the connection itself
+    * @param activation
     */
-   public void addClusterChannelHandler(Channel channel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection)
+   public void addClusterChannelHandler(Channel channel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, Activation activation)
    {
-      channel.setHandler(new ClusterControllerChannelHandler(channel, acceptorUsed, remotingConnection));
+      channel.setHandler(new ClusterControllerChannelHandler(channel, acceptorUsed, remotingConnection, activation.getActivationChannelHandler(channel, acceptorUsed)));
    }
 
    public int getDefaultClusterSize()
@@ -310,6 +305,11 @@ public class ClusterController implements HornetQComponent
       return server.getIdentity();
    }
 
+   public void setReplicatedClusterName(String replicatedClusterName)
+   {
+      this.replicatedClusterName = new SimpleString(replicatedClusterName);
+   }
+
    /**
     * a handler for handling packets sent between the cluster.
     */
@@ -318,13 +318,15 @@ public class ClusterController implements HornetQComponent
       private final Channel clusterChannel;
       private final Acceptor acceptorUsed;
       private final CoreRemotingConnection remotingConnection;
+      private final ChannelHandler channelHandler;
       boolean authorized = false;
 
-      public ClusterControllerChannelHandler(Channel clusterChannel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection)
+      public ClusterControllerChannelHandler(Channel clusterChannel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, ChannelHandler channelHandler)
       {
          this.clusterChannel = clusterChannel;
          this.acceptorUsed = acceptorUsed;
          this.remotingConnection = remotingConnection;
+         this.channelHandler = channelHandler;
       }
 
       @Override
@@ -336,6 +338,12 @@ public class ClusterController implements HornetQComponent
             {
                ClusterConnection clusterConnection = acceptorUsed.getClusterConnection();
 
+               //if this acceptor isnt associated with a cluster connection use the default
+               if (clusterConnection == null)
+               {
+                  clusterConnection = server.getClusterManager().getDefaultConnection(null);
+               }
+
                ClusterConnectMessage msg = (ClusterConnectMessage) packet;
 
                if (server.getConfiguration().isSecurityEnabled() && !clusterConnection.verify(msg.getClusterUser(), msg.getClusterPassword()))
@@ -387,24 +395,6 @@ public class ClusterController implements HornetQComponent
                   HornetQServerLogger.LOGGER.debug("there is no acceptor used configured at the CoreProtocolManager " + this);
                }
             }
-            else if (packet.getType() == PacketImpl.BACKUP_REGISTRATION)
-            {
-               BackupRegistrationMessage msg = (BackupRegistrationMessage)packet;
-               ClusterConnection clusterConnection = acceptorUsed.getClusterConnection();
-               try
-               {
-                  server.startReplication(remotingConnection, clusterConnection, getPair(msg.getConnector(), true),
-                        msg.isFailBackRequest());
-               }
-               catch (HornetQAlreadyReplicatingException are)
-               {
-                  clusterChannel.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.ALREADY_REPLICATING));
-               }
-               catch (HornetQException e)
-               {
-                  clusterChannel.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.EXCEPTION));
-               }
-            }
             else if (packet.getType() == PacketImpl.QUORUM_VOTE)
             {
                QuorumVoteMessage quorumVoteMessage = (QuorumVoteMessage) packet;
@@ -413,31 +403,6 @@ public class ClusterController implements HornetQComponent
                Vote vote = quorumManager.vote(quorumVoteMessage.getHandler(), quorumVoteMessage.getVote());
                clusterChannel.send(new QuorumVoteReplyMessage(quorumVoteMessage.getHandler(), vote));
             }
-            else if (packet.getType() == PacketImpl.BACKUP_REQUEST)
-            {
-               BackupRequestMessage backupRequestMessage = (BackupRequestMessage) packet;
-               boolean started = false;
-               try
-               {
-                  if (backupRequestMessage.getBackupType() == HAPolicy.POLICY_TYPE.COLOCATED_REPLICATED)
-                  {
-                     started = server.getClusterManager().getHAManager().activateReplicatedBackup(backupRequestMessage.getBackupSize(), backupRequestMessage.getNodeID());
-                  }
-                  else
-                  {
-                     started = server.getClusterManager().getHAManager().activateSharedStoreBackup(backupRequestMessage.getBackupSize(),
-                           backupRequestMessage.getJournalDirectory(),
-                           backupRequestMessage.getBindingsDirectory(),
-                           backupRequestMessage.getLargeMessagesDirectory(),
-                           backupRequestMessage.getPagingDirectory());
-                  }
-               }
-               catch (Exception e)
-               {
-                  //todo log a warning and send false
-               }
-               clusterChannel.send(new BackupResponseMessage(started));
-            }
             else if (packet.getType() == PacketImpl.SCALEDOWN_ANNOUNCEMENT)
             {
                ScaleDownAnnounceMessage message = (ScaleDownAnnounceMessage) packet;
@@ -447,17 +412,13 @@ public class ClusterController implements HornetQComponent
                   server.addScaledDownNode(message.getScaledDownNodeId());
                }
             }
+            else if (channelHandler != null)
+            {
+               channelHandler.handlePacket(packet);
+            }
          }
       }
-      private Pair<TransportConfiguration, TransportConfiguration> getPair(TransportConfiguration conn,
-                                                                           boolean isBackup)
-      {
-         if (isBackup)
-         {
-            return new Pair<>(null, conn);
-         }
-         return new Pair<>(conn, null);
-      }
+
    }
 
    /**

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterManager.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterManager.java
index bd9ba38..62e8f22 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ClusterManager.java
@@ -55,8 +55,8 @@ import org.hornetq.core.server.cluster.impl.BridgeImpl;
 import org.hornetq.core.server.cluster.impl.BroadcastGroupImpl;
 import org.hornetq.core.server.cluster.impl.ClusterConnectionImpl;
 import org.hornetq.core.server.cluster.qourum.QuorumManager;
+import org.hornetq.core.server.impl.Activation;
 import org.hornetq.core.server.management.ManagementService;
-import org.hornetq.core.settings.impl.AddressSettings;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.spi.core.remoting.Acceptor;
 import org.hornetq.utils.ConcurrentHashSet;
@@ -66,8 +66,8 @@ import org.hornetq.utils.FutureLatch;
 /**
  * A ClusterManager manages {@link ClusterConnection}s, {@link BroadcastGroup}s and {@link Bridge}s.
  * <p/>
- * Note that {@link ClusterConnectionBridge}s extend Bridges but are controlled over through
- * {@link ClusterConnectionImpl}. As a node is discovered a new {@link ClusterConnectionBridge} is
+ * Note that {@link org.hornetq.core.server.cluster.impl.ClusterConnectionBridge}s extend Bridges but are controlled over through
+ * {@link ClusterConnectionImpl}. As a node is discovered a new {@link org.hornetq.core.server.cluster.impl.ClusterConnectionBridge} is
  * deployed.
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
@@ -112,9 +112,9 @@ public final class ClusterManager implements HornetQComponent
       return haManager;
    }
 
-   public void addClusterChannelHandler(Channel channel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection)
+   public void addClusterChannelHandler(Channel channel, Acceptor acceptorUsed, CoreRemotingConnection remotingConnection, Activation activation)
    {
-      clusterController.addClusterChannelHandler(channel, acceptorUsed, remotingConnection);
+      clusterController.addClusterChannelHandler(channel, acceptorUsed, remotingConnection, activation);
    }
 
    enum State
@@ -172,7 +172,7 @@ public final class ClusterManager implements HornetQComponent
 
       clusterController = new ClusterController(server, scheduledExecutor);
 
-      haManager = new HAManager(server.getConfiguration().getHAPolicy(), server.getSecurityManager(), server, server.getConfiguration().getBackupServerConfigurations());
+      haManager = server.getActivation().getHAManager();
    }
 
    public String describe()
@@ -235,12 +235,12 @@ public final class ClusterManager implements HornetQComponent
 
    public String getBackupGroupName()
    {
-      return configuration.getHAPolicy().getBackupGroupName();
+      return server.getHAPolicy().getBackupGroupName();
    }
 
    public String getScaleDownGroupName()
    {
-      return haManager.getHAPolicy().getScaleDownGroupName();
+      return server.getHAPolicy().getScaleDownGroupName();
    }
 
    public synchronized void deploy() throws Exception
@@ -514,30 +514,6 @@ public final class ClusterManager implements HornetQComponent
 
       }
 
-      if (config.getForwardingAddress() != null)
-      {
-         AddressSettings addressConfig = configuration.getAddressesSettings().get(config.getForwardingAddress());
-
-         // The address config could be null on certain test cases or some Embedded environment
-         if (addressConfig == null)
-         {
-            // We will certainly have this warning on testcases which is ok
-            HornetQServerLogger.LOGGER.bridgeCantFindAddressConfig(config.getName(), config.getForwardingAddress());
-         }
-         else
-         {
-            final int windowSize = config.getConfirmationWindowSize();
-            final long maxBytes = addressConfig.getMaxSizeBytes();
-
-            if (maxBytes != -1 && maxBytes < windowSize)
-            {
-               HornetQServerLogger.LOGGER.bridgeConfirmationWindowTooSmall(config.getName(),
-                                                                           config.getForwardingAddress(), windowSize,
-                                                                           maxBytes);
-            }
-         }
-      }
-
       serverLocator.setIdentity("Bridge " + config.getName());
       serverLocator.setConfirmationWindowSize(config.getConfirmationWindowSize());
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/HornetQServerSideProtocolManagerFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/HornetQServerSideProtocolManagerFactory.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/HornetQServerSideProtocolManagerFactory.java
new file mode 100644
index 0000000..b45cf94
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/HornetQServerSideProtocolManagerFactory.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.server.cluster;
+
+import org.hornetq.core.protocol.ServerPacketDecoder;
+import org.hornetq.core.protocol.core.impl.HornetQClientProtocolManager;
+import org.hornetq.core.protocol.core.impl.PacketDecoder;
+import org.hornetq.spi.core.remoting.ClientProtocolManager;
+import org.hornetq.spi.core.remoting.ClientProtocolManagerFactory;
+
+/**
+ * A protocol manager that will replace the packet manager for inter-server communications
+ * @author Clebert Suconic
+ */
+public class HornetQServerSideProtocolManagerFactory implements ClientProtocolManagerFactory
+{
+   private static final HornetQServerSideProtocolManagerFactory INSTANCE = new  HornetQServerSideProtocolManagerFactory();
+
+   public static HornetQServerSideProtocolManagerFactory getInstance()
+   {
+      return INSTANCE;
+   }
+
+   private HornetQServerSideProtocolManagerFactory()
+   {
+   }
+
+   private static final long serialVersionUID = 1;
+
+   @Override
+   public ClientProtocolManager newProtocolManager()
+   {
+      return new HornetQReplicationProtocolManager();
+   }
+
+   class HornetQReplicationProtocolManager extends HornetQClientProtocolManager
+   {
+      @Override
+      protected PacketDecoder getPacketDecoder()
+      {
+         return ServerPacketDecoder.INSTANCE;
+      }
+   }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/BackupPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/BackupPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/BackupPolicy.java
new file mode 100644
index 0000000..f6749df
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/BackupPolicy.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.server.impl.Activation;
+
+public abstract class BackupPolicy implements HAPolicy<Activation>
+{
+   protected ScaleDownPolicy scaleDownPolicy;
+   protected boolean restartBackup = HornetQDefaultConfiguration.isDefaultRestartBackup();
+
+   public ScaleDownPolicy getScaleDownPolicy()
+   {
+      return scaleDownPolicy;
+   }
+
+   public void setScaleDownPolicy(ScaleDownPolicy scaleDownPolicy)
+   {
+      this.scaleDownPolicy = scaleDownPolicy;
+   }
+
+
+   @Override
+   public boolean isBackup()
+   {
+      return true;
+   }
+
+   @Override
+   public String getScaleDownClustername()
+   {
+      return null;
+   }
+
+   @Override
+   public String getScaleDownGroupName()
+   {
+      return getScaleDownPolicy() != null ? getScaleDownPolicy().getGroupName() : null;
+   }
+
+   public boolean isRestartBackup()
+   {
+      return restartBackup;
+   }
+
+   public void setRestartBackup(boolean restartBackup)
+   {
+      this.restartBackup = restartBackup;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedHAManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedHAManager.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedHAManager.java
new file mode 100644
index 0000000..85e97a0
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedHAManager.java
@@ -0,0 +1,313 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.core.Pair;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.TopologyMember;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.server.ActivationParams;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.cluster.ClusterControl;
+import org.hornetq.core.server.cluster.ClusterController;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class ColocatedHAManager implements HAManager
+{
+
+   private final ColocatedPolicy haPolicy;
+
+   private final HornetQServer server;
+
+   private Map<String, HornetQServer> backupServers = new HashMap<>();
+
+   private boolean started;
+
+   public ColocatedHAManager(ColocatedPolicy haPolicy, HornetQServer hornetQServer)
+   {
+      this.haPolicy = haPolicy;
+      server = hornetQServer;
+   }
+
+   /**
+    * starts the HA manager.
+    */
+   public void start()
+   {
+      if (started)
+         return;
+
+      server.getActivation().haStarted();
+
+      started = true;
+   }
+
+   /**
+    * stop any backups
+    */
+   public void stop()
+   {
+      for (HornetQServer hornetQServer : backupServers.values())
+      {
+         try
+         {
+            hornetQServer.stop();
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+            //todo
+         }
+      }
+      backupServers.clear();
+      started = false;
+   }
+
+   @Override
+   public boolean isStarted()
+   {
+      return started;
+   }
+
+   public synchronized boolean activateBackup(int backupSize, String journalDirectory, String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory, SimpleString nodeID) throws Exception
+   {
+      if (backupServers.size() >= haPolicy.getMaxBackups() || backupSize != backupServers.size())
+      {
+         return false;
+      }
+      if (haPolicy.getBackupPolicy().isSharedStore())
+      {
+         return activateSharedStoreBackup(journalDirectory, bindingsDirectory, largeMessagesDirectory, pagingDirectory);
+      }
+      else
+      {
+         return activateReplicatedBackup(nodeID);
+      }
+   }
+
+
+   /**
+    * return the current backup servers
+    *
+    * @return the backups
+    */
+   public Map<String, HornetQServer> getBackupServers()
+   {
+      return backupServers;
+   }
+
+   /**
+    * send a request to a live server to start a backup for us
+    *
+    * @param connectorPair the connector for the node to request a backup from
+    * @param backupSize the current size of the requested nodes backups
+    * @param replicated
+    * @return true if the request wa successful.
+    * @throws Exception
+    */
+   public boolean requestBackup(Pair<TransportConfiguration, TransportConfiguration> connectorPair, int backupSize, boolean replicated) throws Exception
+   {
+      ClusterController clusterController = server.getClusterManager().getClusterController();
+      try
+            (
+                  ClusterControl clusterControl = clusterController.connectToNode(connectorPair.getA());
+            )
+      {
+         clusterControl.authorize();
+         if (replicated)
+         {
+            return clusterControl.requestReplicatedBackup(backupSize, server.getNodeID());
+         }
+         else
+         {
+            return clusterControl.requestSharedStoreBackup(backupSize,
+                  server.getConfiguration().getJournalDirectory(),
+                  server.getConfiguration().getBindingsDirectory(),
+                  server.getConfiguration().getLargeMessagesDirectory(),
+                  server.getConfiguration().getPagingDirectory());
+
+         }
+      }
+   }
+
+   private synchronized boolean activateSharedStoreBackup(String journalDirectory, String bindingsDirectory, String largeMessagesDirectory, String pagingDirectory) throws Exception
+   {
+      Configuration configuration = server.getConfiguration().copy();
+      HornetQServer backup = server.createBackupServer(configuration);
+      try
+      {
+         int portOffset = haPolicy.getBackupPortOffset() * (backupServers.size() + 1);
+         String name = "colocated_backup_" + backupServers.size() + 1;
+         //make sure we don't restart as we are colocated
+         haPolicy.getBackupPolicy().setRestartBackup(false);
+         //set the backup policy
+         backup.setHAPolicy(haPolicy.getBackupPolicy());
+         updateSharedStoreConfiguration(configuration, name, portOffset, haPolicy.getExcludedConnectors(), journalDirectory, bindingsDirectory, largeMessagesDirectory, pagingDirectory, haPolicy.getBackupPolicy().getScaleDownPolicy() == null);
+
+         backupServers.put(configuration.getName(), backup);
+         backup.start();
+      }
+      catch (Exception e)
+      {
+         backup.stop();
+         HornetQServerLogger.LOGGER.activateSharedStoreSlaveFailed(e);
+         return false;
+      }
+      HornetQServerLogger.LOGGER.activatingSharedStoreSlave();
+      return true;
+   }
+
+   /**
+    * activate a backup server replicating from a specified node.
+    *
+    * decline and the requesting server can cast a re vote
+    * @param nodeID the id of the node to replicate from
+    * @return true if the server was created and started
+    * @throws Exception
+    */
+   private synchronized boolean activateReplicatedBackup(SimpleString nodeID) throws Exception
+   {
+      Configuration configuration = server.getConfiguration().copy();
+      HornetQServer backup = server.createBackupServer(configuration);
+      try
+      {
+         TopologyMember member = server.getClusterManager().getDefaultConnection(null).getTopology().getMember(nodeID.toString());
+         int portOffset = haPolicy.getBackupPortOffset() * (backupServers.size() + 1);
+         String name = "colocated_backup_" + backupServers.size() + 1;
+         //make sure we don't restart as we are colocated
+         haPolicy.getBackupPolicy().setRestartBackup(false);
+         //set the backup policy
+         backup.setHAPolicy(haPolicy.getBackupPolicy());
+         updateReplicatedConfiguration(configuration, name, portOffset, haPolicy.getExcludedConnectors(), haPolicy.getBackupPolicy().getScaleDownPolicy() == null);
+         backup.addActivationParam(ActivationParams.REPLICATION_ENDPOINT, member);
+         backupServers.put(configuration.getName(), backup);
+         backup.start();
+      }
+      catch (Exception e)
+      {
+         backup.stop();
+         HornetQServerLogger.LOGGER.activateReplicatedBackupFailed(e);
+         return false;
+      }
+      HornetQServerLogger.LOGGER.activatingReplica(nodeID);
+      return true;
+   }
+
+   /**
+    * update the backups configuration
+    * @param backupConfiguration the configuration to update
+    * @param name the new name of the backup
+    * @param portOffset the offset for the acceptors and any connectors that need changing
+    * @param remoteConnectors the connectors that don't need off setting, typically remote
+    * @param journalDirectory
+    * @param bindingsDirectory
+    * @param largeMessagesDirectory
+    * @param pagingDirectory
+    * @param fullServer
+    */
+   private static void updateSharedStoreConfiguration(Configuration backupConfiguration,
+                                                      String name,
+                                                      int portOffset,
+                                                      List<String> remoteConnectors,
+                                                      String journalDirectory,
+                                                      String bindingsDirectory,
+                                                      String largeMessagesDirectory,
+                                                      String pagingDirectory,
+                                                      boolean fullServer)
+   {
+      backupConfiguration.setName(name);
+      backupConfiguration.setJournalDirectory(journalDirectory);
+      backupConfiguration.setBindingsDirectory(bindingsDirectory);
+      backupConfiguration.setLargeMessagesDirectory(largeMessagesDirectory);
+      backupConfiguration.setPagingDirectory(pagingDirectory);
+      updateAcceptorsAndConnectors(backupConfiguration, portOffset, remoteConnectors, fullServer);
+   }
+
+   /**
+    * update the backups configuration
+    *
+    * @param backupConfiguration the configuration to update
+    * @param name the new name of the backup
+    * @param portOffset the offset for the acceptors and any connectors that need changing
+    * @param remoteConnectors the connectors that don't need off setting, typically remote
+    */
+   private static void updateReplicatedConfiguration(Configuration backupConfiguration,
+                                                     String name,
+                                                     int portOffset,
+                                                     List<String> remoteConnectors,
+                                                     boolean fullServer)
+   {
+      backupConfiguration.setName(name);
+      backupConfiguration.setJournalDirectory(backupConfiguration.getJournalDirectory() + name);
+      backupConfiguration.setPagingDirectory(backupConfiguration.getPagingDirectory() + name);
+      backupConfiguration.setLargeMessagesDirectory(backupConfiguration.getLargeMessagesDirectory() + name);
+      backupConfiguration.setBindingsDirectory(backupConfiguration.getBindingsDirectory() + name);
+      updateAcceptorsAndConnectors(backupConfiguration, portOffset, remoteConnectors, fullServer);
+   }
+
+   private static void updateAcceptorsAndConnectors(Configuration backupConfiguration,
+                                                    int portOffset,
+                                                    List<String> remoteConnectors,
+                                                    boolean fullServer)
+   {
+      //we only do this if we are a full server, if scale down then our acceptors wont be needed and our connectors will
+      // be the same as the parent server
+      if (fullServer)
+      {
+         Set<TransportConfiguration> acceptors = backupConfiguration.getAcceptorConfigurations();
+         for (TransportConfiguration acceptor : acceptors)
+         {
+            updatebackupParams(backupConfiguration.getName(), portOffset, acceptor.getParams());
+         }
+         Map<String, TransportConfiguration> connectorConfigurations = backupConfiguration.getConnectorConfigurations();
+         for (Map.Entry<String, TransportConfiguration> entry : connectorConfigurations.entrySet())
+         {
+            //check to make sure we aren't a remote connector as this shouldn't be changed
+            if (!remoteConnectors.contains(entry.getValue().getName()))
+            {
+               updatebackupParams(backupConfiguration.getName(), portOffset, entry.getValue().getParams());
+            }
+         }
+      }
+      else
+      {
+         //if we are scaling down then we wont need any acceptors but clear anyway for belts and braces
+         backupConfiguration.getAcceptorConfigurations().clear();
+      }
+   }
+
+   private static void updatebackupParams(String name, int portOffset, Map<String, Object> params)
+   {
+      if (params != null)
+      {
+         Object port = params.get("port");
+         if (port != null)
+         {
+            Integer integer = Integer.valueOf(port.toString());
+            integer += portOffset;
+            params.put("port", integer.toString());
+         }
+         Object serverId = params.get("server-id");
+         if (serverId != null)
+         {
+            params.put("server-id", serverId.toString() + "(" + name + ")");
+         }
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedPolicy.java
new file mode 100644
index 0000000..f951ec9
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/cluster/ha/ColocatedPolicy.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.cluster.ha;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.core.server.impl.ColocatedActivation;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.LiveActivation;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class ColocatedPolicy implements HAPolicy<LiveActivation>
+{
+
+   /*live stuff*/
+   private boolean requestBackup = HornetQDefaultConfiguration.isDefaultHapolicyRequestBackup();
+
+   private int backupRequestRetries = HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetries();
+
+   private long backupRequestRetryInterval = HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetryInterval();
+
+   private int maxBackups = HornetQDefaultConfiguration.getDefaultHapolicyMaxBackups();
+
+   private int backupPortOffset = HornetQDefaultConfiguration.getDefaultHapolicyBackupPortOffset();
+
+   /*backup stuff*/
+   private List<String> excludedConnectors = new ArrayList<>();
+
+   private BackupPolicy backupPolicy;
+
+   private HAPolicy<LiveActivation> livePolicy;
+
+   public ColocatedPolicy(boolean requestBackup,
+                          int backupRequestRetries,
+                          long backupRequestRetryInterval,
+                          int maxBackups,
+                          int backupPortOffset,
+                          List<String> excludedConnectors,
+                          HAPolicy livePolicy,
+                          BackupPolicy backupPolicy)
+   {
+      this.requestBackup = requestBackup;
+      this.backupRequestRetries = backupRequestRetries;
+      this.backupRequestRetryInterval = backupRequestRetryInterval;
+      this.maxBackups = maxBackups;
+      this.backupPortOffset = backupPortOffset;
+      this.excludedConnectors = excludedConnectors;
+      this.livePolicy = livePolicy;
+      this.backupPolicy = backupPolicy;
+   }
+
+   @Override
+   public String getBackupGroupName()
+   {
+      return null;
+   }
+
+   @Override
+   public String getScaleDownGroupName()
+   {
+      return null;
+   }
+
+   @Override
+   public boolean isSharedStore()
+   {
+      return backupPolicy.isSharedStore();
+   }
+
+   @Override
+   public boolean isBackup()
+   {
+      return false;
+   }
+
+   @Override
+   public LiveActivation createActivation(HornetQServerImpl server, boolean wasLive, Map<String, Object> activationParams, HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO) throws Exception
+   {
+      return new ColocatedActivation(server, this, livePolicy.createActivation(server, wasLive, activationParams, shutdownOnCriticalIO));
+   }
+
+   @Override
+   public boolean canScaleDown()
+   {
+      return false;
+   }
+
+   @Override
+   public String getScaleDownClustername()
+   {
+      return null;
+   }
+
+
+
+   public boolean isRequestBackup()
+   {
+      return requestBackup;
+   }
+
+   public void setRequestBackup(boolean requestBackup)
+   {
+      this.requestBackup = requestBackup;
+   }
+
+   public int getBackupRequestRetries()
+   {
+      return backupRequestRetries;
+   }
+
+   public void setBackupRequestRetries(int backupRequestRetries)
+   {
+      this.backupRequestRetries = backupRequestRetries;
+   }
+
+   public long getBackupRequestRetryInterval()
+   {
+      return backupRequestRetryInterval;
+   }
+
+   public void setBackupRequestRetryInterval(long backupRequestRetryInterval)
+   {
+      this.backupRequestRetryInterval = backupRequestRetryInterval;
+   }
+
+   public int getMaxBackups()
+   {
+      return maxBackups;
+   }
+
+   public void setMaxBackups(int maxBackups)
+   {
+      this.maxBackups = maxBackups;
+   }
+
+   public int getBackupPortOffset()
+   {
+      return backupPortOffset;
+   }
+
+   public void setBackupPortOffset(int backupPortOffset)
+   {
+      this.backupPortOffset = backupPortOffset;
+   }
+
+   public List<String> getExcludedConnectors()
+   {
+      return excludedConnectors;
+   }
+
+   public void setExcludedConnectors(List<String> excludedConnectors)
+   {
+      this.excludedConnectors = excludedConnectors;
+   }
+
+   public HAPolicy<LiveActivation> getLivePolicy()
+   {
+      return livePolicy;
+   }
+
+   public void setLivePolicy(HAPolicy<LiveActivation> livePolicy)
+   {
+      this.livePolicy = livePolicy;
+   }
+
+   public BackupPolicy getBackupPolicy()
+   {
+      return backupPolicy;
+   }
+
+   public void setBackupPolicy(BackupPolicy backupPolicy)
+   {
+      this.backupPolicy = backupPolicy;
+   }
+}


[46/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/jms-bridge/src/main/resources/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/jms-bridge/src/main/resources/hornetq-beans.xml b/examples/jms/jms-bridge/src/main/resources/hornetq-beans.xml
deleted file mode 100644
index c38275a..0000000
--- a/examples/jms/jms-bridge/src/main/resources/hornetq-beans.xml
+++ /dev/null
@@ -1,234 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <!-- **************************************** -->
-      <!-- Replace with the *target* server address -->
-      <!-- **************************************** -->
-      <property name="bindAddress">@TARGET_SERVER@</property>
-      <!-- **************************************** -->
-      <!-- Replace with the *target* server address -->
-      <!-- **************************************** -->
-      <property name="rmiBindAddress">@TARGET_SERVER@</property>
-      <property name="port">1099</property>
-      <property name="rmiPort">1098</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-   
-   <!-- The JMS Bridge -->
-   <bean name="JMSBridge" class="org.hornetq.jms.bridge.impl.JMSBridgeImpl">
-           <constructor>
-               <!-- Source ConnectionFactory Factory -->
-               <parameter>
-                   <inject bean="SourceCFF"/>
-               </parameter>
-               <!-- Target ConnectionFactory Factory -->
-               <parameter>
-                   <inject bean="TargetCFF"/>
-               </parameter>
-               <!-- Source DestinationFactory -->
-               <parameter>
-                   <inject bean="SourceDestinationFactory"/>
-               </parameter>
-               <!-- Target DestinationFactory -->
-               <parameter>
-                   <inject bean="TargetDestinationFactory"/>
-               </parameter>
-               <!-- Source username (no username here) -->
-               <parameter><null /></parameter>
-               <!-- Source password (no password here)-->
-               <parameter><null /></parameter>
-               <!-- Target username (no username here)-->
-               <parameter><null /></parameter>
-               <!-- Target password (no password here)-->
-               <parameter><null /></parameter>
-               <!-- Selector -->
-               <parameter><null /></parameter>
-               <!-- Interval to retry in case of failure (in ms) -->
-               <parameter>5000</parameter>
-               <!-- Maximum number of retries to connect to the source and target -->
-               <parameter>10</parameter>
-               <!-- Quality of service -->
-               <parameter>ONCE_AND_ONLY_ONCE</parameter>
-               <!-- Maximum batch size -->
-               <parameter>1</parameter>
-               <!-- Maximum batch time (-1 means infinite) -->
-               <parameter>-1</parameter>
-               <!-- Subscription name (no subscription name here)-->
-               <parameter><null /></parameter>
-               <!-- client ID  (no client ID here)-->
-               <parameter><null /></parameter>
-               <!-- concatenate JMS messageID to the target's message header -->
-               <parameter>true</parameter>
-               <!-- register the JMS Bridge in the JMX MBeanServer -->
-               <parameter>
-                   <inject bean="MBeanServer"/>
-               </parameter>
-               <parameter>org.hornetq:service=JMSBridge</parameter>
-           </constructor>
-           <property name="transactionManager">
-               <inject bean="TransactionManager"/>
-           </property>
-           
-           <!-- HornetQ JMS Server must be started before the bridge -->
-           <depends>JMSServerManager</depends>
-           
-       </bean>
-
-       <bean name="TransactionManager" class="com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple">
-       </bean>
-
-       <!-- SourceCFF describes the ConnectionFactory used to connect to the source destination -->
-       <bean name="SourceCFF" class="org.hornetq.jms.bridge.impl.JNDIConnectionFactoryFactory">
-           <constructor>
-               <parameter>
-                   <inject bean="SourceJNDI" />
-               </parameter>
-               <parameter>/source/ConnectionFactory</parameter>
-           </constructor>  
-       </bean>
-
-       <!-- TargetCFF describes the ConnectionFactory used to connect to the target destination -->
-       <bean name="TargetCFF" class="org.hornetq.jms.bridge.impl.JNDIConnectionFactoryFactory">
-           <constructor>
-               <parameter>
-                   <inject bean="TargetJNDI" />
-               </parameter>
-               <parameter>/target/ConnectionFactory</parameter>
-           </constructor>  
-       </bean>
-
-       <!-- SourceDestinationFactory describes the Destination used as the source -->
-       <bean name="SourceDestinationFactory" class="org.hornetq.jms.bridge.impl.JNDIDestinationFactory">
-           <constructor>
-               <parameter>
-                   <inject bean="SourceJNDI" />
-               </parameter>
-               <parameter>/source/topic</parameter>
-           </constructor>  
-       </bean>
-
-       <!-- TargetDestinationFactory describes the Destination used as the target -->
-       <bean name="TargetDestinationFactory" class="org.hornetq.jms.bridge.impl.JNDIDestinationFactory">
-           <constructor>
-               <parameter>
-                   <inject bean="TargetJNDI" />
-               </parameter>
-               <parameter>/target/queue</parameter>
-           </constructor>  
-       </bean>
-       
-       <!-- JNDI is a Hashtable containing the JNDI properties required -->
-       <!-- to connect to the *source* JMS resources                    -->       
-      <bean name="SourceJNDI" class="java.util.Hashtable">
-         <constructor class="java.util.Map">
-            <map class="java.util.Hashtable" keyClass="java.lang.String"
-                                             valueClass="java.lang.String">
-               <entry>
-                  <key>java.naming.factory.initial</key>
-                  <value>org.jnp.interfaces.NamingContextFactory</value>
-               </entry>
-               <entry>
-                  <key>java.naming.provider.url</key>
-                  <!-- **************************************** -->
-                  <!-- Replace with the *source* server address -->
-                  <!-- **************************************** -->
-                  <value>jnp://@SOURCE_SERVER@:1099</value>
-               </entry>
-               <entry>
-                  <key>java.naming.factory.url.pkgs</key>
-                  <value>org.jboss.naming:org.jnp.interfaces"</value>
-               </entry>
-               <entry>
-                  <key>jnp.timeout</key>
-                  <value>5000</value>
-               </entry>
-               <entry>
-                  <key>jnp.sotimeout</key>
-                  <value>5000</value>
-               </entry>
-            </map>
-         </constructor>
-      </bean>
-      
-      <!-- JNDI is a Hashtable containing the JNDI properties required -->
-      <!-- to connect to the *target* JMS resources                    -->       
-      <bean name="TargetJNDI" class="java.util.Hashtable">
-         <constructor class="java.util.Map">
-            <map class="java.util.Hashtable" keyClass="java.lang.String"
-                                             valueClass="java.lang.String">
-               <entry>
-                  <key>java.naming.factory.initial</key>
-                  <value>org.jnp.interfaces.NamingContextFactory</value>
-               </entry>
-               <entry>
-                  <key>java.naming.provider.url</key>
-                  <!-- **************************************** -->
-                  <!-- Replace with the *target* server address -->
-                  <!-- **************************************** -->
-                  <value>jnp://@TARGET_SERVER@:1099</value>
-               </entry>
-               <entry>
-                  <key>java.naming.factory.url.pkgs</key>
-                  <value>org.jboss.naming:org.jnp.interfaces"</value>
-               </entry>
-               <entry>
-                  <key>jnp.timeout</key>
-                  <value>5000</value>
-               </entry>
-               <entry>
-                  <key>jnp.sotimeout</key>
-                  <value>5000</value>
-               </entry>
-            </map>
-         </constructor>
-      </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 97f8649..c670e1f 100644
--- a/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -10,8 +10,10 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="SHARED_STORE">
-      <allow-failback>true</allow-failback>
+   <ha-policy>
+      <shared-store>
+         <master/>
+      </shared-store>
    </ha-policy>
 
    <!-- Connectors -->

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 4edace8..c3aec8b 100644
--- a/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -10,8 +10,10 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_SHARED_STORE">
-      <allow-failback>true</allow-failback>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
    </ha-policy>
 
     <!-- Connectors -->

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server2/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server2/hornetq-configuration.xml b/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server2/hornetq-configuration.xml
index 1d6ed9f..569407b 100644
--- a/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server2/hornetq-configuration.xml
+++ b/examples/jms/multiple-failover-failback/src/main/resources/hornetq/server2/hornetq-configuration.xml
@@ -10,8 +10,10 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_SHARED_STORE">
-      <allow-failback>true</allow-failback>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
    </ha-policy>
     
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
index cc04ddc..10d84cd 100644
--- a/examples/jms/multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <master/>
+      </shared-store>
+   </ha-policy>
 
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 437b56e..4246cb2 100644
--- a/examples/jms/multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
+   </ha-policy>
 
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml b/examples/jms/multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
index 9d647c6..52f807e 100644
--- a/examples/jms/multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
+++ b/examples/jms/multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
+   </ha-policy>
 
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/non-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/non-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/non-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 4c2bc1e..8ade9a9 100644
--- a/examples/jms/non-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/non-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -2,7 +2,11 @@
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
 
-   <ha-policy template="SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <master/>
+      </shared-store>
+   </ha-policy>
 
    <!-- Connectors -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/non-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/non-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/non-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 73b1f0f..206edf7 100644
--- a/examples/jms/non-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/non-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -1,8 +1,12 @@
 <configuration xmlns="urn:hornetq"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="urn:hornetq ../../../src/schema/hornetq-configuration.xsd">
+         xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
 
-   <ha-policy template="BACKUP_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
+   </ha-policy>
     
    <!-- Connectors -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/openwire/pom.xml
----------------------------------------------------------------------
diff --git a/examples/jms/openwire/pom.xml b/examples/jms/openwire/pom.xml
new file mode 100644
index 0000000..e91f633
--- /dev/null
+++ b/examples/jms/openwire/pom.xml
@@ -0,0 +1,125 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.hornetq.examples.jms</groupId>
+      <artifactId>jms-examples</artifactId>
+      <version>2.5.0-SNAPSHOT</version>
+   </parent>
+
+   <artifactId>hornetq-jms-openwire-example</artifactId>
+   <packaging>jar</packaging>
+   <name>HornetQ JMS Openwire Example</name>
+
+   <dependencies>
+      <dependency>
+         <groupId>org.hornetq.examples.jms</groupId>
+         <artifactId>hornetq-jms-examples-common</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.spec.javax.jms</groupId>
+         <artifactId>jboss-jms-api_2.0_spec</artifactId>
+      </dependency>
+      <dependency>
+         <groupId>org.apache.activemq</groupId>
+         <artifactId>activemq-client</artifactId>
+      </dependency>
+   </dependencies>
+
+   <build>
+      <plugins>
+         <plugin>
+            <groupId>org.hornetq</groupId>
+            <artifactId>hornetq-maven-plugin</artifactId>
+            <executions>
+               <execution>
+                  <id>start</id>
+                  <goals>
+                     <goal>start</goal>
+                  </goals>
+                  <configuration>
+                     <systemProperties>
+                        <property>
+                           <name>build.directory</name>
+                           <value>${basedir}/target/</value>
+                        </property>
+                     </systemProperties>
+                  </configuration>
+               </execution>
+               <execution>
+                  <id>runClient</id>
+                  <goals>
+                     <goal>runClient</goal>
+                  </goals>
+                  <configuration>
+                     <clientClass>org.hornetq.jms.example.OpenWireExample</clientClass>
+                     <args>
+                        <param>jnp://localhost:1099</param>
+                     </args>
+                  </configuration>
+               </execution>
+               <execution>
+                  <id>stop</id>
+                  <goals>
+                     <goal>stop</goal>
+                  </goals>
+               </execution>
+            </executions>
+            <dependencies>
+               <dependency>
+                  <groupId>org.hornetq.examples.jms</groupId>
+                  <artifactId>hornetq-jms-openwire-example</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-core-client</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-server</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-jms-client</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-jms-server</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-openwire-protocol</artifactId>
+                  <version>${project.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>io.netty</groupId>
+                  <artifactId>netty-all</artifactId>
+                  <version>${netty.version}</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.jboss.javaee</groupId>
+                  <artifactId>jboss-jms-api</artifactId>
+                  <version>1.1.0.GA</version>
+               </dependency>
+               <dependency>
+                  <groupId>org.jboss.naming</groupId>
+                  <artifactId>jnpserver</artifactId>
+                  <version>5.0.3.GA</version>
+               </dependency>
+            </dependencies>
+            <configuration>
+               <waitOnStart>false</waitOnStart>
+               <hornetqConfigurationDir>${basedir}/target/classes/hornetq/server0</hornetqConfigurationDir>
+            </configuration>
+         </plugin>
+      </plugins>
+   </build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/openwire/readme.html
----------------------------------------------------------------------
diff --git a/examples/jms/openwire/readme.html b/examples/jms/openwire/readme.html
new file mode 100644
index 0000000..a7e8d72
--- /dev/null
+++ b/examples/jms/openwire/readme.html
@@ -0,0 +1,79 @@
+<html>
+  <head>
+    <title>HornetQ OpenWire Example</title>
+    <link rel="stylesheet" type="text/css" href="../common/common.css" />
+    <link rel="stylesheet" type="text/css" href="../common/prettify.css" />
+    <script type="text/javascript" src="../common/prettify.js"></script>
+  </head>
+  <body onload="prettyPrint()">
+     <h1>JMS OpenWire Example</h1>
+
+     <p>This example shows you how to configure HornetQ server to communicate with an ActiveMQ JMS client using ActiveMQ's native openwire protocol.</p>
+
+     <h2>Example step-by-step</h2>
+     <p><i>To run the example, simply type <code>mvn verify</code> from this directory</i></p>
+
+     <ol>
+        <li>First we need to create an ActiveMQ connection factory.</code></li>
+        <pre class="prettyprint">
+           <code>ConnectionFactory factory = new ActiveMQConnectionFactory(urlString);</code>
+        </pre>
+
+        <li>Create the target queue</li>
+        <pre class="prettyprint">
+           <code>Queue queue = new ActiveMQQueue("exampleQueue");</code>
+        </pre>
+
+        <li>We create a JMS connection and start it</li>
+        <pre class="prettyprint">
+           <code>connection = cf.createConnection();</code>
+           <code>connection.start()</code>
+        </pre>
+
+        <li>We create a JMS session. The session is created as non transacted and will auto acknowledge messages.</li>
+        <pre class="prettyprint">
+           <code>Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);</code>
+        </pre>
+
+        <li>We create a JMS message producer on the session. This will be used to send the messages.</li>
+        <pre class="prettyprint">
+          <code>MessageProducer messageProducer = session.createProducer(topic);</code>
+       </pre>
+
+        <li>We create a JMS text message that we are going to send.</li>
+        <pre class="prettyprint">
+           <code>TextMessage message = session.createTextMessage("This is a text message");</code>
+        </pre>
+
+        <li>We send message to the queue</li>
+        <pre class="prettyprint">
+           <code>messageProducer.send(message);</code>
+        </pre>
+
+        <li>We create a JMS Message Consumer to receive the message.</li>
+          <pre class="prettyprint">
+           <code>MessageConsumer messageConsumer = session.createConsumer(queue);</code>
+        </pre>
+
+        <li>The message arrives at the consumer. In this case we use a timeout of 5000 milliseconds but we could use a blocking 'receive()'</li>
+        <pre class="prettyprint">
+           <code>TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);</code>
+        </pre>
+
+        <li>And finally, <b>always</b> remember to close your JMS connections and resources after use, in a <code>finally</code> block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects</li>
+
+        <pre class="prettyprint">
+           <code>finally
+           {
+              if (connection != null)
+              {
+                 connection.close();
+              }
+           }</code>
+        </pre>
+
+
+
+     </ol>
+  </body>
+</html>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/openwire/src/main/java/org/hornetq/jms/example/OpenWireExample.java
----------------------------------------------------------------------
diff --git a/examples/jms/openwire/src/main/java/org/hornetq/jms/example/OpenWireExample.java b/examples/jms/openwire/src/main/java/org/hornetq/jms/example/OpenWireExample.java
new file mode 100644
index 0000000..81f078e
--- /dev/null
+++ b/examples/jms/openwire/src/main/java/org/hornetq/jms/example/OpenWireExample.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.command.ActiveMQQueue;
+import org.hornetq.common.example.HornetQExample;
+
+/**
+ * A simple JMS Queue example that creates a producer and consumer on a queue
+ * and sends then receives a message.
+ * 
+ * @author <a href="ataylor@redhat.com">Andy Taylor</a>
+ */
+public class OpenWireExample extends HornetQExample
+{
+   public static final String OWHOST = "localhost";
+   public static final int OWPORT = 61616;
+
+   public static void main(final String[] args)
+   {
+      new OpenWireExample().run(args);
+   }
+
+   @Override
+   public boolean runExample() throws Exception
+   {
+      Connection connection = null;
+
+      try
+      {
+         String urlString = "tcp://" + OWHOST + ":" + OWPORT;
+
+         // Step 1. Create an ActiveMQ Connection Factory
+         ConnectionFactory factory = new ActiveMQConnectionFactory(urlString);
+
+         // Step 2. Create the target queue
+         Queue queue = new ActiveMQQueue("exampleQueue");
+
+         // Step 3. Create a JMS Connection
+         connection = factory.createConnection();
+
+         // Step 4. Start the Connection
+         connection.start();
+
+         // Step 5. Create a JMS Session
+         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+         // Step 6. Create a JMS Message Producer
+         MessageProducer producer = session.createProducer(queue);
+
+         // Step 7. Create a Text Message
+         TextMessage message = session.createTextMessage("This is a text message");
+
+         // Step 8. Send the Message
+         producer.send(message);
+
+         System.out.println("Sent message: " + message.getText());
+
+         // Step 9. Create a JMS Message Consumer
+         MessageConsumer messageConsumer = session.createConsumer(queue);
+
+         // Step 10. Receive the message
+         TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);
+
+         System.out.println("Received message: " + messageReceived.getText());
+
+         return true;
+      }
+      finally
+      {
+         if (connection != null)
+         {
+            connection.close();
+         }
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-configuration.xml
new file mode 100644
index 0000000..1c4b0e0
--- /dev/null
+++ b/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -0,0 +1,50 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
+
+   <bindings-directory>${build.directory}/server0/data/messaging/bindings</bindings-directory>
+
+   <journal-directory>${build.directory}/server0/data/messaging/journal</journal-directory>
+
+   <large-messages-directory>${build.directory}/server0/data/messaging/largemessages</large-messages-directory>
+
+   <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
+   
+   <connectors>
+      <connector name="netty-connector">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+      </connector>
+   </connectors>
+   
+   <!-- Acceptors -->
+   <acceptors>
+      <acceptor name="netty-acceptor">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>        
+      </acceptor>
+      <acceptor name="openwire-acceptor">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>        
+         <param key="protocols" value="OPENWIRE" />
+         <param key="port" value="61616" />
+     </acceptor>
+   </acceptors>
+
+   <!-- Other config -->
+
+   <security-settings>
+	  <security-setting match="jms.topic.ActiveMQ.Advisory.#">
+		 <permission type="createNonDurableQueue" roles="guest"/>		  
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+	  </security-setting>
+      <!--security for example queue-->
+      <security-setting match="jms.queue.exampleQueue">
+         <permission type="createDurableQueue" roles="guest"/>
+         <permission type="deleteDurableQueue" roles="guest"/>
+         <permission type="createNonDurableQueue" roles="guest"/>
+         <permission type="deleteNonDurableQueue" roles="guest"/>
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+      </security-setting>
+   </security-settings>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-jms.xml b/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-jms.xml
new file mode 100644
index 0000000..71b83dd
--- /dev/null
+++ b/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-jms.xml
@@ -0,0 +1,19 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
+   <!--the connection factory used by the example-->
+   <connection-factory name="ConnectionFactory">
+      <connectors>
+         <connector-ref connector-name="netty-connector"/>
+      </connectors>
+      <entries>
+         <entry name="ConnectionFactory"/>
+      </entries>
+   </connection-factory>
+
+   <!--the queue used by the example-->
+   <queue name="exampleQueue">
+      <entry name="/queue/exampleQueue"/>
+   </queue>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-users.xml b/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-users.xml
new file mode 100644
index 0000000..934306c
--- /dev/null
+++ b/examples/jms/openwire/src/main/resources/hornetq/server0/hornetq-users.xml
@@ -0,0 +1,7 @@
+<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
+   <!-- the default user.  this is used where username is null-->
+   <defaultuser name="guest" password="guest">
+      <role name="guest"/>
+   </defaultuser>
+</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-cpp/compile.sh
----------------------------------------------------------------------
diff --git a/examples/jms/proton-cpp/compile.sh b/examples/jms/proton-cpp/compile.sh
new file mode 100755
index 0000000..7ff5579
--- /dev/null
+++ b/examples/jms/proton-cpp/compile.sh
@@ -0,0 +1,2 @@
+# This requires g++ and qpid-cpp-client-devel
+g++ src/main/cpp/hello.cpp  -o hello -l qpidmessaging -l qpidtypes

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-cpp/pom.xml
----------------------------------------------------------------------
diff --git a/examples/jms/proton-cpp/pom.xml b/examples/jms/proton-cpp/pom.xml
new file mode 100644
index 0000000..b7fde84
--- /dev/null
+++ b/examples/jms/proton-cpp/pom.xml
@@ -0,0 +1,135 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.hornetq.examples.jms</groupId>
+      <artifactId>jms-examples</artifactId>
+      <version>2.5.0-SNAPSHOT</version>
+   </parent>
+
+   <artifactId>hornetq-jms-protoncpp</artifactId>
+   <packaging>jar</packaging>
+   <name>HornetQ AMQP CPP Example</name>
+
+   <dependencies>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-core-client</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-commons</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>io.netty</groupId>
+         <artifactId>netty-all</artifactId>
+         <version>${netty.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.javaee</groupId>
+         <artifactId>jboss-jms-api</artifactId>
+         <version>1.1.0.GA</version>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.naming</groupId>
+         <artifactId>jnp-client</artifactId>
+         <version>5.0.5.Final</version>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.spec.javax.jms</groupId>
+         <artifactId>jboss-jms-api_2.0_spec</artifactId>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-amqp-protocol</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+
+   </dependencies>
+
+   <profiles>
+      <profile>
+         <id>default</id>
+         <activation>
+            <activeByDefault>true</activeByDefault>
+         </activation>
+         <build>
+            <plugins>
+               <plugin>
+                  <groupId>org.hornetq</groupId>
+                  <artifactId>hornetq-maven-plugin</artifactId>
+                  <executions>
+                     <execution>
+                        <id>start</id>
+                        <goals>
+                           <goal>start</goal>
+                        </goals>
+                        <configuration>
+                           <waitOnStart>true</waitOnStart>
+                           <hornetqConfigurationDir>${basedir}/target/classes/hornetq/server0</hornetqConfigurationDir>
+                           <systemProperties>
+                              <property>
+                                 <name>build.directory</name>
+                                 <value>${basedir}/target/</value>
+                              </property>
+                           </systemProperties>
+                        </configuration>
+                     </execution>
+                  </executions>
+                  <configuration>
+                     <waitOnStart>false</waitOnStart>
+                     <hornetqConfigurationDir>${basedir}/target/classes/hornetq/server0</hornetqConfigurationDir>
+                  </configuration>
+                  <dependencies>
+                     <dependency>
+                        <groupId>org.hornetq</groupId>
+                        <artifactId>hornetq-core-client</artifactId>
+                        <version>${project.version}</version>
+                     </dependency>
+                     <dependency>
+                        <groupId>org.hornetq</groupId>
+                        <artifactId>hornetq-server</artifactId>
+                        <version>${project.version}</version>
+                     </dependency>
+                     <dependency>
+                        <groupId>org.hornetq</groupId>
+                        <artifactId>hornetq-jms-client</artifactId>
+                        <version>${project.version}</version>
+                     </dependency>
+                     <dependency>
+                        <groupId>org.hornetq</groupId>
+                        <artifactId>hornetq-jms-server</artifactId>
+                        <version>${project.version}</version>
+                     </dependency>
+                     <dependency>
+                        <groupId>org.hornetq</groupId>
+                        <artifactId>hornetq-amqp-protocol</artifactId>
+                        <version>${project.version}</version>
+                     </dependency>
+                     <dependency>
+                        <groupId>io.netty</groupId>
+                        <artifactId>netty-all</artifactId>
+                        <version>${netty.version}</version>
+                     </dependency>
+                     <dependency>
+                        <groupId>org.jboss.javaee</groupId>
+                        <artifactId>jboss-jms-api</artifactId>
+                        <version>1.1.0.GA</version>
+                     </dependency>
+                     <dependency>
+                        <groupId>org.jboss.naming</groupId>
+                        <artifactId>jnpserver</artifactId>
+                        <version>5.0.3.GA</version>
+                     </dependency>
+                  </dependencies>
+               </plugin>
+            </plugins>
+         </build>
+      </profile>
+   </profiles>
+
+
+</project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-cpp/readme.html
----------------------------------------------------------------------
diff --git a/examples/jms/proton-cpp/readme.html b/examples/jms/proton-cpp/readme.html
new file mode 100644
index 0000000..a64588d
--- /dev/null
+++ b/examples/jms/proton-cpp/readme.html
@@ -0,0 +1,104 @@
+<html>
+<head>
+    <title>HornetQ QPID cpp example</title>
+    <link rel="stylesheet" type="text/css" href="../common/common.css" />
+    <link rel="stylesheet" type="text/css" href="../common/prettify.css" />
+    <script type="text/javascript" src="../common/prettify.js"></script>
+</head>
+<body onload="prettyPrint()">
+<h1>AMQP CPP example</h1>
+
+<p>HornetQ is a multi protocol broker. It will inspect the initial handshake of clients to determine what protocol to use.</p>
+<p>All you need to do is to connect a client into hornetq's configured port and you should be able connect.</p>
+<p>To run this example simply run the command <literal>mvn verify</literal>, execute the compile.sh script and start the executable called ./hello</p>
+<pre>
+    # first make sure you have the dependencies you need to compile and run the client
+    # You will have to adapt this step according to your platform. Consult the <a href="http://qpid.apache.org/releases/qpid-0.30/programming/book/">qpid docs</a> for more information.
+    # There is a list of <a href="http://qpid.apache.org/packages.html">packages</a> you can install as well.
+    [proton-cpp]$ sudo yum install qpid-cpp-client-devel
+
+    # on a first window
+    [proton-cpp]$ mvn verify
+
+    # on a second window
+    # That goes without saying but you will of course need g++ (the C++ compiler) installed
+    [proton-cpp]$ ./compile.sh
+    [proton-cpp]$ ./hello
+</pre>
+
+
+<p>You don't need to do anything special to configure the HornetQ server to accept AMQP clients. </p>
+<p>Just for the sake of documentation though we are setting the port of HornetQ on this example as 5672 which is the port qpid have by default. </p>
+<p>This is totally optional and you don't need to follow this convention. You can use any port you chose including HornetQ's 5445 default port</p>
+     <pre class="prettyprint">
+     <code>
+         &lt;acceptor name="proton-acceptor"&gt;
+         &lt;factory-class&gt;org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory&lt;/factory-class&gt;
+         &lt;param key="port" value="5672"/&gt;
+         &lt;/acceptor&gt;
+     </code>
+     </pre>
+<h2>Example step-by-step</h2>
+<p> We are using qpid cpp client on this example. There are several libraries you may chose from for AMQP. We have ellect one that we consider simple enough for users.</p>
+
+<p> This example is based on <a href='http://qpid.apache.org/releases/qpid-0.30/messaging-api/cpp/examples/hello_world.cpp.html'>qpid's hello world example</a>.</p>
+<ol>
+    <li>qpid-cpp-client-devel installed.</li>
+    <p>Assuming you are on Linux Fedora, you will need to run this following command</p>
+    <pre class="prettyprint">
+        <code>yum install qpid-cpp-client-devel</code>
+    </pre>
+    <p>Consult the <a href="http://qpid.apache.org/releases/qpid-0.30/programming/book/">qpid documentation</a>, and <a href="http://qpid.apache.org/packages.html">the required </a> packages for information on other platoforms.</p>
+    <li>Make the proper C++ imports</li>
+
+    <li> Create an amqp qpid 1.0 connection.</li>
+        <pre class="prettyprint">
+           <code>
+        std::string broker = argc > 1 ? argv[1] : "localhost:5445";
+        std::string address = argc > 2 ? argv[2] : "jms.queue.exampleQueue";
+        std::string connectionOptions = argc > 3 ? argv[3] : "{protocol:amqp1.0}"; // Look at the <a href="http://qpid.apache.org/releases/qpid-0.30/programming/book/connections.html#connection-options">docs</a> for more options
+
+        Connection connection(broker, connectionOptions);
+        connection.open();
+           </code>
+        </pre>
+
+    <li>Create a session</li>
+        <pre class="prettyprint">
+       <code>Session session = connection.createSession();</code>
+        </pre>
+
+    <li>Create a sender</li>
+        <pre class="prettyprint">
+       <code>Sender sender = session.createSender(address);</code>
+        </pre>
+
+    <li>send a simple message</li>
+        <pre class="prettyprint">
+       <code>sender.send(Message("Hello world!"));</code>
+        </pre>
+
+    <li>create a receiver</li>
+        <pre class="prettyprint">
+       <code>Receiver receiver = session.createReceiver(address);</code>
+        </pre>
+
+    <li>receive the simple message</li>
+        <pre class="prettyprint">
+      <code>Message message = receiver.fetch(Duration::SECOND * 1);
+      </code>
+        </pre>
+
+    <li>acknowledge the message</li>
+        <pre class="prettyprint">
+      <code>session.acknowledge();</code>
+        </pre>
+
+    <li>close the connection</li>
+        <pre class="prettyprint">
+      <code>connection.close();</code>
+        </pre>
+</ol>
+
+</body>
+</html>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-cpp/src/main/cpp/hello.cpp
----------------------------------------------------------------------
diff --git a/examples/jms/proton-cpp/src/main/cpp/hello.cpp b/examples/jms/proton-cpp/src/main/cpp/hello.cpp
new file mode 100644
index 0000000..a14eff5
--- /dev/null
+++ b/examples/jms/proton-cpp/src/main/cpp/hello.cpp
@@ -0,0 +1,72 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+// Step 2. Make the proper C++ imports
+#include <qpid/messaging/Connection.h>
+#include <qpid/messaging/Message.h>
+#include <qpid/messaging/Receiver.h>
+#include <qpid/messaging/Sender.h>
+#include <qpid/messaging/Session.h>
+
+#include <iostream>
+
+using namespace qpid::messaging;
+
+int main(int argc, char** argv) {
+    std::string broker = argc > 1 ? argv[1] : "localhost:5445";
+    std::string address = argc > 2 ? argv[2] : "jms.queue.exampleQueue";
+
+    // Connection options documented at http://qpid.apache.org/releases/qpid-0.30/programming/book/connections.html#connection-options
+    std::string connectionOptions = argc > 3 ? argv[3] : "{protocol:amqp1.0}";
+
+    try {
+         // Step 3. Create an amqp qpid 1.0 connection
+        Connection connection(broker, connectionOptions);
+        connection.open();
+
+         // Step 4. Create a session
+        Session session = connection.createSession();
+
+         // Step 5. Create a sender
+        Sender sender = session.createSender(address);
+
+         // Step 6. send a simple message
+        sender.send(Message("Hello world!"));
+
+         // Step 7. create a receiver
+        Receiver receiver = session.createReceiver(address);
+
+         // Step 8. receive the simple message
+        Message message = receiver.fetch(Duration::SECOND * 1);
+        std::cout << "Received a message with this following content \"" << message.getContent() << "\"" << std::endl;
+
+         // Step 9. acknowledge the message
+        session.acknowledge();
+
+        // Step 10. close the connection
+        connection.close();
+        return 0;
+    } catch(const std::exception& error) {
+        std::cerr << error.what() << std::endl;
+        return 1;
+    }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-configuration.xml
new file mode 100644
index 0000000..253375e
--- /dev/null
+++ b/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -0,0 +1,35 @@
+<configuration xmlns="urn:hornetq"
+               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
+
+   <bindings-directory>${build.directory}/server0/data/messaging/bindings</bindings-directory>
+
+   <journal-directory>${build.directory}/server0/data/messaging/journal</journal-directory>
+
+   <large-messages-directory>${build.directory}/server0/data/messaging/largemessages</large-messages-directory>
+
+   <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
+
+
+   <!-- Acceptors -->
+   <acceptors>
+      <acceptor name="proton-acceptor">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+      </acceptor>
+   </acceptors>
+
+   <!-- Other config -->
+
+   <security-settings>
+      <!--security for example queue-->
+      <security-setting match="jms.queue.exampleQueue">
+         <permission type="createDurableQueue" roles="guest"/>
+         <permission type="deleteDurableQueue" roles="guest"/>
+         <permission type="createNonDurableQueue" roles="guest"/>
+         <permission type="deleteNonDurableQueue" roles="guest"/>
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+      </security-setting>
+   </security-settings>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-jms.xml b/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-jms.xml
new file mode 100644
index 0000000..9ec5894
--- /dev/null
+++ b/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-jms.xml
@@ -0,0 +1,10 @@
+<configuration xmlns="urn:hornetq"
+               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
+
+   <!--the queue used by the example-->
+   <queue name="exampleQueue">
+      <entry name="/queue/exampleQueue"/>
+   </queue>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-users.xml b/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-users.xml
new file mode 100644
index 0000000..934306c
--- /dev/null
+++ b/examples/jms/proton-cpp/src/main/resources/hornetq/server0/hornetq-users.xml
@@ -0,0 +1,7 @@
+<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
+   <!-- the default user.  this is used where username is null-->
+   <defaultuser name="guest" password="guest">
+      <role name="guest"/>
+   </defaultuser>
+</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-j/readme.html
----------------------------------------------------------------------
diff --git a/examples/jms/proton-j/readme.html b/examples/jms/proton-j/readme.html
index cac21b0..c732a66 100644
--- a/examples/jms/proton-j/readme.html
+++ b/examples/jms/proton-j/readme.html
@@ -8,16 +8,17 @@
 <body onload="prettyPrint()">
 <h1>Proton qpid java example</h1>
 
-<p>HornetQ can be configured to accept requests from any AMQP client that supports the 1.0 version of the protocol.
-    This example shows a simply qpid java 1.0 client example</p>
-<p>To run the example simply run the command <literal>mvn verify</literal></p>
+<<p>HornetQ is a multi protocol broker. It will inspect the initial handshake of clients to determine what protocol to use.</p>
+<p>All you need to do is to connect a client into hornetq's configured port and you should be able connect.</p>
+<p>To run this example simply run the command <literal>mvn verify</literal>, execute the compile.sh script and start the executable called ./hello</p>
 
-<p>To configure HornetQ to accept AMQP client connections you need to add an Acceptor like so:</p>
+<p>You don't need to do anything special to configure the HornetQ server to accept AMQP clients. </p>
+<p>Just for the sake of documentation though we are setting the port of HornetQ on this example as 5672 which is the port qpid have by default. </p>
+<p>This is totally optional and you don't need to follow this convention. You can use any port you chose including HornetQ's 5445 default port</p>
      <pre class="prettyprint">
      <code>
          &lt;acceptor name="proton-acceptor"&gt;
          &lt;factory-class&gt;org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory&lt;/factory-class&gt;
-         &lt;param key="protocol" value="AMQP"/&gt;
          &lt;param key="port" value="5672"/&gt;
          &lt;/acceptor&gt;
      </code>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-j/src/main/java/org/hornetq/jms/example/ProtonJExample.java
----------------------------------------------------------------------
diff --git a/examples/jms/proton-j/src/main/java/org/hornetq/jms/example/ProtonJExample.java b/examples/jms/proton-j/src/main/java/org/hornetq/jms/example/ProtonJExample.java
index 64defa2..7f848fc 100644
--- a/examples/jms/proton-j/src/main/java/org/hornetq/jms/example/ProtonJExample.java
+++ b/examples/jms/proton-j/src/main/java/org/hornetq/jms/example/ProtonJExample.java
@@ -41,13 +41,13 @@ public class ProtonJExample extends HornetQExample
          Session session = connection.createSession();
 
          // Step 3. Create a sender
-         Sender sender = session.createSender("testQueue");
+         Sender sender = session.createSender("jms.queue.exampleQueue");
 
          // Step 4. send a simple message
          sender.send(new Message("I am an amqp message"));
 
          // Step 5. create a moving receiver, this means the message will be removed from the queue
-         Receiver rec = session.createMovingReceiver("testQueue");
+         Receiver rec = session.createMovingReceiver("jms.queue.exampleQueue");
 
          // Step 6. set some credit so we can receive
          rec.setCredit(UnsignedInteger.valueOf(1), false);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 5040931..6975003 100644
--- a/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -15,7 +15,6 @@
     <acceptors>
         <acceptor name="proton-acceptor">
             <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-            <param key="protocol" value="AMQP"/>
             <param key="port" value="5672"/>
         </acceptor>
     </acceptors>
@@ -30,7 +29,7 @@
 
    <security-settings>
       <!--security for example queue-->
-      <security-setting match="testQueue">
+      <security-setting match="jms.queue.exampleQueue">
          <permission type="createDurableQueue" roles="guest"/>
          <permission type="deleteDurableQueue" roles="guest"/>
          <permission type="createNonDurableQueue" roles="guest"/>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-jms.xml b/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-jms.xml
index 2aef01e..b2ec7ca 100644
--- a/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-jms.xml
+++ b/examples/jms/proton-j/src/main/resources/hornetq/server0/hornetq-jms.xml
@@ -2,5 +2,9 @@
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
 
+   <!--the queue used by the example-->
+   <queue name="exampleQueue">
+      <entry name="/queue/exampleQueue"/>
+   </queue>
 
 </configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-failback-static/readme.html
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-failback-static/readme.html b/examples/jms/replicated-failback-static/readme.html
index c04419b..79e8f98 100644
--- a/examples/jms/replicated-failback-static/readme.html
+++ b/examples/jms/replicated-failback-static/readme.html
@@ -7,8 +7,6 @@
   </head>
   <body onload="prettyPrint()">
      <h1>JMS Multiple Failover using Replication Example</h1>
-
-     <b>Note that failback example is not working in 2.3.0.Alpha but will be fully functional in the next release.</b>
      
      <p>This example demonstrates three servers coupled as a live-backup-backup group for high availability (HA) using replication, and a client
      connection failing over from live to backup when the live server is crashed and then to the second backup once the new live fails.</p>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-failback-static/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-failback-static/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/replicated-failback-static/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 8fa244a..e761e94 100644
--- a/examples/jms/replicated-failback-static/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/replicated-failback-static/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -14,10 +14,14 @@
 
    <cluster-password>secret</cluster-password>
 
-   <ha-policy template="REPLICATED">
-      <!--we need this for auto failback-->
-      <check-for-live-server>true</check-for-live-server>
-      <allow-failback>true</allow-failback>
+   <ha-policy>
+      <replication>
+         <master>
+            <!--we need this for auto failback-->
+            <check-for-live-server>true</check-for-live-server>
+            <allow-failback>true</allow-failback>
+         </master>
+      </replication>
    </ha-policy>
 
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-failback-static/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-failback-static/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/replicated-failback-static/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 5efbb42..d523667 100644
--- a/examples/jms/replicated-failback-static/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/replicated-failback-static/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -14,10 +14,14 @@
 
     <cluster-password>secret</cluster-password>
 
-   <ha-policy template="BACKUP_REPLICATED">
-      <allow-failback>true</allow-failback>
-      <!-- not needed but tells the backup not to restart after failback as there will be > 0 backups saved -->
-      <max-saved-replicated-journals-size>0</max-saved-replicated-journals-size>
+   <ha-policy>
+      <replication>
+         <slave>
+            <allow-failback>true</allow-failback>
+            <!-- not needed but tells the backup not to restart after failback as there will be > 0 backups saved -->
+            <max-saved-replicated-journals-size>0</max-saved-replicated-journals-size>
+         </slave>
+      </replication>
    </ha-policy>
 
    <!-- Connectors -->

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/replicated-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
index fb7ece0..c2f96ef 100644
--- a/examples/jms/replicated-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/replicated-failback/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -14,10 +14,14 @@
 
    <cluster-password>secret</cluster-password>
 
-   <ha-policy template="REPLICATED">
-      <!--we need this for auto failback-->
-      <check-for-live-server>true</check-for-live-server>
-      <allow-failback>true</allow-failback>
+   <ha-policy>
+      <replication>
+         <master>
+            <!--we need this for auto failback-->
+            <check-for-live-server>true</check-for-live-server>
+            <allow-failback>true</allow-failback>
+         </master>
+      </replication>
    </ha-policy>
 
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/replicated-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
index c4178eb..183f7cc 100644
--- a/examples/jms/replicated-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/replicated-failback/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -14,8 +14,12 @@
 
    <cluster-password>secret</cluster-password>
 
-   <ha-policy template="BACKUP_REPLICATED">
-      <allow-failback>true</allow-failback>
+   <ha-policy>
+      <replication>
+         <slave>
+            <allow-failback>true</allow-failback>
+         </slave>
+      </replication>
    </ha-policy>
 
    <!-- Connectors -->

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
index cc04ddc..50b968e 100644
--- a/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="SHARED_STORE"/>
+   <ha-policy>
+      <replication>
+         <master/>
+      </replication>
+   </ha-policy>
 
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 633f3c4..36ffd7c 100644
--- a/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server1/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_REPLICATED"/>
+   <ha-policy>
+      <replication>
+         <slave/>
+      </replication>
+   </ha-policy>
 
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml b/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
index 325b6ab..1b571da 100644
--- a/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
+++ b/examples/jms/replicated-multiple-failover/src/main/resources/hornetq/server2/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server2/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_REPLICATED"/>
+   <ha-policy>
+      <replication>
+         <slave/>
+      </replication>
+   </ha-policy>
     
    <connectors>
       <connector name="netty-live-connector">

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 551725f..3630d94 100644
--- a/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="REPLICATED"/>
+   <ha-policy>
+      <replication>
+         <master/>
+      </replication>
+   </ha-policy>
 
    <!-- Connectors -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 66b6f39..e371cdb 100644
--- a/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/replicated-transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -1,6 +1,6 @@
 <configuration xmlns="urn:hornetq"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="urn:hornetq ../../../../../../../hornetq-core/src/main/resources/schema/hornetq-configuration.xsd">
+         xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
 
    <bindings-directory>${build.directory}/server1/data/messaging/bindings</bindings-directory>
 
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server1/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_REPLICATED"/>
+   <ha-policy>
+      <replication>
+         <slave/>
+      </replication>
+   </ha-policy>
     
    <!-- Connectors -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/scale-down/readme.html
----------------------------------------------------------------------
diff --git a/examples/jms/scale-down/readme.html b/examples/jms/scale-down/readme.html
index ab7929f..f009d58 100644
--- a/examples/jms/scale-down/readme.html
+++ b/examples/jms/scale-down/readme.html
@@ -13,16 +13,18 @@
      <p>The second live server is killed and its messages are scaled down to the first server on shutdown.</p>
      <p>The following shows how to configure the live servers to scale down to one another.</p>
      <pre class="prettyprint">
-     <code>&lt;ha-policy template="NONE">
-         &lt;scale-down>true&lt;/scale-down>
-         &lt;scale-down-connectors>
-         &lt;connector-ref>server1-connector&lt;/connector-ref>
-         &lt;/scale-down-connectors>
-     </ha-policy>
+     <code>
+     &lt;ha-policy>
+         &lt;live-only>
+             &lt;scale-down>
+                 &lt;connectors>
+                     &lt;connector-ref>server0-connector&lt;/connector-ref>
+                 &lt;/connectors>
+             &lt;/scale-down>
+         &lt;/live-only>
+     &lt;/ha-policy>
      </code>
      </pre>
-     <p>notice that we have used a template to set some sensible defaults but overridden the backup strategy so back ups
-     are full servers</p>
      <h2>Example step-by-step</h2>
      <p><i>To run the example, simply type <code>mvn verify</code> from this directory</i></p>
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 23faf76..1990397 100644
--- a/examples/jms/scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -62,13 +62,7 @@
       </cluster-connection>
    </cluster-connections>
 
-   <!--a live server that will scale down on server shutdown-->
-   <ha-policy template="NONE">
-      <scale-down>true</scale-down>
-      <scale-down-connectors>
-         <connector-ref>server1-connector</connector-ref>
-      </scale-down-connectors>
-   </ha-policy>
+   <ha-policy/>
    
    <!-- Other config -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 8041fb4..9db2874 100644
--- a/examples/jms/scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -64,11 +64,14 @@
    </cluster-connections>
 
    <!--a live server that will scale down on server shutdown-->
-   <ha-policy template="NONE">
-      <scale-down>true</scale-down>
-      <scale-down-connectors>
-         <connector-ref>server0-connector</connector-ref>
-      </scale-down-connectors>
+   <ha-policy>
+      <live-only>
+         <scale-down>
+            <connectors>
+               <connector-ref>server0-connector</connector-ref>
+            </connectors>
+         </scale-down>
+      </live-only>
    </ha-policy>
    
    <!-- Other config -->

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/stop-server-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/stop-server-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/stop-server-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 037891d..8ebca5d 100644
--- a/examples/jms/stop-server-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/stop-server-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <master/>
+      </shared-store>
+   </ha-policy>
     
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/stop-server-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/stop-server-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/stop-server-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 191c5e7..c6a960b 100644
--- a/examples/jms/stop-server-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/stop-server-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
+   </ha-policy>
     
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/topic/src/main/resources/hornetq/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/topic/src/main/resources/hornetq/server0/hornetq-beans.xml b/examples/jms/topic/src/main/resources/hornetq/server0/hornetq-beans.xml
deleted file mode 100644
index 171d373..0000000
--- a/examples/jms/topic/src/main/resources/hornetq/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 3669a9c..2d5dbcd 100644
--- a/examples/jms/transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/transaction-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <master/>
+      </shared-store>
+   </ha-policy>
     
    <!-- Connectors -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
index b23a7be..0a96b6c 100644
--- a/examples/jms/transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/transaction-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
+   </ha-policy>
     
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/xa-with-jta/pom.xml
----------------------------------------------------------------------
diff --git a/examples/jms/xa-with-jta/pom.xml b/examples/jms/xa-with-jta/pom.xml
index 4a14816..e0c915d 100644
--- a/examples/jms/xa-with-jta/pom.xml
+++ b/examples/jms/xa-with-jta/pom.xml
@@ -24,7 +24,7 @@
       </dependency>
       <dependency>
          <groupId>org.jboss.spec.javax.transaction</groupId>
-         <artifactId>jboss-transaction-api_1.1_spec</artifactId>
+         <artifactId>jboss-transaction-api_1.2_spec</artifactId>
       </dependency>
       <dependency>
          <groupId>org.jboss.jbossts</groupId>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/README
----------------------------------------------------------------------
diff --git a/examples/soak/normal/README b/examples/soak/normal/README
index 831806f..b1025c4 100644
--- a/examples/soak/normal/README
+++ b/examples/soak/normal/README
@@ -2,23 +2,36 @@
 * Soak Test For Manual Reconnection of JMS Clients *
 ****************************************************
 
-Run The Server
-==============
+Running the Soak Tests
+=======================
+
+The default soak tests with start a HornetQ instance, 1 producer and 1 consumer.  To run the default suite.
+
+  $mvn verify
+
+Run The Server Standalone
+==========================
+
+If would like to run a number of servers or run the server on a different machine:
 
 To run server using the default configuration (server0, using localhost):
-   $ ant runServer
+   $ mvn verify -Pserver
 
 To run multiple servers, you can specify the server configuration directory using server.dir 
 system property (which defaults to server0). To run a 2nd server with a configuration stored in server1:
 
-   $ ant -Dserver.dir=server1 
+   $ mvn verify -Pserver -Dserver.dir=server1
 
-server1 dir contains a copy of server0 with different settings.
+server1 should contain a copy of configuration equivilent to that found under the server0 director with different
+settings.
 
-To run a server with the same configuration but on a different host, change:
+To run a server with the same configuration but on a different host.  Check out this source on the host machine and
+change:
 * hornetq.remoting.netty.host property in hornetq-configuration.xml
 * bindAddress and rmiBindAddress properties in hornetq-beans.xml
 
+  $ mvn verify -P server
+
 Configure Server Dump
 =====================
 
@@ -39,23 +52,22 @@ total paging memory:   0,00 B
 # of conns:      0
 ********************
 
-Run The Client
-==============
+Run The Clients
+===============
+
+The clients can be run separate from the server using:
+
+  $ mvn verify -Premote
+
+Parameters are specified in soak.properties.
 
-Senders (resp. receivers) are run with "ant runSender" (resp. "ant runReceiver").
-Parameters are specified in soak.properties. 
 The duration of the tests is configured by duration-in-minutes (defaults to 2 minutes, set to 
 -1 to run the test indefinitely).
 
-To configure the soak properties to run the client, use the system property soak.props.
+To configure the soak properties different to the defaults for the clients, use the system property
 To specify the JNDI server to connect to, use the system property jndi.address
-(defaults to localhost) and jndi.port (defaults to 1099)
-
-To run a receiver connected to the local server with soak.properties
-  $  ant runReceiver
 
-To run a sender connected to another server using settings in paging-soak.properties:
-  $ ant runSender -Djndi.address=172.16.8.10 -Djndi.port=2099 -Dsoak.props=paging-soak.properties
+  $ mvn verify -Premote -Dsoak.props=<path to properties> -Pjndi.address=jnp:remote.host:1099
 
 Every 1000th message, the clients will display their recent activity:
 
@@ -72,6 +84,3 @@ You can kill the server (ctl+c or kill -9), the clients are configured to reconn
 indefinitely to the same single server (even in case of clean shutdown)
 Once the server restarts, all the clients will resume their activities after reconnecting
 to the server.
-
-
-

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/normal/build.xml
----------------------------------------------------------------------
diff --git a/examples/soak/normal/build.xml b/examples/soak/normal/build.xml
deleted file mode 100644
index 9b04232..0000000
--- a/examples/soak/normal/build.xml
+++ /dev/null
@@ -1,92 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE project [
-      <!ENTITY libraries SYSTEM "../../../thirdparty/libraries.ent">
-      ]>
-
-<!--
-Copyright 2009 Red Hat, Inc.
- Red Hat licenses this file to you under the Apache License, version
- 2.0 (the "License"); you may not use this file except in compliance
- with the License.  You may obtain a copy of the License at
-   http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied.  See the License for the specific language governing
- permissions and limitations under the License.
-  -->
-
-<project name="HornetQ JMS Soak Example">
-
-	<import file="../../common/build.xml" />
-
-    <property name="server.dir" value="server0" />
-    <property name="jndi.address" value="localhost" />
-    <property name="jndi.port" value="1099" />
-    <property name="soak.props" value="soak.properties" />
-	
-	<path id="extra.classpath">
-		<path location="${server.dir}" />
-		<fileset dir="extra-libs">
-			<include name="*.jar" />
-		</fileset>
-	</path>
-
-	<path id="the.classpath">
-		<path refid="client.classpath" />
-		<path location="." />
-	</path>
-
-	<target name="runSender" depends="compile">
-	    <property name="jndi.url" value="jnp://${jndi.address}:${jndi.port}" />
-		<java classname="org.hornetq.jms.soak.example.SoakSender" fork="true" resultproperty="example-result">
-			<jvmarg value="-Xms512M" />
-			<jvmarg value="-Xmx512M" />
-			<jvmarg value="-XX:+UseParallelGC" />
-			<jvmarg value="-XX:+AggressiveOpts" />
-			<jvmarg value="-Dcom.sun.management.jmxremote" />
-			<jvmarg value="-XX:+UseFastAccessorMethods" />
-			<!--
-                 <jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"/>
-             -->
-			<jvmarg value="-Djava.util.logging.config.file=${config.dir}/logging.properties" />
-			<classpath refid="the.classpath" />
-			<arg line="${jndi.url} ${soak.props}" />
-		</java>
-	</target>
-
-	<target name="runReceiver" depends="compile">
-	    <property name="jndi.url" value="jnp://${jndi.address}:${jndi.port}" />
-		<java classname="org.hornetq.jms.soak.example.SoakReceiver" fork="true" resultproperty="example-result">
-			<jvmarg value="-Xms512M" />
-			<jvmarg value="-Xmx512M" />
-			<jvmarg value="-XX:+UseParallelGC" />
-			<jvmarg value="-XX:+AggressiveOpts" />
-			<jvmarg value="-Dcom.sun.management.jmxremote" />
-			<jvmarg value="-XX:+UseFastAccessorMethods" />
-			<!--
-                 <jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"/>
-             -->
-			<jvmarg value="-Djava.util.logging.config.file=${config.dir}/logging.properties" />
-			<classpath refid="the.classpath" />
-			<arg line="${jndi.url} ${soak.props}" />
-		</java>
-	</target>
-
-	<target name="runServer" depends="compile">
-	    <echo message="Using server configuration from server.dir: ${server.dir}" />
-		<java classname="org.hornetq.common.example.SpawnedHornetQServer" fork="true" clonevm="true" resultproperty="example-result">
-			<jvmarg value="-Xms2048M" />
-			<jvmarg value="-Xmx2048M" />
-			<jvmarg value="-XX:+UseParallelGC" />
-			<sysproperty key="java.library.path" value="${java.library.path}${path.separator}${aio.library.path}" />
-			<jvmarg value="-XX:+AggressiveOpts" />
-			<jvmarg value="-XX:+UseFastAccessorMethods" />
-			<jvmarg value="-Djava.util.logging.config.file=${config.dir}/logging.properties" />
-			<jvmarg value="-Dcom.sun.management.jmxremote" />
-			<arg line="hornetq-beans.xml" />
-			<classpath refid="extra.classpath" />
-			<classpath refid="server.classpath" />
-		</java>
-	</target>
-</project>


[47/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/using-core.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/using-core.xml b/docs/user-manual/en/using-core.xml
index eb72c79..38f3d3a 100644
--- a/docs/user-manual/en/using-core.xml
+++ b/docs/user-manual/en/using-core.xml
@@ -181,29 +181,40 @@
     <section>
         <title>A simple example of using Core</title>
         <para>Here's a very simple program using the core messaging API to send and receive a
-            message:</para>
+            message. Logically it's comprised of two sections: firstly setting up the producer to 
+            write a message to an <emphasis>addresss</emphasis>, and secondly, creating a 
+            <emphasis>queue</emphasis> for the consumer, creating the consumer and 
+            <emphasis>starting</emphasis> it.</para>
         <programlisting>
 ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(
                                            InVMConnectorFactory.class.getName()));
 
-ClientSessionFactory factory =  locator.createClientSessionFactory();
+// In this simple example, we just use one session for both producing and receiving
 
+ClientSessionFactory factory =  locator.createClientSessionFactory();
 ClientSession session = factory.createSession();
 
-session.createQueue("example", "example", true);
+// A producer is associated with an address ...
 
 ClientProducer producer = session.createProducer("example");
-
 ClientMessage message = session.createMessage(true);
-
 message.getBodyBuffer().writeString("Hello");
 
-producer.send(message);
+// We need a queue attached to the address ...
 
-session.start();
+session.createQueue("example", "example", true);
+
+// And a consumer attached to the queue ...
 
 ClientConsumer consumer = session.createConsumer("example");
 
+// Once we have a queue, we can send the message ...
+
+producer.send(message);
+
+// We need to start the session before we can -receive- messages ...
+
+session.start();
 ClientMessage msgReceived = consumer.receive();
 
 System.out.println("message = " + msgReceived.getBodyBuffer().readString());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/using-server.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/using-server.xml b/docs/user-manual/en/using-server.xml
index c5f1265..17ce895 100644
--- a/docs/user-manual/en/using-server.xml
+++ b/docs/user-manual/en/using-server.xml
@@ -35,30 +35,26 @@
         <title>Starting and Stopping the standalone server</title>
         <para>In the distribution you will find a directory called <literal>bin</literal>.</para>
         <para><literal>cd</literal> into that directory and you will find a Unix/Linux script called
-                <literal>run.sh</literal> and a windows batch file called <literal
-            >run.bat</literal></para>
-        <para>To run on Unix/Linux type <literal>./run.sh</literal></para>
-        <para>To run on Windows type <literal>run.bat</literal></para>
+                <literal>hornetq</literal> and a Windows script called <literal>hornetq.cmd</literal>.</para>
+        <para>To start the HornetQ instance on Unix/Linux type <literal>./hornetq run</literal></para>
+        <para>To start the HornetQ instance on Windows type <literal>hornetq.cmd run</literal></para>
         <para>These scripts are very simple and basically just set-up the classpath and some JVM
-            parameters and start the JBoss Microcontainer. The Microcontainer is a light weight
-            container used to deploy the HornetQ POJO's</para>
-        <para>To stop the server you will also find a Unix/Linux script <literal>stop.sh</literal> and
-            a windows batch file <literal>stop.bat</literal></para>
-        <para>To run on Unix/Linux type <literal>./stop.sh</literal></para>
-        <para>To run on Windows type <literal>stop.bat</literal></para>
+            parameters and bootstrap the server using <ulink
+                   url="https://github.com/airlift/airline">Airline</ulink>.</para>
+        <para>To stop the HornetQ instance you will use the same <literal>hornetq</literal> script.</para>
+        <para>To run on Unix/Linux type <literal>./hornetq stop</literal></para>
+        <para>To run on Windows type <literal>hornetq.cmd stop</literal></para>
         <para>Please note that HornetQ requires a Java 6 or later runtime to run.</para>
-        <para>Both the run and the stop scripts use the config under <literal
-                >config/stand-alone/non-clustered</literal> by default. The configuration can be
-            changed by running <literal>./run.sh ../config/stand-alone/clustered</literal> or
-            another config of your choosing. This is the same for the stop script and the windows
-            bat files.</para>
+        <para>By default the <literal>config/non-clustered/bootstrap.xml</literal> configuration is used. The
+            configuration can be changed e.g. by running
+            <literal>./hornetq run -- xml:../config/clustered/bootstrap.xml</literal> or another config of
+            your choosing.</para>
     </section>
     <section>
         <title>Server JVM settings</title>
-        <para>The run scripts <literal>run.sh</literal> and <literal>run.bat</literal> set some JVM
-            settings for tuning running on Java 6 and choosing the garbage collection policy. We
-            recommend using a parallel garbage collection algorithm to smooth out latency and
-            minimise large GC pauses.</para>
+        <para>The run scripts set some JVM settings for tuning the garbage collection policy
+            and heap size. We recommend using a parallel garbage collection algorithm to smooth
+            out latency and minimise large GC pauses.</para>
         <para>By default HornetQ runs in a maximum of 1GiB of RAM. To increase the memory settings
             change the <literal>-Xms</literal> and <literal>-Xmx</literal> memory settings as you
             would for any Java program.</para>
@@ -66,15 +62,7 @@
             are the place to do it.</para>
     </section>
     <section>
-        <title>Server classpath</title>
-        <para>HornetQ looks for its configuration files on the Java classpath.</para>
-        <para>The scripts <literal>run.sh</literal> and <literal>run.bat</literal> specify the
-            classpath when calling Java to run the server.</para>
-        <para>In the distribution, the run scripts will add the non clustered configuration
-            directory to the classpath. This is a directory which contains a set of configuration
-            files for running the HornetQ server in a basic non-clustered configuration. In the
-            distribution this directory is <literal>config/stand-alone/non-clustered/</literal> from
-            the root of the distribution.</para>
+        <title>Pre-configured Options</title>
         <para>The distribution contains several standard configuration sets for running:</para>
         <itemizedlist>
             <listitem>
@@ -84,22 +72,20 @@
                 <para>Clustered stand-alone</para>
             </listitem>
             <listitem>
-                <para>Non clustered in JBoss Application Server</para>
+                <para>Replicated stand-alone</para>
             </listitem>
             <listitem>
-                <para>Clustered in JBoss Application Server</para>
+                <para>Shared-store stand-alone</para>
             </listitem>
         </itemizedlist>
         <para>You can of course create your own configuration and specify any configuration
-            directory when running the run script.</para>
-        <para>Just make sure the directory is on the classpath and HornetQ will search there when
-            starting up.</para>
+            when running the run script.</para>
     </section>
     <section id="using-server.library.path">
         <title>Library Path</title>
         <para>If you're using the <link linkend="aio-journal">Asynchronous IO Journal</link> on
             Linux, you need to specify <literal>java.library.path</literal> as a property on your
-            Java options. This is done automatically in the <literal>run.sh</literal> script.</para>
+            Java options. This is done automatically in the scripts.</para>
         <para>If you don't specify <literal>java.library.path</literal> at your Java options then
             the JVM will use the environment variable <literal>LD_LIBRARY_PATH</literal>.</para>
     </section>
@@ -111,20 +97,10 @@
     </section>
     <section id="using-server.configuration">
         <title>Configuration files</title>
-        <para>The configuration directory is specified on the classpath in the run scripts <literal
-                >run.sh</literal> and <literal>run.bat</literal> This directory can contain the
-            following files.</para>
+        <para>The configuration file used to bootstrap the server (e.g. <literal>bootstrap.xml</literal>
+            by default) references the specific broker configuration files.</para>
         <itemizedlist>
             <listitem>
-                <para><literal>hornetq-beans.xml</literal> (or <literal
-                        >hornetq-jboss-beans.xml</literal> if you're running inside JBoss
-                    Application Server). This is the JBoss Microcontainer beans file which defines
-                    what beans the Microcontainer should create and what dependencies to enforce
-                    between them. Remember that HornetQ is just a set of POJOs. In the stand-alone
-                    server, it's the JBoss Microcontainer which instantiates these POJOs and
-                    enforces dependencies between them and other beans. </para>
-            </listitem>
-            <listitem>
                 <para><literal>hornetq-configuration.xml</literal>. This is the main HornetQ
                     configuration file. All the parameters in this file are described in <xref
                         linkend="configuration-index"/>. Please see <xref
@@ -156,11 +132,6 @@
                     file. For more information on using JMS, please see <xref linkend="using-jms"
                     />.</para>
             </listitem>
-            <listitem>
-                <para><literal>logging.properties</literal> This is used to configure the logging
-                    handlers used by the Java logger. For more information on configuring logging,
-                    please see <xref linkend="logging"/>.</para>
-            </listitem>
         </itemizedlist>
         <note>
             <para>The property <literal>file-deployment-enabled</literal> in the <literal
@@ -184,190 +155,43 @@
                 >${hornetq.remoting.netty.host}</literal>, however the system property
                 <emphasis>must</emphasis> be supplied in that case.</para>
     </section>
-    <section id="server.microcontainer.configuration">
-        <title>JBoss Microcontainer Beans File</title>
-        <para>The stand-alone server is basically a set of POJOs which are instantiated by the light
-                weight<ulink url="http://www.jboss.org/jbossmc/"> JBoss Microcontainer
-            </ulink>engine.</para>
-        <note>
-            <para>A beans file is also needed when the server is deployed in the JBoss Application
-                Server but this will deploy a slightly different set of objects since the
-                Application Server will already have things like security etc deployed.</para>
-        </note>
-        <para>Let's take a look at an example beans file from the stand-alone server:</para>
+    <section id="server.bootstrap.configuration">
+        <title>Bootstrap File</title>
+        <para>The stand-alone server is basically a set of POJOs which are instantiated by Airline commands.</para>
+        <para>The bootstrap file is very simple.  Let's take a look at an example:</para>
         <para>
             <programlisting>
-&lt;?xml version="1.0" encoding="UTF-8"?>
-
-&lt;deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   &lt;!-- MBean server -->
-   &lt;bean name="MBeanServer" class="javax.management.MBeanServer">
-      &lt;constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   &lt;/bean>
-
-   &lt;!-- The core configuration -->
-   &lt;bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   &lt;/bean>
-
-    &lt;!-- The security manager -->
-   &lt;bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      &lt;start ignored="true"/>
-      &lt;stop ignored="true"/>
-   &lt;/bean>
+&lt;broker xmlns="http://hornetq.org/schema">
 
-    &lt;!-- The core server -->
-   &lt;bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      &lt;constructor>
-         &lt;parameter>
-            &lt;inject bean="Configuration"/>
-         &lt;/parameter>
-         &lt;parameter>
-            &lt;inject bean="MBeanServer"/>
-         &lt;/parameter>
-         &lt;parameter>
-            &lt;inject bean="HornetQSecurityManager"/>
-         &lt;/parameter>
-      &lt;/constructor>
-      &lt;start ignored="true"/>
-      &lt;stop ignored="true"/>
-   &lt;/bean>
+   &lt;file:core configuration="${hornetq.home}/config/stand-alone/non-clustered/hornetq-configuration.xml">&lt;/core>
+   &lt;file:jms configuration="${hornetq.home}/config/stand-alone/non-clustered/hornetq-jms.xml">&lt;/jms>
 
-    &lt;!-- The Stand alone server that controls the jndi server-->
-   &lt;bean name="StandaloneServer" class="org.hornetq.jms.server.impl.StandaloneNamingServer">
-      &lt;constructor>
-         &lt;parameter>
-            &lt;inject bean="HornetQServer"/>
-         &lt;/parameter>
-      &lt;/constructor>
-      &lt;property name="port">${jnp.port:1099}&lt;/property>
-      &lt;property name="bindAddress">${jnp.host:localhost}&lt;/property>
-      &lt;property name="rmiPort">${jnp.rmiPort:1098}&lt;/property>
-      &lt;property name="rmiBindAddress">${jnp.host:localhost}&lt;/property>
-   &lt;/bean>
+   &lt;basic-security/>
 
-   &lt;!-- The JMS server -->
-   &lt;bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      &lt;constructor>
-         &lt;parameter>
-            &lt;inject bean="HornetQServer"/>
-         &lt;/parameter>
-      &lt;/constructor>
-   &lt;/bean>
+   &lt;naming bindAddress="localhost" port="1099" rmiBindAddress="localhost" rmiPort="1098"/>
 
-
-&lt;/deployment></programlisting>
+&lt;/broker></programlisting>
         </para>
-        <para>We can see that, as well as the core HornetQ server, the stand-alone server
-            instantiates various different POJOs, let's look at them in turn:</para>
         <itemizedlist>
             <listitem>
-                <para>MBeanServer</para>
-                <para>In order to provide a JMX management interface a JMS MBean server is necessary
-                    in which to register the management objects. Normally this is just the default
-                    platform MBean server available in the JVM instance. If you don't want to
-                    provide a JMX management interface this can be commented out or removed.</para>
-            </listitem>
-            <listitem>
-                <para>Configuration</para>
-                <para>The HornetQ server is configured with a Configuration object. In the default
-                    stand-alone set-up it uses a FileConfiguration object which knows to read
-                    configuration information from the file system. In different configurations such
-                    as embedded you might want to provide configuration information from somewhere
-                    else.</para>
-            </listitem>
-            <listitem>
-                <para>Security Manager. The security manager used by the messaging server is
-                    pluggable. The default one used just reads user-role information from the
-                        <literal>hornetq-users.xml</literal> file on disk. However it can be
-                    replaced by a JAAS security manager, or when running inside JBoss Application
-                    Server it can be configured to use the JBoss AS security manager for tight
-                    integration with JBoss AS security. If you've disabled security altogether you
-                    can remove this too.</para>
+                <para>core</para>
+                <para>Instantiates a core server using the configuration file from the
+                   <literal>configuration</literal> attribute. This is the main broker POJO necessary
+                   to do all the real messaging work.</para>
             </listitem>
-            <listitem>
-                <para>HornetQServer</para>
-                <para>This is the core server. It's where 99% of the magic happens</para>
-            </listitem>
-            <listitem>
-                <para>StandaloneServer</para>
-                <para>Many clients like to look up JMS Objects from JNDI so we provide a JNDI server
-                    for them to do that. This class is a wrapper around the JBoss naming server.
-                   If you don't need JNDI this can be commented out or removed.</para>
-            </listitem>
-            <listitem id="bean-jmsservermanager">
-                <para>JMSServerManager</para>
+            <listitem id="jms">
+                <para>jms</para>
                 <para>This deploys any JMS Objects such as JMS Queues, Topics and ConnectionFactory
-                    instances from <literal>hornetq-jms.xml</literal> files on the disk. It also
+                    instances from the <literal>hornetq-jms.xml</literal> file specified. It also
                     provides a simple management API for manipulating JMS Objects. On the whole it
                     just translates and delegates its work to the core server. If you don't need to
-                    deploy JMS Queues, Topics and ConnectionFactorys from server side configuration
+                    deploy JMS Queues, Topics and ConnectionFactories from server side configuration
                     and don't require the JMS management interface this can be disabled.</para>
             </listitem>
-        </itemizedlist>
-    </section>
-    <section id="server.microkernel.configuration">
-        <title>JBoss AS4 MBean Service.</title>
-        <note>
-            <para>The section is only to configure HornetQ on JBoss AS4. The service functionality is
-                similar to Microcontainer Beans</para>
-        </note>
-        <para>
-            <programlisting>
-&lt;?xml version="1.0" encoding="UTF-8"?>
-&lt;server>
-   &lt;mbean code="org.hornetq.service.HornetQFileConfigurationService"
-      name="org.hornetq:service=HornetQFileConfigurationService">
-   &lt;/mbean>
-
-   &lt;mbean code="org.hornetq.service.JBossASSecurityManagerService"
-      name="org.hornetq:service=JBossASSecurityManagerService">
-   &lt;/mbean>
-
-   &lt;mbean code="org.hornetq.service.HornetQStarterService" 
-      name="org.hornetq:service=HornetQStarterService">
-      &lt;!--let's let the JMS Server start us-->
-         &lt;attribute name="Start">false&lt;/attribute>
-
-      &lt;depends optional-attribute-name="SecurityManagerService"
-         proxy-type="attribute">org.hornetq:service=JBossASSecurityManagerService&lt;/depends>
-      &lt;depends optional-attribute-name="ConfigurationService"
-         proxy-type="attribute">org.hornetq:service=HornetQFileConfigurationService&lt;/depends>
-   &lt;/mbean>
-
-   &lt;mbean code="org.hornetq.service.HornetQJMSStarterService"
-      name="org.hornetq:service=HornetQJMSStarterService">
-      &lt;depends optional-attribute-name="HornetQServer"
-         proxy-type="attribute">org.hornetq:service=HornetQStarterService&lt;/depends>
-   &lt;/mbean>
-&lt;/server></programlisting>
-        </para>
-        <para>This jboss-service.xml configuration file is included inside the hornetq-service.sar
-            on AS4 with embedded HornetQ. As you can see, on this configuration file we are starting
-            various services:</para>
-        <itemizedlist>
-            <listitem>
-                <para>HornetQFileConfigurationService</para>
-                <para>This is an MBean Service that takes care of the life cycle of the <literal>FileConfiguration POJO</literal></para>
-            </listitem>
-            <listitem>
-                <para>JBossASSecurityManagerService</para>
-                <para>This is an MBean Service that takes care of the lifecycle of the <literal>JBossASSecurityManager</literal> POJO</para>
-            </listitem>
-            <listitem>
-                <para>HornetQStarterService</para>
-                <para>This is an MBean Service that controls the main <literal>HornetQServer</literal> POJO.
-                   this has a dependency on JBossASSecurityManagerService and HornetQFileConfigurationService MBeans</para>
-            </listitem>
-            <listitem>
-                <para>HornetQJMSStarterService</para>
-                <para>This is an MBean Service that controls the <literal>JMSServerManagerImpl</literal> POJO.
-                   If you aren't using jms this can be removed.</para>
-            </listitem>
             <listitem>
-                <para>JMSServerManager</para>
-                <para>Has the responsibility to start the JMSServerManager and the same behaviour that JMSServerManager Bean</para>
+                <para>naming</para>
+                <para>Instantiates a naming server which implements JNDI. This is used by JMS
+                    clients</para>
             </listitem>
         </itemizedlist>
     </section>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/user-manual.xpr
----------------------------------------------------------------------
diff --git a/docs/user-manual/user-manual.xpr b/docs/user-manual/user-manual.xpr
index 2f3e5dd..fc5025a 100644
--- a/docs/user-manual/user-manual.xpr
+++ b/docs/user-manual/user-manual.xpr
@@ -21,6 +21,7 @@
             <file name="en/configuration-index.xml"/>
             <file name="en/configuring-transports.xml"/>
             <file name="en/connection-ttl.xml"/>
+            <file name="en/slow-consumers.xml"/>
             <file name="en/core-bridges.xml"/>
             <file name="en/diverts.xml"/>
             <file name="en/duplicate-detection.xml"/>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/etc/checkstyle.xml
----------------------------------------------------------------------
diff --git a/etc/checkstyle.xml b/etc/checkstyle.xml
index 7a420f4..3f8da10 100644
--- a/etc/checkstyle.xml
+++ b/etc/checkstyle.xml
@@ -71,5 +71,16 @@
          <property name="caseIndent" value="3"/>
          <property name="throwsIndent" value="3"/>
       </module>
+
+       <module name="IllegalImport">
+           <property name="illegalPkgs" value="junit.framework"/>
+       </module>
+
+      <!-- developed at https://github.com/hornetq/hornetq-checkstyle-checks -->
+      <module name="org.hornetq.checks.annotation.RequiredAnnotation">
+         <property name="annotationName" value="Parameters"/>
+         <property name="requiredParameters" value="name"/>
+      </module>
+
    </module>
 </module>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/microcontainer/pom.xml
----------------------------------------------------------------------
diff --git a/examples/core/microcontainer/pom.xml b/examples/core/microcontainer/pom.xml
deleted file mode 100644
index f3d92f5..0000000
--- a/examples/core/microcontainer/pom.xml
+++ /dev/null
@@ -1,84 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <modelVersion>4.0.0</modelVersion>
-
-   <parent>
-      <groupId>org.hornetq.examples.core</groupId>
-      <artifactId>core-examples</artifactId>
-      <version>2.5.0-SNAPSHOT</version>
-   </parent>
-
-   <artifactId>hornetq-core-microcontainer-example</artifactId>
-   <packaging>jar</packaging>
-   <name>HornetQ Core Microcontainer Example</name>
-
-   <dependencies>
-      <dependency>
-         <groupId>org.hornetq</groupId>
-         <artifactId>hornetq-bootstrap</artifactId>
-         <version>${project.version}</version>
-      </dependency>
-      <dependency>
-         <groupId>org.hornetq</groupId>
-         <artifactId>hornetq-server</artifactId>
-         <version>${project.version}</version>
-      </dependency>
-      <dependency>
-         <groupId>org.hornetq</groupId>
-         <artifactId>hornetq-core-client</artifactId>
-         <version>${project.version}</version>
-      </dependency>
-      <dependency>
-         <groupId>org.hornetq</groupId>
-         <artifactId>hornetq-commons</artifactId>
-         <version>${project.version}</version>
-      </dependency>
-      <dependency>
-         <groupId>io.netty</groupId>
-         <artifactId>netty-all</artifactId>
-         <version>${netty.version}</version>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.javaee</groupId>
-         <artifactId>jboss-jms-api</artifactId>
-         <version>1.1.0.GA</version>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.naming</groupId>
-         <artifactId>jnp-client</artifactId>
-         <version>5.0.5.Final</version>
-      </dependency>
-      <dependency>
-         <groupId>org.jboss.spec.javax.jms</groupId>
-         <artifactId>jboss-jms-api_2.0_spec</artifactId>
-      </dependency>
-   </dependencies>
-
-   <profiles>
-      <profile>
-         <id>example</id>
-         <build>
-            <plugins>
-               <plugin>
-                  <groupId>org.codehaus.mojo</groupId>
-                  <artifactId>exec-maven-plugin</artifactId>
-                  <version>1.1</version>
-                  <executions>
-                     <execution>
-                        <phase>package</phase>
-                        <goals>
-                           <goal>java</goal>
-                        </goals>
-                     </execution>
-                  </executions>
-                  <configuration>
-                     <mainClass>org.hornetq.core.example.EmbeddedMicroContainerExample</mainClass>
-                  </configuration>
-               </plugin>
-            </plugins>
-         </build>
-      </profile>
-   </profiles>
-
-
-</project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/microcontainer/readme.html
----------------------------------------------------------------------
diff --git a/examples/core/microcontainer/readme.html b/examples/core/microcontainer/readme.html
deleted file mode 100644
index 40d2832..0000000
--- a/examples/core/microcontainer/readme.html
+++ /dev/null
@@ -1,82 +0,0 @@
-<html>
-  <head>
-    <title>HornetQ Embedded Example</title>
-    <link rel="stylesheet" type="text/css" href="../../common/common.css" />
-    <link rel="stylesheet" type="text/css" href="../../common/prettify.css" />
-    <script type="text/javascript" src="../../common/prettify.js"></script>
-  </head>
-  <body onload="prettyPrint()">
-     <h1>Micro Container Example</h1>
-
-     <p>This examples shows how to setup and run HornetQ through the Micro Container.</p>
-     <p>Refer to the user's manual for the list of required Jars, since JBoss Micro Container requires a few jars.</p>
-     <h2>Example step-by-step</h2>     
-     <p><i>To run the example, simply type <code>mvn verify</code> from this directory</i></p>
-     <p>In this we don't use any configuration files. (Everything is embedded). We simply instantiate ConfigurationImpl, HornetQServer, start it and operate on JMS regularly</p>
-
-     <ol>
-     
-        <li>Start the server</li>
-        <pre class="prettyprint">
-           hornetq = new HornetQBootstrapServer("./server0/hornetq-beans.xml");
-           hornetq.run();
-        </pre>
-     
-        <li>As we are not using a JNDI environment we instantiate the objects directly</li>
-        <pre class="prettyprint">
-           ServerLocator serverLocator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName()));
-           ClientSessionFactory sf = serverLocator.createSessionFactory();
-        </pre>
-
-        <li>Create a Core Queue</li>
-        <pre class="prettyprint">
-           ClientSession coreSession = sf.createSession(false, false, false);
-           final String queueName = "queue.exampleQueue";
-           coreSession.createQueue(queueName, queueName, true);
-           coreSession.close();
-        </pre>
-
-        <li>Create the session and producer</li>
-        <pre class="prettyprint">
-           session = sf.createSession();
-                                   
-           ClientProducer producer = session.createProducer(queueName);
-        </pre>
-
-        <li>Create and send a Message</li>
-        <pre class="prettyprint">
-           ClientMessage message = session.createMessage(false);
-           message.putStringProperty(propName, "Hello sent at " + new Date());
-           System.out.println("Sending the message.");
-           producer.send(message);
-        </pre>
-
-        <li>Create the message consumer and start the connection</li>
-        <pre class="prettyprint">
-           ClientConsumer messageConsumer = session.createConsumer(queueName);
-           session.start();
-        </pre>
-
-        <li>Receive the message</li>
-        <pre class="prettyprint">
-           ClientMessage messageReceived = messageConsumer.receive(1000);
-           System.out.println("Received TextMessage:" + messageReceived.getProperty(propName));
-         </pre>
-
-        <li>Be sure to close our resources!</li>
-
-        <pre class="prettyprint">
-           if (sf != null)
-           {
-              sf.close();
-           }
-        </pre>
-
-        <li>Stop the server</li>
-
-        <pre class="prettyprint">
-           hornetq.shutdown();
-        </pre>
-     </ol>
-  </body>
-</html>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/microcontainer/src/main/java/org/hornetq/core/example/EmbeddedMicroContainerExample.java
----------------------------------------------------------------------
diff --git a/examples/core/microcontainer/src/main/java/org/hornetq/core/example/EmbeddedMicroContainerExample.java b/examples/core/microcontainer/src/main/java/org/hornetq/core/example/EmbeddedMicroContainerExample.java
deleted file mode 100644
index ac5ace4..0000000
--- a/examples/core/microcontainer/src/main/java/org/hornetq/core/example/EmbeddedMicroContainerExample.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.core.example;
-
-import java.util.Date;
-
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.*;
-import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory;
-import org.hornetq.integration.bootstrap.HornetQBootstrapServer;
-
-/**
- *
- * This example shows how to run a HornetQ core client and server embedded in your
- * own application
- *
- * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
- *
- */
-public class EmbeddedMicroContainerExample
-{
-
-   public static void main(final String[] args) throws Exception
-   {
-
-      HornetQBootstrapServer hornetQ = null;
-      try
-      {
-
-         // Step 1. Start the server
-         hornetQ = new HornetQBootstrapServer("hornetq-beans.xml");
-         hornetQ.run();
-
-         // Step 2. As we are not using a JNDI environment we instantiate the objects directly
-         ServerLocator serverLocator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName()));
-         ClientSessionFactory sf = serverLocator.createSessionFactory();
-
-         // Step 3. Create a core queue
-         ClientSession coreSession = sf.createSession(false, false, false);
-
-         final String queueName = "queue.exampleQueue";
-
-         coreSession.createQueue(queueName, queueName, true);
-
-         coreSession.close();
-
-         ClientSession session = null;
-
-         try
-         {
-
-            // Step 4. Create the session, and producer
-            session = sf.createSession();
-
-            ClientProducer producer = session.createProducer(queueName);
-
-            // Step 5. Create and send a message
-            ClientMessage message = session.createMessage(false);
-
-            final String propName = "myprop";
-
-            message.putStringProperty(propName, "Hello sent at " + new Date());
-
-            System.out.println("Sending the message.");
-
-            producer.send(message);
-
-            // Step 6. Create the message consumer and start the connection
-            ClientConsumer messageConsumer = session.createConsumer(queueName);
-            session.start();
-
-            // Step 7. Receive the message.
-            ClientMessage messageReceived = messageConsumer.receive(1000);
-
-            System.out.println("Received TextMessage:" + messageReceived.getStringProperty(propName));
-         }
-         finally
-         {
-            // Step 8. Be sure to close our resources!
-            if (sf != null)
-            {
-               sf.close();
-            }
-
-            // Step 9. Shutdown the container
-            if (hornetQ != null)
-            {
-               hornetQ.shutDown();
-            }
-         }
-      }
-      catch (Exception e)
-      {
-         e.printStackTrace();
-         throw e;
-      }
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/microcontainer/src/main/resources/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/core/microcontainer/src/main/resources/hornetq-beans.xml b/examples/core/microcontainer/src/main/resources/hornetq-beans.xml
deleted file mode 100644
index b68c7ae..0000000
--- a/examples/core/microcontainer/src/main/resources/hornetq-beans.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-    <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean>
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/microcontainer/src/main/resources/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/core/microcontainer/src/main/resources/hornetq-configuration.xml b/examples/core/microcontainer/src/main/resources/hornetq-configuration.xml
deleted file mode 100644
index 766b4b1..0000000
--- a/examples/core/microcontainer/src/main/resources/hornetq-configuration.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-
-
-
-   <bindings-directory>target/data/messaging/bindings</bindings-directory>
-
-   <journal-directory>target/data/messaging/journal</journal-directory>
-
-   <large-messages-directory>target/data/messaging/largemessages</large-messages-directory>
-
-   <paging-directory>target/data/messaging/paging</paging-directory>
-
-   <!-- Acceptors -->
-   <acceptors>
-      <acceptor name="netty-acceptor">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>    
-         <param key="tcp-no-delay" value="false"/>
-         <param key="tcp-send-buffer-size" value="1048576"/>
-         <param key="tcp-receive-buffer-size" value="1048576"/>
-      </acceptor>
-   </acceptors>
-   
-   <security-enabled>false</security-enabled>
-   
-   <persistence-enabled>false</persistence-enabled>
- 
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/perf/src/main/resources/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/core/perf/src/main/resources/server0/hornetq-beans.xml b/examples/core/perf/src/main/resources/server0/hornetq-beans.xml
deleted file mode 100644
index 1ab8e95..0000000
--- a/examples/core/perf/src/main/resources/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-      
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>   
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>         
-      </constructor>
-   </bean>
-   
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/twitter-connector/src/main/resources/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/core/twitter-connector/src/main/resources/server0/hornetq-beans.xml b/examples/core/twitter-connector/src/main/resources/server0/hornetq-beans.xml
deleted file mode 100644
index 171d373..0000000
--- a/examples/core/twitter-connector/src/main/resources/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/vertx-connector/pom.xml
----------------------------------------------------------------------
diff --git a/examples/core/vertx-connector/pom.xml b/examples/core/vertx-connector/pom.xml
index a2cc7f3..4c0fef3 100644
--- a/examples/core/vertx-connector/pom.xml
+++ b/examples/core/vertx-connector/pom.xml
@@ -13,7 +13,7 @@
    <name>HornetQ Vert.x Example</name>
 
    <properties>
-      <vertx.version>2.1RC1</vertx.version>
+      <vertx.version>2.1.2</vertx.version>
    </properties>
    <dependencies>
       <dependency>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/core/vertx-connector/src/main/resources/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/core/vertx-connector/src/main/resources/server0/hornetq-beans.xml b/examples/core/vertx-connector/src/main/resources/server0/hornetq-beans.xml
deleted file mode 100644
index 171d373..0000000
--- a/examples/core/vertx-connector/src/main/resources/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/javaee/jca-remote/src/test/resources/arquillian.xml
----------------------------------------------------------------------
diff --git a/examples/javaee/jca-remote/src/test/resources/arquillian.xml b/examples/javaee/jca-remote/src/test/resources/arquillian.xml
index f1338ea..4fbd8f2 100644
--- a/examples/javaee/jca-remote/src/test/resources/arquillian.xml
+++ b/examples/javaee/jca-remote/src/test/resources/arquillian.xml
@@ -44,4 +44,4 @@ This feature can also be controlled using the system property arquillian.deploym
 </container>
 -->
 
-</arquillian>
\ No newline at end of file
+</arquillian>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server0/hornetq-configuration.xml
index f923f5e..c670e1f 100644
--- a/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <master/>
+      </shared-store>
+   </ha-policy>
 
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 7d61f04..7c2bad8 100644
--- a/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/client-side-failoverlistener/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -10,7 +10,11 @@
 
    <paging-directory>${build.directory}/server0/data/messaging/paging</paging-directory>
 
-   <ha-policy template="BACKUP_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <slave/>
+      </shared-store>
+   </ha-policy>
 
    <!-- Connectors -->
    <connectors>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/clustered-grouping/src/main/java/org/hornetq/jms/example/ClusteredGroupingExample.java
----------------------------------------------------------------------
diff --git a/examples/jms/clustered-grouping/src/main/java/org/hornetq/jms/example/ClusteredGroupingExample.java b/examples/jms/clustered-grouping/src/main/java/org/hornetq/jms/example/ClusteredGroupingExample.java
index 6901227..0e8b263 100644
--- a/examples/jms/clustered-grouping/src/main/java/org/hornetq/jms/example/ClusteredGroupingExample.java
+++ b/examples/jms/clustered-grouping/src/main/java/org/hornetq/jms/example/ClusteredGroupingExample.java
@@ -80,37 +80,37 @@ public class ClusteredGroupingExample extends HornetQExample
          // Step 7. We create a JMS Connection connection1 which is a connection to server 1
          connection1 = cf1.createConnection();
 
-         // Step 7. We create a JMS Connection connection1 which is a connection to server 1
+         // Step 8. We create a JMS Connection connection2 which is a connection to server 2
          connection2 = cf2.createConnection();
 
-         // Step 8. We create a JMS Session on server 0
+         // Step 9. We create a JMS Session on server 0
          Session session0 = connection0.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-         // Step 9. We create a JMS Session on server 1
+         // Step 10. We create a JMS Session on server 1
          Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-         // Step 10. We create a JMS Session on server 1
+         // Step 11. We create a JMS Session on server 1
          Session session2 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-         // Step 11. We start the connections to ensure delivery occurs on them
+         // Step 12. We start the connections to ensure delivery occurs on them
          connection0.start();
 
          connection1.start();
 
          connection2.start();
 
-         // Step 12. We create JMS MessageConsumer objects on server 0
+         // Step 13. We create JMS MessageConsumer objects on server 0
          MessageConsumer consumer = session0.createConsumer(queue);
 
 
-         // Step 13. We create a JMS MessageProducer object on server 0, 1 and 2
+         // Step 14. We create a JMS MessageProducer object on server 0, 1 and 2
          MessageProducer producer0 = session0.createProducer(queue);
 
          MessageProducer producer1 = session1.createProducer(queue);
 
          MessageProducer producer2 = session2.createProducer(queue);
 
-         // Step 14. We send some messages to server 0, 1 and 2 with the same groupid set
+         // Step 15. We send some messages to server 0, 1 and 2 with the same groupid set
 
          final int numMessages = 10;
 
@@ -148,7 +148,7 @@ public class ClusteredGroupingExample extends HornetQExample
             System.out.println("Sent messages: " + message.getText() + " to node 2");
          }
 
-         // Step 15. We now consume those messages from server 0
+         // Step 16. We now consume those messages from server 0
          // We note the messages have all been sent to the same consumer on the same node
 
          for (int i = 0; i < numMessages * 3; i++)
@@ -163,7 +163,7 @@ public class ClusteredGroupingExample extends HornetQExample
       }
       finally
       {
-         // Step 16. Be sure to close our resources!
+         // Step 17. Be sure to close our resources!
 
          if (connection0 != null)
          {
@@ -197,4 +197,4 @@ public class ClusteredGroupingExample extends HornetQExample
       }
    }
 
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/clustered-jgroups/src/main/resources/hornetq/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/clustered-jgroups/src/main/resources/hornetq/server0/hornetq-beans.xml b/examples/jms/clustered-jgroups/src/main/resources/hornetq/server0/hornetq-beans.xml
deleted file mode 100644
index 61c04e6..0000000
--- a/examples/jms/clustered-jgroups/src/main/resources/hornetq/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-	<!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/clustered-jgroups/src/main/resources/hornetq/server1/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/clustered-jgroups/src/main/resources/hornetq/server1/hornetq-beans.xml b/examples/jms/clustered-jgroups/src/main/resources/hornetq/server1/hornetq-beans.xml
deleted file mode 100644
index e5fe1e0..0000000
--- a/examples/jms/clustered-jgroups/src/main/resources/hornetq/server1/hornetq-beans.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">2099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">2098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-	<!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/colocated-failover-scale-down/pom.xml
----------------------------------------------------------------------
diff --git a/examples/jms/colocated-failover-scale-down/pom.xml b/examples/jms/colocated-failover-scale-down/pom.xml
index 5faf069..25d1167 100644
--- a/examples/jms/colocated-failover-scale-down/pom.xml
+++ b/examples/jms/colocated-failover-scale-down/pom.xml
@@ -104,7 +104,7 @@
             <dependencies>
                <dependency>
                   <groupId>org.hornetq.examples.jms</groupId>
-                  <artifactId>colocated-failover-recover-only</artifactId>
+                  <artifactId>colocated-failover-scale-down</artifactId>
                   <version>${project.version}</version>
                </dependency>
                <dependency>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/colocated-failover-scale-down/readme.html
----------------------------------------------------------------------
diff --git a/examples/jms/colocated-failover-scale-down/readme.html b/examples/jms/colocated-failover-scale-down/readme.html
index f5e3909..a731a15 100644
--- a/examples/jms/colocated-failover-scale-down/readme.html
+++ b/examples/jms/colocated-failover-scale-down/readme.html
@@ -12,19 +12,31 @@
          HA Policy that is colocated. colocated means that backup servers can be created and maintained by live servers on behalf
          of other requesting live servers. In this example we create a colocated shared store server that will scale down.
          That is it will not become live but scale down the journal to the colocated live server.
-     <p>This example starts 2 live servers each with a backup server that backs up the other live server.</p>
+     <p>This example starts 2 live servers each will request the other to create a backup.</p>
      <p>The first live server will be killed and the backup in the second will recover the journal and recreate its state
          in the live server it shares its VM with.</p>
-     <p>The following shows how to configure the backup, the backup strategy is set to <b>SCALE_DOWN</b> which means
+     <p>The following shows how to configure the backup, the slave is configured <b>&lt;scale-down/></b> which means
          that the backup server will not fully start on fail over, instead it will just recover the journal and write it
-     to its parent live server. Also notice we have over ridden some of the configuration since we want it to use the same
-     journal as server1 since it is using shared store.</p>
+     to its parent live server.</p>
      <pre class="prettyprint">
-     <code>&lt;ha-policy template="COLOCATED_SHARED_STORE"/>
+     <code>&lt;ha-policy>
+         &lt;shared-store>
+             &lt;colocated>
+                 &lt;backup-port-offset>100&lt;/backup-port-offset>
+                 &lt;backup-request-retries>-1&lt;/backup-request-retries>
+                 &lt;backup-request-retry-interval>2000&lt;/backup-request-retry-interval>
+                 &lt;max-backups>1&lt;/max-backups>
+                 &lt;request-backup>true&lt;/request-backup>
+                 &lt;master/>
+                 &lt;slave>
+                     &lt;scale-down/>
+                 &lt;/slave>
+             &lt;/colocated>
+         &lt;/shared-store>
+     &lt;/ha-policy>
      </code>
      </pre>
-     <p>note that for this HA policy we use a template that will use some sensibe settings, in this case this includes
-     setting scale down to true. Also note that since we dont specify a scale down connector it will use most appropriate
+     <p>Notice that we dont need to specify a scale down connector as it will use most appropriate
      from the list of available connectors which in  this case is the first INVM connector</p>
      <p> One other thing to notice is that the cluster connection has its reconnect attempts set to 5, this is so it will
          disconnect instead of trying to reconnect to a backup that doesn't exist.</p>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 5563ffe..a4a139a 100644
--- a/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -66,7 +66,21 @@
    </cluster-connections>
 
    <!-- a colocated server that will allow shared store backups to be requested, the default for this template is to scale down-->
-   <ha-policy template="COLOCATED_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <colocated>
+            <backup-port-offset>100</backup-port-offset>
+            <backup-request-retries>-1</backup-request-retries>
+            <backup-request-retry-interval>2000</backup-request-retry-interval>
+            <max-backups>1</max-backups>
+            <request-backup>true</request-backup>
+            <master/>
+            <slave>
+               <scale-down/>
+            </slave>
+         </colocated>
+      </shared-store>
+   </ha-policy>
 
    <!-- Other config -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 2da9ca8..298f123 100644
--- a/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/colocated-failover-scale-down/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -67,7 +67,21 @@
    </cluster-connections>
 
    <!-- a colocated server that will allow shared store backups to be requested, the default for this template is to scale down-->
-   <ha-policy template="COLOCATED_SHARED_STORE"/>
+   <ha-policy>
+      <shared-store>
+         <colocated>
+            <backup-port-offset>100</backup-port-offset>
+            <backup-request-retries>-1</backup-request-retries>
+            <backup-request-retry-interval>2000</backup-request-retry-interval>
+            <max-backups>1</max-backups>
+            <request-backup>true</request-backup>
+            <master/>
+            <slave>
+               <scale-down/>
+            </slave>
+         </colocated>
+      </shared-store>
+   </ha-policy>
    
    <!-- Other config -->
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/colocated-failover/readme.html
----------------------------------------------------------------------
diff --git a/examples/jms/colocated-failover/readme.html b/examples/jms/colocated-failover/readme.html
index ac680f6..64665f4 100644
--- a/examples/jms/colocated-failover/readme.html
+++ b/examples/jms/colocated-failover/readme.html
@@ -15,9 +15,19 @@
      <p>The first live server will be killed and the backup in the second will become live</p>
      <p>The following shows how to configure the live servers to request and allow backups to be deployed</p>
      <pre class="prettyprint">
-     <code>&lt;ha-policy template="COLOCATED_SHARED_STORE">
-         &ltbackup-strategy>FULL&lt/backup-strategy>
-         &lt/ha-policy>
+     <code>&lt;ha-policy>
+         &lt;shared-store>
+             &lt;colocated>
+                 &lt;backup-port-offset>100&lt;/backup-port-offset>
+                 &lt;backup-request-retries>-1&lt;/backup-request-retries>
+                 &lt;backup-request-retry-interval>2000&lt;/backup-request-retry-interval>
+                 &lt;max-backups>1&lt;/max-backups>
+                 &lt;request-backup>true&lt;/request-backup>
+                 &lt;master/>
+                 &lt;slave/>
+             &lt;/colocated>
+         &lt;/shared-store>
+     &lt;/ha-policy>
      </code>
      </pre>
      <p>notice that we have used a template to set some sensible defaults but overridden the backup strategy so back ups

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/colocated-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/colocated-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/colocated-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 1a6e606..244a78e 100644
--- a/examples/jms/colocated-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/colocated-failover/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -58,8 +58,18 @@
    </cluster-connections>
 
    <!-- a colocated server that will allow shared store full backups to be requested-->
-   <ha-policy template="COLOCATED_SHARED_STORE">
-      <backup-strategy>FULL</backup-strategy>
+   <ha-policy>
+      <shared-store>
+         <colocated>
+            <backup-port-offset>100</backup-port-offset>
+            <backup-request-retries>-1</backup-request-retries>
+            <backup-request-retry-interval>2000</backup-request-retry-interval>
+            <max-backups>1</max-backups>
+            <request-backup>true</request-backup>
+            <master/>
+            <slave/>
+         </colocated>
+      </shared-store>
    </ha-policy>
    
    <!-- Other config -->

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/colocated-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/colocated-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/colocated-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
index c301c46..d4ff70d 100644
--- a/examples/jms/colocated-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/colocated-failover/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -59,8 +59,18 @@
    </cluster-connections>
 
    <!-- a colocated server that will allow shared store full backups to be requested-->
-   <ha-policy template="COLOCATED_SHARED_STORE">
-      <backup-strategy>FULL</backup-strategy>
+   <ha-policy>
+      <shared-store>
+         <colocated>
+            <backup-port-offset>100</backup-port-offset>
+            <backup-request-retries>-1</backup-request-retries>
+            <backup-request-retry-interval>2000</backup-request-retry-interval>
+            <max-backups>1</max-backups>
+            <request-backup>true</request-backup>
+            <master/>
+            <slave/>
+         </colocated>
+      </shared-store>
    </ha-policy>
    
    <!-- Other config -->

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/consumer-rate-limit/src/main/resources/hornetq/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/consumer-rate-limit/src/main/resources/hornetq/server0/hornetq-beans.xml b/examples/jms/consumer-rate-limit/src/main/resources/hornetq/server0/hornetq-beans.xml
deleted file mode 100644
index 171d373..0000000
--- a/examples/jms/consumer-rate-limit/src/main/resources/hornetq/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-   <!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/dead-letter/src/main/resources/hornetq/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/dead-letter/src/main/resources/hornetq/server0/hornetq-beans.xml b/examples/jms/dead-letter/src/main/resources/hornetq/server0/hornetq-beans.xml
deleted file mode 100644
index cfb2d3e..0000000
--- a/examples/jms/dead-letter/src/main/resources/hornetq/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>        
-      </constructor>
-   </bean>
-
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/delayed-redelivery/src/main/resources/hornetq/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/delayed-redelivery/src/main/resources/hornetq/server0/hornetq-beans.xml b/examples/jms/delayed-redelivery/src/main/resources/hornetq/server0/hornetq-beans.xml
deleted file mode 100644
index cfb2d3e..0000000
--- a/examples/jms/delayed-redelivery/src/main/resources/hornetq/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>        
-      </constructor>
-   </bean>
-
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/durable-subscription/src/main/resources/hornetq/server0/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/durable-subscription/src/main/resources/hornetq/server0/hornetq-beans.xml b/examples/jms/durable-subscription/src/main/resources/hornetq/server0/hornetq-beans.xml
deleted file mode 100644
index 71274b3..0000000
--- a/examples/jms/durable-subscription/src/main/resources/hornetq/server0/hornetq-beans.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server0/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server0/hornetq-configuration.xml b/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server0/hornetq-configuration.xml
index 6c90184..06b358a 100644
--- a/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server0/hornetq-configuration.xml
+++ b/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server0/hornetq-configuration.xml
@@ -38,16 +38,27 @@
    </acceptors>
    
    <!-- HA configuration -->
-   <ha-policy template="COLOCATED_REPLICATED">
-      <max-backups>1</max-backups>
-      <scale-down-connectors>
-         <connector-ref>invm-connector</connector-ref>
-      </scale-down-connectors>
-      <remote-connectors>
-         <connector-ref>invm-connector</connector-ref>
-         <connector-ref>server1-connector</connector-ref>
-         <connector-ref>netty-connector</connector-ref>
-      </remote-connectors>
+   <ha-policy>
+      <replication>
+         <colocated>
+            <max-backups>1</max-backups>
+            <request-backup>true</request-backup>
+            <backup-request-retry-interval>1000</backup-request-retry-interval>
+            <excludes>
+               <connector-ref>invm-connector</connector-ref>
+               <connector-ref>server1-connector</connector-ref>
+               <connector-ref>netty-connector</connector-ref>
+            </excludes>
+            <master/>
+            <slave>
+               <scale-down>
+                  <connectors>
+                     <connector-ref>invm-connector</connector-ref>
+                  </connectors>
+               </scale-down>
+            </slave>
+         </colocated>
+      </replication>
    </ha-policy>
 
    <cluster-connections>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server1/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server1/hornetq-configuration.xml b/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server1/hornetq-configuration.xml
index 36b3d9d..ffcfa6b 100644
--- a/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server1/hornetq-configuration.xml
+++ b/examples/jms/ha-policy-autobackup/src/main/resources/hornetq/server1/hornetq-configuration.xml
@@ -38,16 +38,27 @@
    </acceptors>
    
    <!-- HA configuration -->
-   <ha-policy template="COLOCATED_REPLICATED">
-      <max-backups>1</max-backups>
-      <scale-down-connectors>
-         <connector-ref>invm-connector</connector-ref>
-      </scale-down-connectors>
-      <remote-connectors>
-         <connector-ref>invm-connector</connector-ref>
-         <connector-ref>server0-connector</connector-ref>
-         <connector-ref>netty-connector</connector-ref>
-      </remote-connectors>
+   <ha-policy>
+      <replication>
+         <colocated>
+            <max-backups>1</max-backups>
+            <request-backup>true</request-backup>
+            <backup-request-retry-interval>1000</backup-request-retry-interval>
+            <excludes>
+               <connector-ref>invm-connector</connector-ref>
+               <connector-ref>server0-connector</connector-ref>
+               <connector-ref>netty-connector</connector-ref>
+            </excludes>
+            <master/>
+            <slave>
+               <scale-down>
+                  <connectors>
+                     <connector-ref>invm-connector</connector-ref>
+                  </connectors>
+               </scale-down>
+            </slave>
+         </colocated>
+      </replication>
    </ha-policy>
 
    <cluster-connections>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/hornetq-jms-examples-common/config/hornetq-example-beans.xml
----------------------------------------------------------------------
diff --git a/examples/jms/hornetq-jms-examples-common/config/hornetq-example-beans.xml b/examples/jms/hornetq-jms-examples-common/config/hornetq-example-beans.xml
deleted file mode 100644
index e70555a..0000000
--- a/examples/jms/hornetq-jms-examples-common/config/hornetq-example-beans.xml
+++ /dev/null
@@ -1,165 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-
-   <bean name="DeploymentManager" class="org.hornetq.core.deployers.impl.FileDeploymentManager">
-      <constructor>
-         <!-- The scan time in milliseconds -->
-         <parameter>5000</parameter>
-      </constructor>
-   </bean>
-   
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
-
-   <!--<bean name="HornetQSecurityManager" class="org.hornetq.core.security.impl.JBossASSecurityManager"/>-->
-
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-   </bean>
-
-   <bean name="BasicSecurityDeployer" class="org.hornetq.core.deployers.impl.BasicUserCredentialsDeployer">
-      <constructor>
-         <parameter>
-            <inject bean="DeploymentManager"/>
-         </parameter>
-      </constructor>
-      <property name="hornetQSecurityManager">
-         <inject bean="HornetQSecurityManager"/>
-      </property>
-   </bean>
-
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <depends>AddressSettingsDeployer</depends>
-      <depends>QueueDeployer</depends>
-      
-      <property name="storageManager">
-         <inject bean="StorageManager"/>
-      </property>
-      <property name="remotingService">
-         <inject bean="RemotingService"/>
-      </property>
-      <property name="configuration">
-         <inject bean="Configuration"/>
-      </property>
-      <property name="securityManager">
-         <inject bean="HornetQSecurityManager"/>
-      </property>
-      <property name="managementService">
-         <inject bean="ManagementService"/>
-      </property>      
-   </bean>
-
-   <bean name="StorageManager" class="org.hornetq.core.persistence.impl.journal.JournalStorageManager">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-   <bean name="RemotingService" class="org.hornetq.core.remoting.server.impl.RemotingServiceImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-      </constructor>
-      <property name="managementService">
-         <inject bean="ManagementService"/>
-      </property>
-   </bean>
-   
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="HornetQServer" property="serverManagement"/>
-         </parameter>
-         <parameter>
-            <inject bean="JMSManagementService"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-   <bean name="JMSServerDeployer" class="org.hornetq.api.jms.server.impl.JMSServerDeployer">
-      <constructor>
-         <parameter>
-            <inject bean="DeploymentManager"/>
-         </parameter>
-          <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-      </constructor>
-      <property name="jmsServerManager">
-         <inject bean="JMSServerManager"/>
-      </property>
-   </bean>
-
-   <bean name="AddressSettingsDeployer" class="org.hornetq.core.deployers.impl.AddressSettingsDeployer">
-      <constructor>
-         <parameter>
-            <inject bean="DeploymentManager"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQServer" property="addressSettingsRepository" state="Configured"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-   <bean name="QueueDeployer" class="org.hornetq.core.deployers.impl.QueueDeployer">
-      <constructor>
-         <parameter>
-            <inject bean="DeploymentManager"/>
-         </parameter>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-      </constructor>
-   </bean>
-   
-   <bean name="SecurityDeployer" class="org.hornetq.core.deployers.impl.SecurityDeployer">
-      <constructor>
-         <parameter>
-            <inject bean="DeploymentManager"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQServer" property="securityRepository"/>
-         </parameter>
-      </constructor>
-   </bean>
-
-   <bean name="ManagementService" class="org.hornetq.core.server.management.impl.ManagementServiceImpl">
-      <constructor>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="Configuration" property="JMXManagementEnabled" />
-         </parameter>
-      </constructor>
-   </bean>
-   
-   <bean name="JMSManagementService" class="org.hornetq.api.jms.server.management.impl.JMSManagementServiceImpl">
-      <constructor>
-         <parameter>
-            <inject bean="ManagementService"/>
-         </parameter>
-      </constructor>
-   </bean>
-   
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-   
-</deployment>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/jms/hornetq-ra-rar/pom.xml
----------------------------------------------------------------------
diff --git a/examples/jms/hornetq-ra-rar/pom.xml b/examples/jms/hornetq-ra-rar/pom.xml
index 3e8077b..82e6249 100644
--- a/examples/jms/hornetq-ra-rar/pom.xml
+++ b/examples/jms/hornetq-ra-rar/pom.xml
@@ -32,7 +32,7 @@
             </exclusion>
             <exclusion>
                <groupId>org.jboss.spec.javax.transaction</groupId>
-               <artifactId>jboss-transaction-api_1.1_spec</artifactId>
+               <artifactId>jboss-transaction-api_1.2_spec</artifactId>
             </exclusion>
             <exclusion>
                <groupId>jboss.jbossts.jts</groupId>


[13/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConcurrentCreateDeleteProduceTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConcurrentCreateDeleteProduceTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConcurrentCreateDeleteProduceTest.java
index c2eed39..5923fc5 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConcurrentCreateDeleteProduceTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConcurrentCreateDeleteProduceTest.java
@@ -58,10 +58,9 @@ public class ConcurrentCreateDeleteProduceTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration config = createDefaultConfig(false);
-
-      config.setJournalSyncNonTransactional(false);
-      config.setJournalSyncTransactional(false);
+      Configuration config = createDefaultConfig(false)
+         .setJournalSyncNonTransactional(false)
+         .setJournalSyncTransactional(false);
 
       server =
          createServer(true, config,

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerCloseTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerCloseTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerCloseTest.java
index 7975279..f3d10db 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerCloseTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerCloseTest.java
@@ -303,9 +303,9 @@ public class ConsumerCloseTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration config = createDefaultConfig();
-      config.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()));
-      config.setSecurityEnabled(false);
+      Configuration config = createDefaultConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()))
+         .setSecurityEnabled(false);
 
       server = addServer(HornetQServers.newHornetQServer(config, false));
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerStuckTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerStuckTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerStuckTest.java
new file mode 100644
index 0000000..e9b1a38
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerStuckTest.java
@@ -0,0 +1,305 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.client;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.ClientConsumer;
+import org.hornetq.api.core.client.ClientMessage;
+import org.hornetq.api.core.client.ClientProducer;
+import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.api.core.client.ClientSessionFactory;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
+import org.hornetq.core.protocol.core.impl.RemotingConnectionImpl;
+import org.hornetq.core.remoting.impl.netty.NettyConnection;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.tests.util.ServiceTestBase;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author <a href="mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
+ */
+public class ConsumerStuckTest extends ServiceTestBase
+{
+   private HornetQServer server;
+
+   private final SimpleString QUEUE = new SimpleString("ConsumerTestQueue");
+
+   protected boolean isNetty()
+   {
+      return true;
+   }
+
+   @Before
+   @Override
+   public void setUp() throws Exception
+   {
+      super.setUp();
+
+      server = createServer(false, isNetty());
+
+      server.start();
+   }
+
+   @Test
+   public void testClientStuckTest() throws Exception
+   {
+
+      ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY));
+      locator.setConnectionTTL(1000);
+      locator.setClientFailureCheckPeriod(100);
+      locator.setConsumerWindowSize(10 * 1024 * 1024);
+      ClientSessionFactory sf = locator.createSessionFactory();
+      ((ClientSessionFactoryImpl) sf).stopPingingAfterOne();
+
+      RemotingConnectionImpl remotingConnection = (RemotingConnectionImpl) sf.getConnection();
+      ClientSession session = sf.createSession(false, true, true, true);
+
+      session.createQueue(QUEUE, QUEUE, null, false);
+
+      ClientProducer producer = session.createProducer(QUEUE);
+
+      final int numMessages = 10000;
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         ClientMessage message = createTextMessage(session, "m" + i);
+         producer.send(message);
+      }
+
+
+      final ClientConsumer consumer = session.createConsumer(QUEUE);
+      session.start();
+
+      final NettyConnection nettyConnection = (NettyConnection) remotingConnection.getTransportConnection();
+
+
+      Thread tReceive = new Thread()
+      {
+         public void run()
+         {
+            boolean first = true;
+            try
+            {
+               while (!Thread.interrupted())
+               {
+                  ClientMessage received = consumer.receive(500);
+                  System.out.println("Received " + received);
+                  if (first)
+                  {
+                     first = false;
+                     nettyConnection.getNettyChannel().config().setAutoRead(false);
+                  }
+                  if (received != null)
+                  {
+                     received.acknowledge();
+                  }
+               }
+            }
+            catch (Throwable e)
+            {
+               Thread.currentThread().interrupt();
+               e.printStackTrace();
+            }
+         }
+      };
+
+      tReceive.start();
+
+      try
+      {
+
+         assertEquals(1, server.getSessions().size());
+
+         System.out.println("sessions = " + server.getSessions().size());
+
+         assertEquals(1, server.getConnectionCount());
+
+         long timeout = System.currentTimeMillis() + 20000;
+
+         while (System.currentTimeMillis() < timeout && server.getSessions().size() != 0)
+         {
+            Thread.sleep(10);
+         }
+
+         System.out.println("Size = " + server.getConnectionCount());
+
+         System.out.println("sessions = " + server.getSessions().size());
+
+
+
+         if (server.getSessions().size() != 0)
+         {
+            System.out.println(threadDump("Thread dump"));
+            fail("The cleanup wasn't able to finish cleaning the session. It's probably stuck, look at the thread dump generated by the test for more information");
+         }
+
+
+         timeout = System.currentTimeMillis() + 20000;
+
+         while (System.currentTimeMillis() < timeout && server.getConnectionCount() != 0)
+         {
+            Thread.sleep(10);
+         }
+
+         assertEquals(0, server.getConnectionCount());
+      }
+      finally
+      {
+         nettyConnection.getNettyChannel().config().setAutoRead(true);
+         tReceive.interrupt();
+         tReceive.join();
+      }
+   }
+
+   @Test
+   public void testClientStuckTestWithDirectDelivery() throws Exception
+   {
+
+      ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY));
+      locator.setConnectionTTL(1000);
+      locator.setClientFailureCheckPeriod(100);
+      locator.setConsumerWindowSize(10 * 1024 * 1024);
+      ClientSessionFactory sf = locator.createSessionFactory();
+      ((ClientSessionFactoryImpl) sf).stopPingingAfterOne();
+
+      RemotingConnectionImpl remotingConnection = (RemotingConnectionImpl) sf.getConnection();
+      ClientSession session = sf.createSession(false, true, true, true);
+
+      session.createQueue(QUEUE, QUEUE, null, false);
+
+
+      final int numMessages = 10000;
+
+      final ClientConsumer consumer = session.createConsumer(QUEUE);
+      session.start();
+
+      final NettyConnection nettyConnection = (NettyConnection) remotingConnection.getTransportConnection();
+
+
+      Thread tReceive = new Thread()
+      {
+         public void run()
+         {
+            boolean first = true;
+            try
+            {
+               while (!Thread.interrupted())
+               {
+                  ClientMessage received = consumer.receive(500);
+                  System.out.println("Received " + received);
+                  if (first)
+                  {
+                     first = false;
+                     nettyConnection.getNettyChannel().config().setAutoRead(false);
+                  }
+                  if (received != null)
+                  {
+                     received.acknowledge();
+                  }
+               }
+            }
+            catch (Throwable e)
+            {
+               Thread.currentThread().interrupt();
+               e.printStackTrace();
+            }
+         }
+      };
+
+      tReceive.start();
+
+      Thread sender = new Thread()
+      {
+         public void run()
+         {
+            try (
+               ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY));
+               ClientSessionFactory factory = locator.createSessionFactory();
+               ClientSession session = factory.createSession(false, true, true, true);
+               ClientProducer producer = session.createProducer(QUEUE);
+               )
+            {
+               for (int i = 0; i < numMessages; i++)
+               {
+                  ClientMessage message = createTextMessage(session, "m" + i);
+                  producer.send(message);
+               }
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+            }
+         }
+      };
+
+
+      sender.start();
+
+      try
+      {
+
+         long timeout = System.currentTimeMillis() + 20000;
+
+         while (System.currentTimeMillis() < timeout && server.getSessions().size() != 2)
+         {
+            Thread.sleep(10);
+         }
+
+         assertEquals(2, server.getSessions().size());
+
+         System.out.println("sessions = " + server.getSessions().size());
+
+         assertEquals(2, server.getConnectionCount());
+
+         timeout = System.currentTimeMillis() + 20000;
+
+         while (System.currentTimeMillis() < timeout && server.getSessions().size() != 1)
+         {
+            Thread.sleep(10);
+         }
+
+         System.out.println("Size = " + server.getConnectionCount());
+
+         System.out.println("sessions = " + server.getSessions().size());
+
+
+
+         if (server.getSessions().size() != 1)
+         {
+            System.out.println(threadDump("Thread dump"));
+            fail("The cleanup wasn't able to finish cleaning the session. It's probably stuck, look at the thread dump generated by the test for more information");
+         }
+
+         sender.join();
+
+         timeout = System.currentTimeMillis() + 20000;
+
+         while (System.currentTimeMillis() < timeout && server.getConnectionCount() != 0)
+         {
+            Thread.sleep(10);
+         }
+         assertEquals(0, server.getConnectionCount());
+      }
+      finally
+      {
+         nettyConnection.getNettyChannel().config().setAutoRead(true);
+         tReceive.interrupt();
+         tReceive.join();
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerTest.java
index 07d9586..96fca27 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ConsumerTest.java
@@ -12,6 +12,8 @@
  */
 package org.hornetq.tests.integration.client;
 
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -38,13 +40,32 @@ import org.hornetq.utils.ConcurrentHashSet;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 
 /**
  * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
  * @author <a href="mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
  */
+
+@RunWith(value = Parameterized.class)
 public class ConsumerTest extends ServiceTestBase
 {
+   @Parameterized.Parameters(name = "isNetty={0}")
+   public static Collection getParameters()
+   {
+      return Arrays.asList(new Object[][]{
+         {true},
+         {false}
+      });
+   }
+
+   public ConsumerTest(boolean netty)
+   {
+      this.netty = netty;
+   }
+
+   private final boolean netty;
    private HornetQServer server;
 
    private final SimpleString QUEUE = new SimpleString("ConsumerTestQueue");
@@ -53,7 +74,7 @@ public class ConsumerTest extends ServiceTestBase
 
    protected boolean isNetty()
    {
-      return false;
+      return netty;
    }
 
    @Before
@@ -114,7 +135,7 @@ public class ConsumerTest extends ServiceTestBase
       }
       // assert that all the messages are there and none have been acked
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable())));
 
       session.close();
    }
@@ -149,7 +170,7 @@ public class ConsumerTest extends ServiceTestBase
       }
       // assert that all the messages are there and none have been acked
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable())));
 
       session.close();
    }
@@ -188,7 +209,7 @@ public class ConsumerTest extends ServiceTestBase
       }
       // assert that all the messages are there and none have been acked
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable())));
 
       session.close();
    }
@@ -227,12 +248,12 @@ public class ConsumerTest extends ServiceTestBase
       }
       // assert that all the messages are there and none have been acked
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable())));
 
       session.close();
 
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable())));
    }
 
    @Test

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CoreClientTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CoreClientTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CoreClientTest.java
index 7521ce6..a87f180 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CoreClientTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CoreClientTest.java
@@ -63,11 +63,9 @@ public class CoreClientTest extends ServiceTestBase
    {
       final SimpleString QUEUE = new SimpleString("CoreClientTestQueue");
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setSecurityEnabled(false);
-
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(acceptorFactoryClassName));
+      Configuration conf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(acceptorFactoryClassName));
 
       HornetQServer server = addServer(HornetQServers.newHornetQServer(conf, false));
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CreateQueueIdempotentTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CreateQueueIdempotentTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CreateQueueIdempotentTest.java
index 4f90e5d..ca11aa4 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CreateQueueIdempotentTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/CreateQueueIdempotentTest.java
@@ -40,9 +40,9 @@ public class CreateQueueIdempotentTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration conf = createDefaultConfig();
-      conf.setSecurityEnabled(false);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
 
       server = addServer(HornetQServers.newHornetQServer(conf, true));
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/DeadLetterAddressTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/DeadLetterAddressTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/DeadLetterAddressTest.java
index 8c58227..e88ca83 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/DeadLetterAddressTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/DeadLetterAddressTest.java
@@ -327,12 +327,12 @@ public class DeadLetterAddressTest extends ServiceTestBase
       long timeout = System.currentTimeMillis() + 5000;
 
       // DLA transfer is asynchronous fired on the rollback
-      while (System.currentTimeMillis() < timeout && ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getMessageCount() != 0)
+      while (System.currentTimeMillis() < timeout && getMessageCount(((Queue)server.getPostOffice().getBinding(qName).getBindable())) != 0)
       {
          Thread.sleep(1);
       }
 
-      Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(qName).getBindable())));
       ClientMessage m = clientConsumer.receiveImmediate();
       Assert.assertNull(m);
       // All the messages should now be in the DLQ
@@ -511,11 +511,11 @@ public class DeadLetterAddressTest extends ServiceTestBase
    public void setUp() throws Exception
    {
       super.setUp();
-
-      Configuration configuration = createDefaultConfig();
-      configuration.setSecurityEnabled(false);
       TransportConfiguration transportConfig = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY);
-      configuration.getAcceptorConfigurations().add(transportConfig);
+
+      Configuration configuration = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(transportConfig);
       server = addServer(HornetQServers.newHornetQServer(configuration, false));
       // start the server
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryAddressTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryAddressTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryAddressTest.java
index cc7a24a..edddb8e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryAddressTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryAddressTest.java
@@ -11,6 +11,7 @@
  * permissions and limitations under the License.
  */
 package org.hornetq.tests.integration.client;
+import org.hornetq.core.message.impl.MessageImpl;
 import org.junit.Before;
 
 import org.junit.Test;
@@ -52,15 +53,16 @@ public class ExpiryAddressTest extends ServiceTestBase
    public void testBasicSend() throws Exception
    {
       SimpleString ea = new SimpleString("EA");
+      SimpleString adSend = new SimpleString("a1");
       SimpleString qName = new SimpleString("q1");
       SimpleString eq = new SimpleString("EA1");
       AddressSettings addressSettings = new AddressSettings();
       addressSettings.setExpiryAddress(ea);
-      server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings);
+      server.getAddressSettingsRepository().addMatch("#", addressSettings);
       clientSession.createQueue(ea, eq, null, false);
-      clientSession.createQueue(qName, qName, null, false);
+      clientSession.createQueue(adSend, qName, null, false);
 
-      ClientProducer producer = clientSession.createProducer(qName);
+      ClientProducer producer = clientSession.createProducer(adSend);
       ClientMessage clientMessage = createTextMessage(clientSession, "heyho!");
       clientMessage.setExpiration(System.currentTimeMillis());
       producer.send(clientMessage);
@@ -75,6 +77,9 @@ public class ExpiryAddressTest extends ServiceTestBase
       clientConsumer = clientSession.createConsumer(eq);
       m = clientConsumer.receive(500);
       Assert.assertNotNull(m);
+      Assert.assertEquals(qName.toString(), m.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE));
+      Assert.assertEquals(adSend.toString(), m.getStringProperty(MessageImpl.HDR_ORIGINAL_ADDRESS));
+      Assert.assertNotNull(m);
       Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!");
       m.acknowledge();
    }
@@ -165,6 +170,9 @@ public class ExpiryAddressTest extends ServiceTestBase
 
       Assert.assertNotNull(m);
 
+      assertNotNull(m.getStringProperty(MessageImpl.HDR_ORIGINAL_ADDRESS));
+      assertNotNull(m.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE));
+
       ExpiryAddressTest.log.info("acking");
       m.acknowledge();
 
@@ -178,6 +186,9 @@ public class ExpiryAddressTest extends ServiceTestBase
 
       Assert.assertNotNull(m);
 
+      assertNotNull(m.getStringProperty(MessageImpl.HDR_ORIGINAL_ADDRESS));
+      assertNotNull(m.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE));
+
       ExpiryAddressTest.log.info("acking");
       m.acknowledge();
 
@@ -206,6 +217,7 @@ public class ExpiryAddressTest extends ServiceTestBase
       ClientConsumer clientConsumer = clientSession.createConsumer(qName);
       ClientMessage m = clientConsumer.receiveImmediate();
       Assert.assertNull(m);
+
       clientConsumer.close();
    }
 
@@ -375,11 +387,11 @@ public class ExpiryAddressTest extends ServiceTestBase
    public void setUp() throws Exception
    {
       super.setUp();
-
-      Configuration configuration = createDefaultConfig();
-      configuration.setSecurityEnabled(false);
       TransportConfiguration transportConfig = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY);
-      configuration.getAcceptorConfigurations().add(transportConfig);
+
+      Configuration configuration = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(transportConfig);
       server = addServer(HornetQServers.newHornetQServer(configuration, false));
       // start the server
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryLargeMessageTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryLargeMessageTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryLargeMessageTest.java
index 62d2b9a..0044d9d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryLargeMessageTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ExpiryLargeMessageTest.java
@@ -143,14 +143,14 @@ public class ExpiryLargeMessageTest extends ServiceTestBase
       Thread.sleep(1500);
 
       long timeout = System.currentTimeMillis() + 5000;
-      while (timeout > System.currentTimeMillis() && queueExpiry.getMessageCount() != numberOfMessages)
+      while (timeout > System.currentTimeMillis() && getMessageCount(queueExpiry) != numberOfMessages)
       {
          // What the Expiry Scan would be doing
          myQueue.expireReferences();
          Thread.sleep(50);
       }
 
-      assertEquals(50, queueExpiry.getMessageCount());
+      assertEquals(50, getMessageCount(queueExpiry));
 
       session = sf.createSession(false, false);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/FailureDeadlockTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/FailureDeadlockTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/FailureDeadlockTest.java
index 7c44021..8435a5e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/FailureDeadlockTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/FailureDeadlockTest.java
@@ -62,9 +62,9 @@ public class FailureDeadlockTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration conf = createDefaultConfig();
-      conf.setSecurityEnabled(false);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       server = createServer(false, conf);
       jmsServer = new JMSServerManagerImpl(server);
       jmsServer.setContext(new NullInitialContext());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HangConsumerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HangConsumerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HangConsumerTest.java
index 0f0ae8f..cfe619f 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HangConsumerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HangConsumerTest.java
@@ -12,9 +12,9 @@
  */
 package org.hornetq.tests.integration.client;
 import org.hornetq.core.server.MessageReference;
+import org.hornetq.core.server.ServerConsumer;
 import org.junit.Before;
 import org.junit.After;
-
 import org.junit.Test;
 
 import java.lang.management.ManagementFactory;
@@ -29,7 +29,6 @@ import java.util.concurrent.TimeUnit;
 import javax.management.MBeanServer;
 
 import org.junit.Assert;
-
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Interceptor;
 import org.hornetq.api.core.SimpleString;
@@ -56,6 +55,7 @@ import org.hornetq.core.protocol.core.impl.wireformat.SessionReceiveMessage;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.Queue;
 import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.ServerSessionFactory;
 import org.hornetq.core.server.impl.HornetQServerImpl;
 import org.hornetq.core.server.impl.QueueFactoryImpl;
 import org.hornetq.core.server.impl.QueueImpl;
@@ -93,9 +93,8 @@ public class HangConsumerTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration config = createDefaultConfig(false);
-
-      config.setMessageExpiryScanPeriod(10);
+      Configuration config = createDefaultConfig(false)
+         .setMessageExpiryScanPeriod(10);
 
       HornetQSecurityManager securityManager = new HornetQSecurityManagerImpl();
 
@@ -148,9 +147,9 @@ public class HangConsumerTest extends ServiceTestBase
          producer.send(sessionProducer.createMessage(true));
          sessionProducer.commit();
 
-         // These two operations should finish without the test hanging
-         queue.getMessagesAdded(1);
-         queue.getMessageCount(1);
+         // These three operations should finish without the test hanging
+         getMessagesAdded(queue);
+         getMessageCount(queue);
 
          releaseConsumers();
 
@@ -161,8 +160,8 @@ public class HangConsumerTest extends ServiceTestBase
 
          // a flush to guarantee any pending task is finished on flushing out delivery and pending msgs
          queue.flushExecutor();
-         Assert.assertEquals(2, queue.getMessageCount());
-         Assert.assertEquals(2, queue.getMessagesAdded());
+         Assert.assertEquals(2, getMessageCount(queue));
+         Assert.assertEquals(2, getMessagesAdded(queue));
 
          ClientMessage msg = consumer.receive(5000);
          Assert.assertNotNull(msg);
@@ -396,8 +395,8 @@ public class HangConsumerTest extends ServiceTestBase
       producer.send(session.createMessage(true));
       session.commit();
 
-      long queueID = server.getStorageManager().generateUniqueID();
-      long txID = server.getStorageManager().generateUniqueID();
+      long queueID = server.getStorageManager().generateID();
+      long txID = server.getStorageManager().generateID();
 
 
       // Forcing a situation where the server would unexpectedly create a duplicated queue. The server should still start normally
@@ -523,6 +522,12 @@ public class HangConsumerTest extends ServiceTestBase
 
    class MyCallback implements SessionCallback
    {
+      @Override
+      public boolean hasCredits(ServerConsumer consumerID)
+      {
+         return true;
+      }
+
       final SessionCallback targetCallback;
 
       MyCallback(SessionCallback parameter)
@@ -548,7 +553,7 @@ public class HangConsumerTest extends ServiceTestBase
        * @see org.hornetq.spi.core.protocol.SessionCallback#sendMessage(org.hornetq.core.server.ServerMessage, long, int)
        */
       @Override
-      public int sendMessage(ServerMessage message, long consumerID, int deliveryCount)
+      public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount)
       {
          inCall.countDown();
          try
@@ -563,7 +568,7 @@ public class HangConsumerTest extends ServiceTestBase
 
          try
          {
-            return targetCallback.sendMessage(message, consumerID, deliveryCount);
+            return targetCallback.sendMessage(message, consumer, deliveryCount);
          }
          finally
          {
@@ -576,18 +581,18 @@ public class HangConsumerTest extends ServiceTestBase
        * @see org.hornetq.spi.core.protocol.SessionCallback#sendLargeMessage(org.hornetq.core.server.ServerMessage, long, long, int)
        */
       @Override
-      public int sendLargeMessage(ServerMessage message, long consumerID, long bodySize, int deliveryCount)
+      public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount)
       {
-         return targetCallback.sendLargeMessage(message, consumerID, bodySize, deliveryCount);
+         return targetCallback.sendLargeMessage(message, consumer, bodySize, deliveryCount);
       }
 
       /* (non-Javadoc)
        * @see org.hornetq.spi.core.protocol.SessionCallback#sendLargeMessageContinuation(long, byte[], boolean, boolean)
        */
       @Override
-      public int sendLargeMessageContinuation(long consumerID, byte[] body, boolean continues, boolean requiresResponse)
+      public int sendLargeMessageContinuation(ServerConsumer consumer, byte[] body, boolean continues, boolean requiresResponse)
       {
-         return targetCallback.sendLargeMessageContinuation(consumerID, body, continues, requiresResponse);
+         return targetCallback.sendLargeMessageContinuation(consumer, body, continues, requiresResponse);
       }
 
       /* (non-Javadoc)
@@ -618,7 +623,7 @@ public class HangConsumerTest extends ServiceTestBase
       }
 
       @Override
-      public void disconnect(long consumerId, String queueName)
+      public void disconnect(ServerConsumer consumerId, String queueName)
       {
          //To change body of implemented methods use File | Settings | File Templates.
       }
@@ -639,7 +644,7 @@ public class HangConsumerTest extends ServiceTestBase
       }
 
       @Override
-      protected ServerSessionImpl internalCreateSession(String name, String username, String password, int minLargeMessageSize, RemotingConnection connection, boolean autoCommitSends, boolean autoCommitAcks, boolean preAcknowledge, boolean xa, String defaultAddress, SessionCallback callback, OperationContext context) throws Exception
+      protected ServerSessionImpl internalCreateSession(String name, String username, String password, int minLargeMessageSize, RemotingConnection connection, boolean autoCommitSends, boolean autoCommitAcks, boolean preAcknowledge, boolean xa, String defaultAddress, SessionCallback callback, OperationContext context, ServerSessionFactory sessionFactory) throws Exception
       {
          return new ServerSessionImpl(name,
             username,

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HeuristicXATest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HeuristicXATest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HeuristicXATest.java
index b7f94bc..b737f83 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HeuristicXATest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HeuristicXATest.java
@@ -67,8 +67,8 @@ public class HeuristicXATest extends ServiceTestBase
    @Test
    public void testInvalidCall() throws Exception
    {
-      Configuration configuration = createDefaultConfig();
-      configuration.setJMXManagementEnabled(true);
+      Configuration configuration = createDefaultConfig()
+         .setJMXManagementEnabled(true);
 
       HornetQServer server = createServer(false, configuration, mbeanServer, new HashMap<String, AddressSettings>());
       server.start();
@@ -92,8 +92,8 @@ public class HeuristicXATest extends ServiceTestBase
 
    private void internalTest(final boolean isCommit) throws Exception
    {
-      Configuration configuration = createDefaultConfig();
-      configuration.setJMXManagementEnabled(true);
+      Configuration configuration = createDefaultConfig()
+         .setJMXManagementEnabled(true);
 
       HornetQServer server = createServer(false, configuration, mbeanServer, new HashMap<String, AddressSettings>());
       server.start();
@@ -155,7 +155,7 @@ public class HeuristicXATest extends ServiceTestBase
 
       if (isCommit)
       {
-         Assert.assertEquals(1, ((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+         Assert.assertEquals(1, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
          session = sf.createSession(false, false, false);
 
@@ -170,7 +170,7 @@ public class HeuristicXATest extends ServiceTestBase
          session.close();
       }
 
-      Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable())));
    }
 
    @Test
@@ -187,8 +187,8 @@ public class HeuristicXATest extends ServiceTestBase
 
    private void doHeuristicCompletionWithRestart(final boolean isCommit) throws Exception
    {
-      Configuration configuration = createDefaultConfig();
-      configuration.setJMXManagementEnabled(true);
+      Configuration configuration = createDefaultConfig()
+         .setJMXManagementEnabled(true);
 
       HornetQServer server = createServer(true, configuration, mbeanServer, new HashMap<String, AddressSettings>());
       server.start();
@@ -237,7 +237,7 @@ public class HeuristicXATest extends ServiceTestBase
 
       if (isCommit)
       {
-         Assert.assertEquals(1, ((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+         Assert.assertEquals(1, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
          session = sf.createSession(false, false, false);
 
@@ -252,7 +252,7 @@ public class HeuristicXATest extends ServiceTestBase
          session.close();
       }
 
-      Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
       server.stop();
 
@@ -287,8 +287,8 @@ public class HeuristicXATest extends ServiceTestBase
 
    private void doRecoverHeuristicCompletedTxWithRestart(final boolean heuristicCommit) throws Exception
    {
-      Configuration configuration = createDefaultConfig();
-      configuration.setJMXManagementEnabled(true);
+      Configuration configuration = createDefaultConfig()
+         .setJMXManagementEnabled(true);
 
       HornetQServer server = createServer(true, configuration, mbeanServer, new HashMap<String, AddressSettings>());
       server.start();
@@ -337,7 +337,7 @@ public class HeuristicXATest extends ServiceTestBase
 
       if (heuristicCommit)
       {
-         Assert.assertEquals(1, ((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+         Assert.assertEquals(1, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
          session = sf.createSession(false, false, false);
 
@@ -352,7 +352,7 @@ public class HeuristicXATest extends ServiceTestBase
          session.close();
       }
 
-      Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
       server.stop();
 
@@ -396,8 +396,8 @@ public class HeuristicXATest extends ServiceTestBase
 
    private void doForgetHeuristicCompletedTxAndRestart(final boolean heuristicCommit) throws Exception
    {
-      Configuration configuration = createDefaultConfig();
-      configuration.setJMXManagementEnabled(true);
+      Configuration configuration = createDefaultConfig()
+         .setJMXManagementEnabled(true);
 
       HornetQServer server = createServer(true, configuration, mbeanServer, new HashMap<String, AddressSettings>());
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HornetQCrashTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HornetQCrashTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HornetQCrashTest.java
index ace6eba..55dc38e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HornetQCrashTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/HornetQCrashTest.java
@@ -56,10 +56,10 @@ public class HornetQCrashTest extends UnitTestCase
    @Test
    public void testHang() throws Exception
    {
-      Configuration configuration = createDefaultConfig();
-      configuration.setPersistenceEnabled(false);
-      configuration.setSecurityEnabled(false);
-      configuration.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration configuration = createDefaultConfig()
+         .setPersistenceEnabled(false)
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
 
       server = addServer(HornetQServers.newHornetQServer(configuration));
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/IncompatibleVersionTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/IncompatibleVersionTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/IncompatibleVersionTest.java
index aaee7fb..ec7f135 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/IncompatibleVersionTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/IncompatibleVersionTest.java
@@ -252,9 +252,9 @@ public class IncompatibleVersionTest extends ServiceTestBase
    {
       public void perform(String startedString) throws Exception
       {
-         Configuration conf = new ConfigurationImpl();
-         conf.setSecurityEnabled(false);
-         conf.getAcceptorConfigurations().add(new TransportConfiguration("org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory"));
+         Configuration conf = new ConfigurationImpl()
+            .setSecurityEnabled(false)
+            .addAcceptorConfiguration(new TransportConfiguration("org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory"));
          HornetQServer server = HornetQServers.newHornetQServer(conf, false);
          server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/InterruptedLargeMessageTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/InterruptedLargeMessageTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/InterruptedLargeMessageTest.java
index ece72e3..5365012 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/InterruptedLargeMessageTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/InterruptedLargeMessageTest.java
@@ -524,7 +524,7 @@ public class InterruptedLargeMessageTest extends LargeMessageTestBase
          }
 
          @Override
-         protected void postAcknowledge(final MessageReference ref)
+         public void postAcknowledge(final MessageReference ref)
          {
             System.out.println("Ignoring postACK on message " + ref);
          }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/JournalCrashTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/JournalCrashTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/JournalCrashTest.java
index ecbb925..4ad3f26 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/JournalCrashTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/JournalCrashTest.java
@@ -59,11 +59,11 @@ public class JournalCrashTest extends ServiceTestBase
 
    protected void startServer() throws Exception
    {
-      Configuration config = createDefaultConfig();
-      config.setJournalFileSize(HornetQDefaultConfiguration.getDefaultJournalFileSize());
-      config.setJournalCompactMinFiles(HornetQDefaultConfiguration.getDefaultJournalCompactMinFiles());
-      config.setJournalCompactPercentage(HornetQDefaultConfiguration.getDefaultJournalCompactPercentage());
-      config.setJournalMinFiles(2);
+      Configuration config = createDefaultConfig()
+         .setJournalFileSize(HornetQDefaultConfiguration.getDefaultJournalFileSize())
+         .setJournalCompactMinFiles(HornetQDefaultConfiguration.getDefaultJournalCompactMinFiles())
+         .setJournalCompactPercentage(HornetQDefaultConfiguration.getDefaultJournalCompactPercentage())
+         .setJournalMinFiles(2);
 
       server = super.createServer(true, config);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/LargeMessageTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/LargeMessageTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/LargeMessageTest.java
index 25f41a0..d3be7b8 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/LargeMessageTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/LargeMessageTest.java
@@ -301,9 +301,8 @@ public class LargeMessageTest extends LargeMessageTestBase
       final int PAGE_SIZE = 10 * 1024;
       final int MESSAGE_SIZE = 1024; // 1k
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true,
                                           config,
@@ -380,11 +379,10 @@ public class LargeMessageTest extends LargeMessageTestBase
 
       ClientSession session = null;
 
-      Configuration config = createDefaultConfig(isNetty());
-      config.setJournalFileSize(journalsize);
-
-      config.setJournalBufferSize_AIO(10 * 1024);
-      config.setJournalBufferSize_NIO(10 * 1024);
+      Configuration config = createDefaultConfig(isNetty())
+         .setJournalFileSize(journalsize)
+         .setJournalBufferSize_AIO(10 * 1024)
+         .setJournalBufferSize_NIO(10 * 1024);
 
       HornetQServer server = createServer(true, config);
 
@@ -2504,7 +2502,7 @@ public class LargeMessageTest extends LargeMessageTestBase
          Assert.assertEquals(0,
                              ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount());
          Assert.assertEquals(0,
-                             ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+                             getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
       }
       finally
@@ -2609,7 +2607,7 @@ public class LargeMessageTest extends LargeMessageTestBase
          Assert.assertEquals(0,
                              ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount());
          Assert.assertEquals(0,
-                             ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+                             getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
       }
       finally
@@ -2942,7 +2940,7 @@ public class LargeMessageTest extends LargeMessageTestBase
          Assert.assertEquals(0,
                              ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount());
          Assert.assertEquals(0,
-                             ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+                             getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
       }
       finally
@@ -3028,7 +3026,7 @@ public class LargeMessageTest extends LargeMessageTestBase
       Assert.assertEquals(0,
                           ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getDeliveringCount());
       Assert.assertEquals(0,
-                          ((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable()).getMessageCount());
+                          getMessageCount(((Queue) server.getPostOffice().getBinding(ADDRESS).getBindable())));
 
       log.debug("Thread done");
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageExpirationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageExpirationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageExpirationTest.java
index 9e567da..2a0ea06 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageExpirationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageExpirationTest.java
@@ -157,7 +157,7 @@ public class MessageExpirationTest extends ServiceTestBase
       Thread.sleep(500);
 
       Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(queue).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(queue).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(queue).getBindable())));
 
       ClientMessage message2 = consumer.receiveImmediate();
       Assert.assertNull(message2);
@@ -188,7 +188,7 @@ public class MessageExpirationTest extends ServiceTestBase
       Assert.assertNull(message2);
 
       Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(queue).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(queue).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(queue).getBindable())));
 
       consumer.close();
       session.deleteQueue(queue);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingConnectionFactoryTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingConnectionFactoryTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingConnectionFactoryTest.java
index b7b167d..93ee1b9 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingConnectionFactoryTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingConnectionFactoryTest.java
@@ -121,11 +121,11 @@ public class MessageGroupingConnectionFactoryTest extends UnitTestCase
    public void setUp() throws Exception
    {
       super.setUp();
-
-      Configuration configuration = createDefaultConfig();
-      configuration.setSecurityEnabled(false);
       TransportConfiguration transportConfig = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY);
-      configuration.getAcceptorConfigurations().add(transportConfig);
+
+      Configuration configuration = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(transportConfig);
       server = addServer(HornetQServers.newHornetQServer(configuration, false));
       // start the server
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingTest.java
index edcc2f2..eff418a 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessageGroupingTest.java
@@ -610,11 +610,11 @@ public class MessageGroupingTest extends UnitTestCase
    public void setUp() throws Exception
    {
       super.setUp();
-
-      Configuration configuration = createDefaultConfig();
-      configuration.setSecurityEnabled(false);
       TransportConfiguration transportConfig = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY);
-      configuration.getAcceptorConfigurations().add(transportConfig);
+
+      Configuration configuration = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(transportConfig);
       server = addServer(HornetQServers.newHornetQServer(configuration, false));
       // start the server
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessagePriorityTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessagePriorityTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessagePriorityTest.java
index 2ba1786..14fb379 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessagePriorityTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/MessagePriorityTest.java
@@ -337,9 +337,9 @@ public class MessagePriorityTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration config = createDefaultConfig();
-      config.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()));
-      config.setSecurityEnabled(false);
+      Configuration config = createDefaultConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()))
+         .setSecurityEnabled(false);
       server = addServer(HornetQServers.newHornetQServer(config, false));
       server.start();
       locator =

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NIOvsOIOTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NIOvsOIOTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NIOvsOIOTest.java
index 3b26f2b..dd752a8 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NIOvsOIOTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NIOvsOIOTest.java
@@ -153,9 +153,8 @@ public class NIOvsOIOTest extends UnitTestCase
    {
       String acceptorFactoryClassName = "org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory";
 
-      Configuration conf = createDefaultConfig();
-
-      conf.setSecurityEnabled(false);
+      Configuration conf = createDefaultConfig()
+         .setSecurityEnabled(false);
 
       Map<String, Object> params = new HashMap<String, Object>();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NettyConsumerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NettyConsumerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NettyConsumerTest.java
deleted file mode 100644
index 6f21b7a..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NettyConsumerTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.client;
-
-/**
- * A NettyConsumerTest
- *
- * @author clebertsuconic
- *
- *
- */
-public class NettyConsumerTest extends ConsumerTest
-{
-   protected boolean isNetty()
-   {
-      return true;
-   }
-
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NewDeadLetterAddressTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NewDeadLetterAddressTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NewDeadLetterAddressTest.java
index 67c0c03..99ea6ba 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NewDeadLetterAddressTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/NewDeadLetterAddressTest.java
@@ -75,11 +75,11 @@ public class NewDeadLetterAddressTest extends UnitTestCase
    public void setUp() throws Exception
    {
       super.setUp();
-
-      Configuration configuration = createDefaultConfig();
-      configuration.setSecurityEnabled(false);
       TransportConfiguration transportConfig = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY);
-      configuration.getAcceptorConfigurations().add(transportConfig);
+
+      Configuration configuration = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(transportConfig);
       server = addServer(HornetQServers.newHornetQServer(configuration, false));
       // start the server
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/OrderTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/OrderTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/OrderTest.java
index fac7099..621073b 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/OrderTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/OrderTest.java
@@ -12,6 +12,9 @@
  */
 package org.hornetq.tests.integration.client;
 
+import java.util.Arrays;
+import java.util.Collection;
+
 import org.hornetq.api.core.client.ClientConsumer;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientProducer;
@@ -24,19 +27,38 @@ import org.hornetq.tests.util.ServiceTestBase;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 
 /**
  * A OrderTest
  *
  * @author <mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
  */
+@RunWith(Parameterized.class)
 public class OrderTest extends ServiceTestBase
 {
 
+   private boolean persistent;
+
    private HornetQServer server;
 
    private ServerLocator locator;
 
+   public OrderTest(boolean persistent)
+   {
+      this.persistent = persistent;
+   }
+   @Parameterized.Parameters(name = "persistent={0}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][]{
+         {true},
+         {false}
+      });
+   }
+
+
    @Override
    @Before
    public void setUp() throws Exception
@@ -53,18 +75,7 @@ public class OrderTest extends ServiceTestBase
    // Public --------------------------------------------------------
 
    @Test
-   public void testSimpleOrderNoStorage() throws Exception
-   {
-      doTestSimpleOrder(false);
-   }
-
-   @Test
-   public void testSimpleOrderPersistence() throws Exception
-   {
-      doTestSimpleOrder(true);
-   }
-
-   public void doTestSimpleOrder(final boolean persistent) throws Exception
+   public void testSimpleStorage() throws Exception
    {
       server = createServer(persistent, true);
       server.start();
@@ -138,18 +149,7 @@ public class OrderTest extends ServiceTestBase
    }
 
    @Test
-   public void testOrderOverSessionClosePersistent() throws Exception
-   {
-      doTestOverCancel(true);
-   }
-
-   @Test
-   public void testOrderOverSessionCloseNonPersistent() throws Exception
-   {
-      doTestOverCancel(false);
-   }
-
-   public void doTestOverCancel(final boolean persistent) throws Exception
+   public void testOrderOverSessionClose() throws Exception
    {
       server = createServer(persistent, true);
 
@@ -210,19 +210,7 @@ public class OrderTest extends ServiceTestBase
    }
 
    @Test
-   public void testOrderOverSessionClosePersistentWithRedeliveryDelay() throws Exception
-   {
-      doTestOverCancelWithRedelivery(true);
-   }
-
-   @Test
-   public void testOrderOverSessionCloseNonPersistentWithRedeliveryDelay() throws Exception
-   {
-      doTestOverCancelWithRedelivery(false);
-   }
-
-
-   public void doTestOverCancelWithRedelivery(final boolean persistent) throws Exception
+   public void testOrderOverSessionCloseWithRedeliveryDelay() throws Exception
    {
       server = createServer(persistent, true);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingOrderTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingOrderTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingOrderTest.java
index 5d8f379..6da8ca3 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingOrderTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingOrderTest.java
@@ -92,9 +92,8 @@ public class PagingOrderTest extends ServiceTestBase
    {
       boolean persistentMessages = true;
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
 
@@ -202,9 +201,8 @@ public class PagingOrderTest extends ServiceTestBase
    {
       boolean persistentMessages = true;
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
 
@@ -304,10 +302,10 @@ public class PagingOrderTest extends ServiceTestBase
 
       assertEquals(0, errors.get());
 
-      assertEquals(numberOfMessages, q2.getMessageCount());
-      assertEquals(numberOfMessages, q2.getMessagesAdded());
-      assertEquals(0, q1.getMessageCount());
-      assertEquals(numberOfMessages, q1.getMessagesAdded());
+      assertEquals(numberOfMessages, getMessageCount(q2));
+      assertEquals(numberOfMessages, getMessagesAdded(q2));
+      assertEquals(0, getMessageCount(q1));
+      assertEquals(numberOfMessages, getMessagesAdded(q1));
 
       session.close();
       sf.close();
@@ -343,11 +341,11 @@ public class PagingOrderTest extends ServiceTestBase
 
       assertNotNull(q2);
 
-      assertEquals("q2 msg count", numberOfMessages, q2.getMessageCount());
-      assertEquals("q2 msgs added", numberOfMessages, q2.getMessagesAdded());
-      assertEquals("q1 msg count", 0, q1.getMessageCount());
+      assertEquals("q2 msg count", numberOfMessages, getMessageCount(q2));
+      assertEquals("q2 msgs added", numberOfMessages, getMessagesAdded(q2));
+      assertEquals("q1 msg count", 0, getMessageCount(q1));
       // 0, since nothing was sent to the queue after the server was restarted
-      assertEquals("q1 msgs added", 0, q1.getMessagesAdded());
+      assertEquals("q1 msgs added", 0, getMessagesAdded(q1));
 
    }
 
@@ -356,9 +354,8 @@ public class PagingOrderTest extends ServiceTestBase
    {
       boolean persistentMessages = true;
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
 
@@ -455,16 +452,15 @@ public class PagingOrderTest extends ServiceTestBase
 
       assertEquals(0, errors.get());
       long timeout = System.currentTimeMillis() + 10000;
-      while (numberOfMessages - 100 != q1.getMessageCount() && System.currentTimeMillis() < timeout)
+      while (numberOfMessages - 100 != getMessageCount(q1) && System.currentTimeMillis() < timeout)
       {
          Thread.sleep(500);
 
       }
 
-      assertEquals(numberOfMessages, q2.getMessageCount());
-      assertEquals(numberOfMessages, q2.getMessagesAdded());
-      assertEquals(numberOfMessages - 100, q1.getMessageCount());
-      assertEquals(numberOfMessages, q2.getMessagesAdded());
+      assertEquals(numberOfMessages, getMessageCount(q2));
+      assertEquals(numberOfMessages, getMessagesAdded(q2));
+      assertEquals(numberOfMessages - 100, getMessageCount(q1));
    }
 
    @Test
@@ -472,9 +468,8 @@ public class PagingOrderTest extends ServiceTestBase
    {
       boolean persistentMessages = true;
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
 
@@ -573,9 +568,8 @@ public class PagingOrderTest extends ServiceTestBase
    {
       boolean persistentMessages = true;
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
 
@@ -721,9 +715,8 @@ public class PagingOrderTest extends ServiceTestBase
    public void testPagingOverCreatedDestinationTopics() throws Exception
    {
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, PAGE_SIZE, -1, new HashMap<String, AddressSettings>());
 
@@ -748,7 +741,10 @@ public class PagingOrderTest extends ServiceTestBase
                                                           1000,
                                                           0,
                                                           false,
-                                                          "PAGE");
+                                                          "PAGE",
+                                                          -1,
+                                                          10,
+                                                          "KILL");
 
       HornetQJMSConnectionFactory cf = (HornetQJMSConnectionFactory) HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF,
                                                                                                                        new TransportConfiguration(INVM_CONNECTOR_FACTORY));
@@ -796,9 +792,8 @@ public class PagingOrderTest extends ServiceTestBase
    public void testPagingOverCreatedDestinationQueues() throws Exception
    {
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, -1, -1, AddressFullMessagePolicy.BLOCK, new HashMap<String, AddressSettings>());
 
@@ -821,7 +816,10 @@ public class PagingOrderTest extends ServiceTestBase
                                                           1000,
                                                           0,
                                                           false,
-                                                          "PAGE");
+                                                          "PAGE",
+                                                          -1,
+                                                          10,
+                                                          "KILL");
 
       jmsServer.createQueue(true, "Q1", null, true, "/queue/Q1");
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingSyncTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingSyncTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingSyncTest.java
index a038863..28fb180 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingSyncTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingSyncTest.java
@@ -53,9 +53,8 @@ public class PagingSyncTest extends ServiceTestBase
    {
       boolean persistentMessages = true;
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       HornetQServer server = createServer(true, config, PAGE_SIZE, PAGE_MAX, new HashMap<String, AddressSettings>());
 


[06/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/StoreConfigTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/StoreConfigTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/StoreConfigTest.java
index d120b57..1cfb83e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/StoreConfigTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/StoreConfigTest.java
@@ -55,13 +55,16 @@ public class StoreConfigTest extends JMSTestBase
 
       List<String> transportConfigurations = new ArrayList<String>();
       transportConfigurations.add("tst");
-      ConnectionFactoryConfigurationImpl factCFG = new ConnectionFactoryConfigurationImpl("tst", false, transportConfigurations);
+      ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl()
+         .setName("tst")
+         .setConnectorNames(transportConfigurations);
 
       jmsServer.createConnectionFactory(true, factCFG, "/someCF", "/someCF2" );
 
 
-      ConnectionFactoryConfigurationImpl nonPersisted = new ConnectionFactoryConfigurationImpl("np", false, transportConfigurations);
-
+      ConnectionFactoryConfigurationImpl nonPersisted = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl()
+         .setName("np")
+         .setConnectorNames(transportConfigurations);
 
       jmsServer.createConnectionFactory(false, nonPersisted, "/nonPersisted" );
 
@@ -130,7 +133,9 @@ public class StoreConfigTest extends JMSTestBase
       List<String> transportConfigurations = new ArrayList<String>();
       transportConfigurations.add("tst");
 
-      ConnectionFactoryConfigurationImpl factCFG = new ConnectionFactoryConfigurationImpl("tst", false, transportConfigurations);
+      ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl()
+         .setName("tst")
+         .setConnectorNames(transportConfigurations);
 
       jmsServer.createConnectionFactory(true, factCFG, "/someCF");
 
@@ -243,8 +248,9 @@ public class StoreConfigTest extends JMSTestBase
       List<String> transportConfigurations = new ArrayList<String>();
       transportConfigurations.add("tst");
 
-      ConnectionFactoryConfigurationImpl factCFG = new ConnectionFactoryConfigurationImpl("tst", false, transportConfigurations);
-
+      ConnectionFactoryConfigurationImpl factCFG = (ConnectionFactoryConfigurationImpl) new ConnectionFactoryConfigurationImpl()
+         .setName("tst")
+         .setConnectorNames(transportConfigurations);
 
       jmsServer.createConnectionFactory(true, factCFG, "/someCF");
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/TopicCleanupTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/TopicCleanupTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/TopicCleanupTest.java
index ca2633b..8a20a4e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/TopicCleanupTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/TopicCleanupTest.java
@@ -76,9 +76,9 @@ public class TopicCleanupTest extends JMSTestBase
 
          for (int i = 0; i < 100; i++)
          {
-            long txid = storage.generateUniqueID();
+            long txid = storage.generateID();
 
-            final Queue queue = new QueueImpl(storage.generateUniqueID(), SimpleString.toSimpleString("jms.topic.topic"), SimpleString.toSimpleString("jms.topic.topic"), FilterImpl.createFilter(HornetQServerImpl.GENERIC_IGNORED_FILTER), true, false, server.getScheduledPool(), server.getPostOffice(),
+            final Queue queue = new QueueImpl(storage.generateID(), SimpleString.toSimpleString("jms.topic.topic"), SimpleString.toSimpleString("jms.topic.topic"), FilterImpl.createFilter(HornetQServerImpl.GENERIC_IGNORED_FILTER), true, false, server.getScheduledPool(), server.getPostOffice(),
                                               storage, server.getAddressSettingsRepository(), server.getExecutorFactory().getExecutor());
 
             LocalQueueBinding binding = new LocalQueueBinding(queue.getAddress(), queue, server.getNodeID());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/BindingsClusterTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/BindingsClusterTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/BindingsClusterTest.java
index 6106ba5..b4313e3 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/BindingsClusterTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/BindingsClusterTest.java
@@ -54,7 +54,7 @@ public class BindingsClusterTest extends JMSClusteredTestBase
       this.crash = crash;
    }
 
-   @Parameterized.Parameters
+   @Parameterized.Parameters(name = "crash={0}")
    public static Collection getParameters()
    {
       return Arrays.asList(new Object[][]{{true}, {false}});
@@ -63,11 +63,10 @@ public class BindingsClusterTest extends JMSClusteredTestBase
    @Before
    public void setUp() throws Exception
    {
+      //todo fix if needed
       super.setUp();
       jmsServer1.getHornetQServer().setIdentity("Server 1");
-      jmsServer1.getHornetQServer().getConfiguration().getHAPolicy().setFailoverOnServerShutdown(true);
       jmsServer2.getHornetQServer().setIdentity("Server 2");
-      jmsServer2.getHornetQServer().getConfiguration().getHAPolicy().setFailoverOnServerShutdown(true);
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverListenerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverListenerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverListenerTest.java
index 73defd5..73efc4f 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverListenerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverListenerTest.java
@@ -21,7 +21,9 @@ import javax.jms.Queue;
 import javax.jms.Session;
 import javax.jms.TextMessage;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 import org.hornetq.api.core.SimpleString;
@@ -32,11 +34,12 @@ import org.hornetq.api.core.client.FailoverEventType;
 import org.hornetq.api.jms.HornetQJMSClient;
 import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.remoting.impl.invm.InVMRegistry;
 import org.hornetq.core.remoting.impl.invm.TransportConstants;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.jms.client.HornetQConnection;
 import org.hornetq.jms.client.HornetQConnectionFactory;
@@ -163,7 +166,7 @@ public class JMSFailoverListenerTest extends ServiceTestBase
 
       JMSUtil.crash(liveService, ((HornetQSession) sess).getCoreSession());
 
-      Assert.assertEquals(FailoverEventType.FAILURE_DETECTED, listener.getEventTypeList().get(0));
+      Assert.assertEquals(FailoverEventType.FAILURE_DETECTED, listener.get(0));
       for (int i = 0; i < numMessages; i++)
       {
          JMSFailoverListenerTest.log.info("got message " + i);
@@ -178,10 +181,10 @@ public class JMSFailoverListenerTest extends ServiceTestBase
       TextMessage tm = (TextMessage) consumer.receiveNoWait();
 
       Assert.assertNull(tm);
-      Assert.assertEquals(FailoverEventType.FAILOVER_COMPLETED, listener.getEventTypeList().get(1));
+      Assert.assertEquals(FailoverEventType.FAILOVER_COMPLETED, listener.get(1));
 
       conn.close();
-      Assert.assertEquals("Expected 2 FailoverEvents to be triggered", 2, listener.getEventTypeList().size());
+      Assert.assertEquals("Expected 2 FailoverEvents to be triggered", 2, listener.size());
    }
 
    @Test
@@ -233,7 +236,7 @@ public class JMSFailoverListenerTest extends ServiceTestBase
       // Note we block on P send to make sure all messages get to server before failover
 
       JMSUtil.crash(liveService, coreSessionLive);
-      Assert.assertEquals(FailoverEventType.FAILURE_DETECTED, listener.getEventTypeList().get(0));
+      Assert.assertEquals(FailoverEventType.FAILURE_DETECTED, listener.get(0));
       connLive.close();
 
       // Now recreate on backup
@@ -256,8 +259,8 @@ public class JMSFailoverListenerTest extends ServiceTestBase
       }
 
       TextMessage tm = (TextMessage) consumerBackup.receiveNoWait();
-      Assert.assertEquals(FailoverEventType.FAILOVER_FAILED, listener.getEventTypeList().get(1));
-      Assert.assertEquals("Expected 2 FailoverEvents to be triggered", 2, listener.getEventTypeList().size());
+      Assert.assertEquals(FailoverEventType.FAILOVER_FAILED, listener.get(1));
+      Assert.assertEquals("Expected 2 FailoverEvents to be triggered", 2, listener.size());
       Assert.assertNull(tm);
 
       connBackup.close();
@@ -285,27 +288,25 @@ public class JMSFailoverListenerTest extends ServiceTestBase
       livetc = new TransportConfiguration(INVM_CONNECTOR_FACTORY);
 
       liveAcceptortc = new TransportConfiguration(INVM_ACCEPTOR_FACTORY);
-
       backupAcceptortc = new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams);
 
-      backupConf = createBasicConfig(0);
+      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
 
-      backupConf.getAcceptorConfigurations().add(backupAcceptortc);
-      backupConf.getConnectorConfigurations().put(livetc.getName(), livetc);
-      backupConf.getConnectorConfigurations().put(backuptc.getName(), backuptc);
-      basicClusterConnectionConfig(backupConf, backuptc.getName(), livetc.getName());
+      backupConf = createBasicConfig(0)
+         .addAcceptorConfiguration(backupAcceptortc)
+         .addConnectorConfiguration(livetc.getName(), livetc)
+         .addConnectorConfiguration(backuptc.getName(), backuptc)
+         .setJournalType(getDefaultJournalType())
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams))
+         .setBindingsDirectory(getBindingsDir())
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir())
+         .setPagingDirectory(getPageDir())
+         .setLargeMessagesDirectory(getLargeMessagesDir())
+         .setPersistenceEnabled(true)
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration())
+         .addClusterConfiguration(basicClusterConnectionConfig(backuptc.getName(), livetc.getName()));
 
-      backupConf.setSecurityEnabled(false);
-      backupConf.setJournalType(getDefaultJournalType());
-      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-      backupConf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams));
-      backupConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      backupConf.setBindingsDirectory(getBindingsDir());
-      backupConf.setJournalMinFiles(2);
-      backupConf.setJournalDirectory(getJournalDir());
-      backupConf.setPagingDirectory(getPageDir());
-      backupConf.setLargeMessagesDirectory(getLargeMessagesDir());
-      backupConf.setPersistenceEnabled(true);
       backupService = new InVMNodeManagerServer(backupConf, nodeManager);
 
       backupJMSService = new JMSServerManagerImpl(backupService);
@@ -316,23 +317,21 @@ public class JMSFailoverListenerTest extends ServiceTestBase
       log.info("Starting backup");
       backupJMSService.start();
 
-      liveConf = createBasicConfig(0);
-
-      liveConf.setJournalDirectory(getJournalDir());
-      liveConf.setBindingsDirectory(getBindingsDir());
-
-      liveConf.setSecurityEnabled(false);
-      liveConf.getAcceptorConfigurations().add(liveAcceptortc);
-      basicClusterConnectionConfig(liveConf, livetc.getName());
-      liveConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConf.setJournalType(getDefaultJournalType());
-      liveConf.setBindingsDirectory(getBindingsDir());
-      liveConf.setJournalMinFiles(2);
-      liveConf.setJournalDirectory(getJournalDir());
-      liveConf.setPagingDirectory(getPageDir());
-      liveConf.setLargeMessagesDirectory(getLargeMessagesDir());
-      liveConf.getConnectorConfigurations().put(livetc.getName(), livetc);
-      liveConf.setPersistenceEnabled(true);
+      liveConf = createBasicConfig(0)
+         .setJournalDirectory(getJournalDir())
+         .setBindingsDirectory(getBindingsDir())
+         .addAcceptorConfiguration(liveAcceptortc)
+         .setJournalType(getDefaultJournalType())
+         .setBindingsDirectory(getBindingsDir())
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir())
+         .setPagingDirectory(getPageDir())
+         .setLargeMessagesDirectory(getLargeMessagesDir())
+         .addConnectorConfiguration(livetc.getName(), livetc)
+         .setPersistenceEnabled(true)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration())
+         .addClusterConfiguration(basicClusterConnectionConfig(livetc.getName()));
+
       liveService = new InVMNodeManagerServer(liveConf, nodeManager);
 
       liveJMSService = new JMSServerManagerImpl(liveService);
@@ -381,17 +380,41 @@ public class JMSFailoverListenerTest extends ServiceTestBase
 
    private static class MyFailoverListener implements FailoverEventListener
    {
-      private ArrayList<FailoverEventType> eventTypeList = new ArrayList<FailoverEventType>();
+      private List<FailoverEventType> eventTypeList = Collections.synchronizedList(new ArrayList<FailoverEventType>());
+
+
+      public FailoverEventType get(int element)
+      {
+         waitForElements(element + 1);
+         return eventTypeList.get(element);
+      }
+
+      public int size()
+      {
+         return eventTypeList.size();
+      }
 
-      public ArrayList<FailoverEventType> getEventTypeList()
+      private void waitForElements(int elements)
       {
-         return eventTypeList;
+         long timeout = System.currentTimeMillis() + 5000;
+         while (timeout > System.currentTimeMillis() && eventTypeList.size() < elements)
+         {
+            try
+            {
+               Thread.sleep(1);
+            }
+            catch (Throwable e)
+            {
+               fail(e.getMessage());
+            }
+         }
+
+         Assert.assertTrue(eventTypeList.size() >= elements);
       }
 
       public void failoverEvent(FailoverEventType eventType)
       {
          eventTypeList.add(eventType);
-         log.info("Failover event just happened : " + eventType.toString());
       }
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverTest.java
index 79b9e28..ec7b768 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSFailoverTest.java
@@ -37,13 +37,16 @@ import org.hornetq.api.jms.HornetQJMSClient;
 import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.core.client.impl.ClientSessionInternal;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.protocol.core.Packet;
 import org.hornetq.core.protocol.core.impl.wireformat.SessionReceiveContinuationMessage;
 import org.hornetq.core.remoting.impl.invm.InVMRegistry;
 import org.hornetq.core.remoting.impl.invm.TransportConstants;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.jms.client.HornetQConnectionFactory;
 import org.hornetq.jms.client.HornetQDestination;
@@ -514,29 +517,24 @@ public class JMSFailoverTest extends ServiceTestBase
 
       backupAcceptortc = new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams);
 
-      backupConf = createBasicConfig(0);
+      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
 
-      backupConf.getAcceptorConfigurations().add(backupAcceptortc);
-      backupConf.getConnectorConfigurations().put(livetc.getName(), livetc);
-      backupConf.getConnectorConfigurations().put(backuptc.getName(), backuptc);
-      basicClusterConnectionConfig(backupConf, backuptc.getName(), livetc.getName());
+      backupConf = createBasicConfig(0)
+         .addAcceptorConfiguration(backupAcceptortc)
+         .addConnectorConfiguration(livetc.getName(), livetc)
+         .addConnectorConfiguration(backuptc.getName(), backuptc)
+         .setSecurityEnabled(false)
+         .setJournalType(getDefaultJournalType())
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams))
+         .setBindingsDirectory(getBindingsDir())
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir())
+         .setPagingDirectory(getPageDir())
+         .setLargeMessagesDirectory(getLargeMessagesDir())
+         .setPersistenceEnabled(true)
+         .setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration())
+         .addClusterConfiguration(basicClusterConnectionConfig(backuptc.getName(), livetc.getName()));
 
-      backupConf.setSecurityEnabled(false);
-      backupConf.setJournalType(getDefaultJournalType());
-      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-      backupConf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams));
-
-      if (sharedStore)
-         backupConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      else
-         backupConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-
-      backupConf.setBindingsDirectory(getBindingsDir());
-      backupConf.setJournalMinFiles(2);
-      backupConf.setJournalDirectory(getJournalDir());
-      backupConf.setPagingDirectory(getPageDir());
-      backupConf.setLargeMessagesDirectory(getLargeMessagesDir());
-      backupConf.setPersistenceEnabled(true);
       backupService = new InVMNodeManagerServer(backupConf, nodeManager);
 
       backupJMSService = new JMSServerManagerImpl(backupService);
@@ -547,28 +545,22 @@ public class JMSFailoverTest extends ServiceTestBase
       log.info("Starting backup");
       backupJMSService.start();
 
-      liveConf = createBasicConfig(0);
-
-      liveConf.setJournalDirectory(getJournalDir());
-      liveConf.setBindingsDirectory(getBindingsDir());
-
-      liveConf.setSecurityEnabled(false);
-      liveConf.getAcceptorConfigurations().add(liveAcceptortc);
-      basicClusterConnectionConfig(liveConf, livetc.getName());
-
-      if (sharedStore)
-         liveConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      else
-         liveConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
+      liveConf = createBasicConfig(0)
+         .setJournalDirectory(getJournalDir())
+         .setBindingsDirectory(getBindingsDir())
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(liveAcceptortc)
+         .setJournalType(getDefaultJournalType())
+         .setBindingsDirectory(getBindingsDir())
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir())
+         .setPagingDirectory(getPageDir())
+         .setLargeMessagesDirectory(getLargeMessagesDir())
+         .addConnectorConfiguration(livetc.getName(), livetc)
+         .setPersistenceEnabled(true)
+         .setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration())
+         .addClusterConfiguration(basicClusterConnectionConfig(livetc.getName()));
 
-      liveConf.setJournalType(getDefaultJournalType());
-      liveConf.setBindingsDirectory(getBindingsDir());
-      liveConf.setJournalMinFiles(2);
-      liveConf.setJournalDirectory(getJournalDir());
-      liveConf.setPagingDirectory(getPageDir());
-      liveConf.setLargeMessagesDirectory(getLargeMessagesDir());
-      liveConf.getConnectorConfigurations().put(livetc.getName(), livetc);
-      liveConf.setPersistenceEnabled(true);
       liveService = new InVMNodeManagerServer(liveConf, nodeManager);
 
       liveJMSService = new JMSServerManagerImpl(liveService);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSReconnectTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSReconnectTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSReconnectTest.java
index 9c64e46..25eb15c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSReconnectTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/JMSReconnectTest.java
@@ -323,16 +323,14 @@ public class JMSReconnectTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration liveConf = createBasicConfig();
-      liveConf.setSecurityEnabled(false);
-      liveConf.setJournalType(getDefaultJournalType());
-      liveConf.getAcceptorConfigurations()
-              .add(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
-      liveConf.setBindingsDirectory(getBindingsDir());
-      liveConf.setJournalMinFiles(2);
-      liveConf.setJournalDirectory(getJournalDir());
-      liveConf.setPagingDirectory(getPageDir());
-      liveConf.setLargeMessagesDirectory(getLargeMessagesDir());
+      Configuration liveConf = createBasicConfig()
+         .setJournalType(getDefaultJournalType())
+         .addAcceptorConfiguration(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"))
+         .setBindingsDirectory(getBindingsDir())
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir())
+         .setPagingDirectory(getPageDir())
+         .setLargeMessagesDirectory(getLargeMessagesDir());
 
       liveService = HornetQServers.newHornetQServer(liveConf, true);
       liveService.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java
index 70ee8ba..f1cd191 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/cluster/ReplicatedJMSFailoverTest.java
@@ -13,9 +13,10 @@
 package org.hornetq.tests.integration.jms.cluster;
 
 import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
 import org.hornetq.core.remoting.impl.invm.TransportConstants;
 import org.hornetq.core.server.HornetQServers;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.jms.server.impl.JMSServerManagerImpl;
 
 /**
@@ -34,17 +35,18 @@ public class ReplicatedJMSFailoverTest extends JMSFailoverTest
    @Override
    protected void startServers() throws Exception
    {
-      backupConf = createBasicConfig();
-      backupConf.setJournalType(getDefaultJournalType());
-      backupConf.setSecurityEnabled(false);
       backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-      backupConf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams));
-      backupConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-      backupConf.setBindingsDirectory(getBindingsDir(0, true));
-      backupConf.setJournalMinFiles(2);
-      backupConf.setJournalDirectory(getJournalDir(0, true));
-      backupConf.setPagingDirectory(getPageDir(0, true));
-      backupConf.setLargeMessagesDirectory(getLargeMessagesDir(0, true));
+
+      backupConf = createBasicConfig()
+         .setJournalType(getDefaultJournalType())
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, backupParams))
+         .setBindingsDirectory(getBindingsDir(0, true))
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir(0, true))
+         .setPagingDirectory(getPageDir(0, true))
+         .setLargeMessagesDirectory(getLargeMessagesDir(0, true))
+         .setHAPolicyConfiguration(new ReplicaPolicyConfiguration());
+
       backupService = HornetQServers.newHornetQServer(backupConf, true);
 
       backupJMSService = new JMSServerManagerImpl(backupService);
@@ -53,23 +55,16 @@ public class ReplicatedJMSFailoverTest extends JMSFailoverTest
 
       backupJMSService.start();
 
-
-
-      liveConf = createBasicConfig();
-      liveConf.setSecurityEnabled(false);
-      liveConf.setJournalType(getDefaultJournalType());
-
-      liveConf.getConnectorConfigurations().put("toBackup", new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams));
-      //liveConf.setBackupConnectorName("toBackup");
-
-      liveConf.getAcceptorConfigurations()
-              .add(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
-      liveConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-      liveConf.setBindingsDirectory(getBindingsDir(0, false));
-      liveConf.setJournalMinFiles(2);
-      liveConf.setJournalDirectory(getJournalDir(0, false));
-      liveConf.setPagingDirectory(getPageDir(0, false));
-      liveConf.setLargeMessagesDirectory(getLargeMessagesDir(0, false));
+      liveConf = createBasicConfig()
+         .setJournalType(getDefaultJournalType())
+         .addConnectorConfiguration("toBackup", new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams))
+         .addAcceptorConfiguration(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"))
+         .setBindingsDirectory(getBindingsDir(0, false))
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir(0, false))
+         .setPagingDirectory(getPageDir(0, false))
+         .setLargeMessagesDirectory(getLargeMessagesDir(0, false))
+         .setHAPolicyConfiguration(new ReplicatedPolicyConfiguration());
 
       liveService = HornetQServers.newHornetQServer(liveConf, true);
 
@@ -78,7 +73,6 @@ public class ReplicatedJMSFailoverTest extends JMSFailoverTest
       liveJMSService.setContext(ctx1);
 
       liveJMSService.start();
-
    }
 
    // Private -------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactorySerializationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactorySerializationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactorySerializationTest.java
index c26ffd0..af11610 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactorySerializationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactorySerializationTest.java
@@ -59,9 +59,17 @@ public class ConnectionFactorySerializationTest extends JMSTestBase
          final int port = getUDPDiscoveryPort();
          String localBindAddress = getLocalHost().getHostAddress();
 
-         UDPBroadcastGroupConfiguration config = new UDPBroadcastGroupConfiguration(groupAddress, port, localBindAddress, 8580);
-
-         DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration("dg1", 5000, 5000, config);
+         UDPBroadcastGroupConfiguration config = new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(groupAddress)
+            .setGroupPort(port)
+            .setLocalBindAddress(localBindAddress)
+            .setLocalBindPort(8580);
+
+         DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration()
+            .setName("dg1")
+            .setRefreshTimeout(5000)
+            .setDiscoveryInitialWaitTimeout(5000)
+            .setBroadcastEndpointFactoryConfiguration(config);
 
          jmsServer.getHornetQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java
new file mode 100644
index 0000000..ae63232
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ConnectionFactoryWithJGroupsSerializationTest.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.jms.connection;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+import javax.jms.Queue;
+
+import org.hornetq.api.core.BroadcastEndpointFactoryConfiguration;
+import org.hornetq.api.core.DiscoveryGroupConfiguration;
+import org.hornetq.api.core.JGroupsBroadcastGroupConfiguration;
+import org.hornetq.api.jms.JMSFactoryType;
+import org.hornetq.jms.client.HornetQConnectionFactory;
+import org.hornetq.tests.util.JMSTestBase;
+import org.jgroups.JChannel;
+import org.jgroups.conf.PlainConfigurator;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class ConnectionFactoryWithJGroupsSerializationTest extends JMSTestBase
+{
+
+   protected static HornetQConnectionFactory jmsCf1;
+   protected static HornetQConnectionFactory jmsCf2;
+
+   private final String jgroupsConfigString = "UDP(oob_thread_pool.max_threads=300;"
+                                            + "bind_addr=127.0.0.1;oob_thread_pool.keep_alive_time=1000;"
+                                            + "max_bundle_size=31k;mcast_send_buf_size=640000;"
+                                            + "internal_thread_pool.keep_alive_time=60000;"
+                                            + "internal_thread_pool.rejection_policy=discard;"
+                                            + "mcast_recv_buf_size=25000000;bind_port=55200;"
+                                            + "internal_thread_pool.queue_max_size=100;"
+                                            + "mcast_port=45688;thread_pool.min_threads=20;"
+                                            + "oob_thread_pool.rejection_policy=discard;"
+                                            + "thread_pool.max_threads=300;enable_diagnostics=false;"
+                                            + "thread_pool.enabled=true;internal_thread_pool.queue_enabled=true;"
+                                            + "ucast_recv_buf_size=20000000;ucast_send_buf_size=640000;"
+                                            + "internal_thread_pool.enabled=true;oob_thread_pool.enabled=true;"
+                                            + "ip_ttl=2;thread_pool.rejection_policy=discard;thread_pool.keep_alive_time=5000;"
+                                            + "internal_thread_pool.max_threads=10;thread_pool.queue_enabled=true;"
+                                            + "mcast_addr=230.0.0.4;singleton_name=udp;max_bundle_timeout=30;"
+                                            + "oob_thread_pool.queue_enabled=false;internal_thread_pool.min_threads=1;"
+                                            + "bundler_type=old;oob_thread_pool.min_threads=20;"
+                                            + "thread_pool.queue_max_size=1000):PING(num_initial_members=3;"
+                                            + "timeout=2000):MERGE3(min_interval=20000;max_interval=100000)"
+                                            + ":FD_SOCK(bind_addr=127.0.0.1;start_port=54200):FD_ALL(interval=3000;"
+                                            + "timeout=15000):VERIFY_SUSPECT(bind_addr=127.0.0.1;"
+                                            + "timeout=1500):pbcast.NAKACK2(max_msg_batch_size=100;"
+                                            + "xmit_table_msgs_per_row=10000;xmit_table_max_compaction_time=10000;"
+                                            + "xmit_table_num_rows=100;xmit_interval=1000):UNICAST3(xmit_table_msgs_per_row=10000;"
+                                            + "xmit_table_max_compaction_time=10000;xmit_table_num_rows=20)"
+                                            + ":pbcast.STABLE(desired_avg_gossip=50000;max_bytes=400000;"
+                                            + "stability_delay=1000):pbcast.GMS(print_local_addr=true;"
+                                            + "view_bundling=true;join_timeout=3000;view_ack_collection_timeout=5000;"
+                                            + "resume_task_timeout=7500):UFC(max_credits=1m;min_threshold=0.40)"
+                                            + ":MFC(max_credits=1m;min_threshold=0.40):FRAG2(frag_size=30k)"
+                                            + ":RSVP(resend_interval=500;ack_on_delivery=false;timeout=60000)";
+
+   JChannel channel = null;
+   Queue testQueue = null;
+
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      try
+      {
+         super.setUp();
+
+         PlainConfigurator configurator = new PlainConfigurator(jgroupsConfigString);
+         channel = new JChannel(configurator);
+
+         String channelName1 = "channel1";
+         String channelName2 = "channel2";
+
+         JGroupsBroadcastGroupConfiguration jgroupsBroadcastCfg1 = new JGroupsBroadcastGroupConfiguration(channel, channelName1);
+         JGroupsBroadcastGroupConfiguration jgroupsBroadcastCfg2 = new JGroupsBroadcastGroupConfiguration(jgroupsConfigString, channelName2);
+
+         DiscoveryGroupConfiguration dcConfig1 = new DiscoveryGroupConfiguration()
+            .setName("dg1")
+            .setRefreshTimeout(5000)
+            .setDiscoveryInitialWaitTimeout(5000)
+            .setBroadcastEndpointFactoryConfiguration(jgroupsBroadcastCfg1);
+
+         DiscoveryGroupConfiguration dcConfig2 = new DiscoveryGroupConfiguration()
+            .setName("dg2")
+            .setRefreshTimeout(5000)
+            .setDiscoveryInitialWaitTimeout(5000)
+            .setBroadcastEndpointFactoryConfiguration(jgroupsBroadcastCfg2);
+
+         jmsServer.getHornetQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig1.getName(), dcConfig1);
+         jmsServer.getHornetQServer().getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig2.getName(), dcConfig2);
+
+         jmsServer.createConnectionFactory("ConnectionFactory1",
+                                           false,
+                                           JMSFactoryType.CF,
+                                           dcConfig1.getName(),
+                                           "/ConnectionFactory1");
+
+
+         jmsServer.createConnectionFactory("ConnectionFactory2",
+                                           false,
+                                           JMSFactoryType.CF,
+                                           dcConfig2.getName(),
+                                           "/ConnectionFactory2");
+
+         testQueue = createQueue("testQueueFor1389");
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+         throw e;
+      }
+   }
+
+   // Public --------------------------------------------------------
+
+   //HORNETQ-1389
+   //Here we deploy two Connection Factories with JGroups discovery groups.
+   //The first one uses a runtime JChannel object, which is the case before the fix.
+   //The second one uses the raw jgroups config string, which is the case after fix.
+   //So the first one will get serialization exception in the test
+   //while the second will not.
+   @Test
+   public void testSerialization() throws Exception
+   {
+      jmsCf1 = (HornetQConnectionFactory) namingContext.lookup("/ConnectionFactory1");
+      jmsCf2 = (HornetQConnectionFactory) namingContext.lookup("/ConnectionFactory2");
+
+      try
+      {
+         serialize(jmsCf1);
+      }
+      catch (java.io.NotSerializableException e)
+      {
+         //this is expected
+      }
+
+      //now cf2 should be OK
+      byte[] x = serialize(jmsCf2);
+      HornetQConnectionFactory jmsCf2Copy = deserialize(x, HornetQConnectionFactory.class);
+      assertNotNull(jmsCf2Copy);
+      BroadcastEndpointFactoryConfiguration broadcastEndpoint = jmsCf2Copy.getDiscoveryGroupConfiguration().getBroadcastEndpointFactoryConfiguration();
+      assertTrue(broadcastEndpoint instanceof JGroupsBroadcastGroupConfiguration);
+   }
+
+   @Override
+   @After
+   public void tearDown() throws Exception
+   {
+      if (channel != null)
+      {
+         channel.close();
+      }
+
+      super.tearDown();
+   }
+
+   private static <T extends Serializable> byte[] serialize(T obj) throws IOException
+   {
+      ByteArrayOutputStream baos = new ByteArrayOutputStream();
+      ObjectOutputStream oos = new ObjectOutputStream(baos);
+      oos.writeObject(obj);
+      oos.close();
+      return baos.toByteArray();
+   }
+
+   private static <T extends Serializable> T deserialize(byte[] b, Class<T> cl) throws IOException, ClassNotFoundException
+   {
+      ByteArrayInputStream bais = new ByteArrayInputStream(b);
+      ObjectInputStream ois = new ObjectInputStream(bais);
+      Object o = ois.readObject();
+      return cl.cast(o);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ExceptionListenerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ExceptionListenerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ExceptionListenerTest.java
index a588911..82589a7 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ExceptionListenerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/connection/ExceptionListenerTest.java
@@ -65,11 +65,8 @@ public class ExceptionListenerTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations()
-          .add(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
       server = addServer(HornetQServers.newHornetQServer(conf, false));
       jmsServer = new JMSServerManagerImpl(server);
       jmsServer.setContext(new NullInitialContext());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/consumer/ConsumerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/consumer/ConsumerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/consumer/ConsumerTest.java
index 6038858..61be8db 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/consumer/ConsumerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/consumer/ConsumerTest.java
@@ -24,6 +24,7 @@ import javax.jms.MessageProducer;
 import javax.jms.QueueBrowser;
 import javax.jms.Session;
 import javax.jms.TextMessage;
+
 import java.util.Enumeration;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -87,6 +88,47 @@ public class ConsumerTest extends JMSTestBase
    }
 
    @Test
+   public void testTransactionalSessionRollback() throws Exception
+   {
+      conn = cf.createConnection();
+      Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
+
+      MessageProducer prod = sess.createProducer(topic);
+      MessageConsumer cons = sess.createConsumer(topic);
+
+      conn.start();
+
+      TextMessage msg1 = sess.createTextMessage("m1");
+      TextMessage msg2 = sess.createTextMessage("m2");
+      TextMessage msg3 = sess.createTextMessage("m3");
+
+      prod.send(msg1);
+      sess.commit();
+
+      prod.send(msg2);
+      sess.rollback();
+
+      prod.send(msg3);
+      sess.commit();
+
+      TextMessage m1 = (TextMessage) cons.receive(2000);
+      assertNotNull(m1);
+      assertEquals("m1", m1.getText());
+
+      TextMessage m2 = (TextMessage) cons.receive(2000);
+      assertNotNull(m2);
+      assertEquals("m3", m2.getText());
+
+      TextMessage m3 = (TextMessage) cons.receive(2000);
+      assertNull("m3 should be null", m3);
+
+      System.out.println("received m1: " + m1.getText());
+      System.out.println("received m2: " + m2.getText());
+      System.out.println("received m3: " + m3);
+      sess.commit();
+   }
+
+   @Test
    public void testPreCommitAcks() throws Exception
    {
       conn = cf.createConnection();
@@ -108,8 +150,8 @@ public class ConsumerTest extends JMSTestBase
       }
 
       SimpleString queueName = new SimpleString(HornetQDestination.JMS_QUEUE_ADDRESS_PREFIX + ConsumerTest.Q_NAME);
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
+      Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
    }
 
    @Test
@@ -161,7 +203,7 @@ public class ConsumerTest extends JMSTestBase
 
       SimpleString queueName = new SimpleString(HornetQDestination.JMS_QUEUE_ADDRESS_PREFIX + ConsumerTest.Q_NAME);
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
       conn.close();
    }
 
@@ -246,7 +288,7 @@ public class ConsumerTest extends JMSTestBase
 
       SimpleString queueName = new SimpleString(HornetQDestination.JMS_QUEUE_ADDRESS_PREFIX + ConsumerTest.Q_NAME);
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
       conn.close();
    }
 
@@ -276,7 +318,7 @@ public class ConsumerTest extends JMSTestBase
       // Messages should all have been acked since we set pre ack on the cf
       SimpleString queueName = new SimpleString(HornetQDestination.JMS_QUEUE_ADDRESS_PREFIX + ConsumerTest.Q_NAME);
       Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getDeliveringCount());
-      Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getMessageCount());
+      Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
    }
 
    @Test

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/divert/DivertAndACKClientTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/divert/DivertAndACKClientTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/divert/DivertAndACKClientTest.java
index 627a592..c92995d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/divert/DivertAndACKClientTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/divert/DivertAndACKClientTest.java
@@ -104,13 +104,12 @@ public class DivertAndACKClientTest extends JMSTestBase
    {
       Configuration config = super.createDefaultConfig(netty);
 
-      DivertConfiguration divert = new DivertConfiguration("local-divert",
-                                                           "some-name",
-                                                           "jms.queue.Source",
-                                                           "jms.queue.Dest",
-                                                           true,
-                                                           null,
-                                                           null);
+      DivertConfiguration divert = new DivertConfiguration()
+         .setName("local-divert")
+         .setRoutingName("some-name")
+         .setAddress("jms.queue.Source")
+         .setForwardingAddress("jms.queue.Dest")
+         .setExclusive(true);
 
       ArrayList<DivertConfiguration> divertList = new ArrayList<DivertConfiguration>();
       divertList.add(divert);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java
index b402147..f80c559 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/jms2client/JmsProducerCompletionListenerTest.java
@@ -38,7 +38,6 @@ import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
 
 @RunWith(Parameterized.class)
 public class JmsProducerCompletionListenerTest extends JMSTestBase
@@ -51,7 +50,7 @@ public class JmsProducerCompletionListenerTest extends JMSTestBase
 
    private final int confirmationWindowSize;
 
-   @Parameters(name = "confirmationWindowSize={0}")
+   @Parameterized.Parameters(name = "confirmationWindowSize={0}")
    public static Iterable<Object[]> data()
    {
       return Arrays.asList(new Object[][]{{-1}, {0}, {10}, {1000}});

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/ColocatedJMSServerStartStopTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/ColocatedJMSServerStartStopTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/ColocatedJMSServerStartStopTest.java
deleted file mode 100644
index c3ce272..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/ColocatedJMSServerStartStopTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.jms.server;
-
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.jms.HornetQJMSClient;
-import org.hornetq.api.jms.JMSFactoryType;
-import org.hornetq.core.config.impl.FileConfiguration;
-import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.impl.InVMNodeManager;
-import org.hornetq.jms.client.HornetQConnectionFactory;
-import org.hornetq.jms.client.HornetQJMSContext;
-import org.hornetq.jms.client.HornetQSession;
-import org.hornetq.jms.server.JMSServerManager;
-import org.hornetq.jms.server.impl.JMSServerManagerImpl;
-import org.hornetq.spi.core.security.HornetQSecurityManager;
-import org.hornetq.spi.core.security.HornetQSecurityManagerImpl;
-import org.hornetq.tests.integration.IntegrationTestLogger;
-import org.hornetq.tests.integration.cluster.util.SameProcessHornetQServer;
-import org.hornetq.tests.integration.cluster.util.TestableServer;
-import org.hornetq.tests.integration.jms.server.management.JMSUtil;
-import org.hornetq.tests.util.ColocatedHornetQServer;
-import org.hornetq.tests.util.UnitTestCase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.jms.JMSConsumer;
-import javax.jms.JMSContext;
-import javax.jms.Queue;
-import java.io.File;
-
-/**
- *
- * A JMSServerStartStopTest
- *
- * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
- */
-public class ColocatedJMSServerStartStopTest extends UnitTestCase
-{
-   private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER;
-
-   private JMSServerManager liveJMSServer;
-
-   private JMSServerManager liveJMSServer2;
-
-   private TestableServer testableServerlive1;
-
-   private HornetQJMSContext context;
-
-   @Test
-   public void testStopStart1() throws Exception
-   {
-      start();
-      JMSUtil.waitForFailoverTopology(5000, ((ColocatedHornetQServer)liveJMSServer2.getHornetQServer()).backupServer, liveJMSServer.getHornetQServer());
-      JMSUtil.waitForFailoverTopology(5000, ((ColocatedHornetQServer)liveJMSServer.getHornetQServer()).backupServer, liveJMSServer2.getHornetQServer());
-      HornetQConnectionFactory connectionFactory = HornetQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF,
-            new TransportConfiguration(NETTY_CONNECTOR_FACTORY));
-      connectionFactory.setReconnectAttempts(-1);
-      context = (HornetQJMSContext) connectionFactory.createContext(JMSContext.AUTO_ACKNOWLEDGE);
-      Queue queue = HornetQJMSClient.createQueue("myJMSQueue");
-      JMSConsumer consumer = context.createConsumer(queue);
-
-      for (int i = 0; i < 100; i++)
-      {
-         String body = "message:" + i;
-         context.createProducer().send(queue, body);
-         System.out.println(body);
-      }
-
-      for (int i = 0; i < 50; i++)
-      {
-         String msg = consumer.receiveBody(String.class);
-         System.out.println("msg = " + msg);
-      }
-
-      testableServerlive1.crash(true, ((HornetQSession) context.getSession()).getCoreSession());
-
-      for (int i = 0; i < 50; i++)
-      {
-         String msg = consumer.receiveBody(String.class, 5000);
-         assertNotNull(msg);
-         System.out.println("msg = " + msg);
-      }
-      stop();
-   }
-
-   @Override
-   @Before
-   public void setUp() throws Exception
-   {
-      File tmp = new File("/tmp/hornetq-unit-test");
-      deleteDirectory(tmp);
-      super.setUp();
-   }
-
-   @Override
-   @After
-   public void tearDown() throws Exception
-   {
-      if (context != null)
-         context.close();
-      if (liveJMSServer != null)
-         liveJMSServer.stop();
-      liveJMSServer = null;
-      if (liveJMSServer2 != null)
-         liveJMSServer2.stop();
-      liveJMSServer2 = null;
-      super.tearDown();
-   }
-
-   // Private -------------------------------------------------------
-
-   private void stop() throws Exception
-   {
-      liveJMSServer.stop();
-   }
-
-   private void start() throws Exception
-   {
-      NodeManager nodeManagerLive1 = new InVMNodeManager(false);
-      NodeManager nodeManagerLive2 = new InVMNodeManager(false);
-      FileConfiguration fc = new FileConfiguration("colocated-server-start-stop-config1.xml");
-
-      fc.start();
-
-      HornetQSecurityManager sm = new HornetQSecurityManagerImpl();
-
-      HornetQServer liveServer = addServer(new ColocatedHornetQServer(fc, sm, nodeManagerLive1, nodeManagerLive2));
-      testableServerlive1 = new SameProcessHornetQServer(liveServer);
-
-      liveJMSServer = new JMSServerManagerImpl(liveServer, "colocated-server-start-stop-jms-config1.xml");
-      addHornetQComponent(liveJMSServer);
-      liveJMSServer.setContext(null);
-
-      liveJMSServer.start();
-
-      FileConfiguration fc2 = new FileConfiguration("colocated-server-start-stop-config2.xml");
-
-      fc2.start();
-
-      HornetQSecurityManager sm2 = new HornetQSecurityManagerImpl();
-
-      HornetQServer liveServer2 = addServer(new ColocatedHornetQServer(fc2, sm2, nodeManagerLive2, nodeManagerLive1));
-
-      liveJMSServer2 = new JMSServerManagerImpl(liveServer2, "colocated-server-start-stop-jms-config2.xml");
-      addHornetQComponent(liveJMSServer);
-      liveJMSServer2.setContext(null);
-
-      liveJMSServer2.start();
-   }
-
-   // Inner classes -------------------------------------------------
-
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/JMSServerDeployerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/JMSServerDeployerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/JMSServerDeployerTest.java
index f788b52..73605e4 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/JMSServerDeployerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/JMSServerDeployerTest.java
@@ -337,15 +337,19 @@ public class JMSServerDeployerTest extends ServiceTestBase
    {
       super.setUp();
 
-      config = createBasicConfig();
-      config.getConnectorConfigurations().put("netty",
-                                              new TransportConfiguration(NettyConnectorFactory.class.getName()));
-
-      DiscoveryGroupConfiguration dcg = new DiscoveryGroupConfiguration("mygroup",
-                                                                        5432, 5432,
-                                                                        new UDPBroadcastGroupConfiguration("243.7.7.7", 12345,
-                                                                                                           "172.16.8.10", -1));
-      config.getDiscoveryGroupConfigurations().put("mygroup", dcg);
+      DiscoveryGroupConfiguration dcg = new DiscoveryGroupConfiguration()
+         .setName("mygroup")
+         .setRefreshTimeout(5432)
+         .setDiscoveryInitialWaitTimeout(5432)
+         .setBroadcastEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+                                                      .setGroupAddress("243.7.7.7")
+                                                      .setGroupPort(12345)
+                                                      .setLocalBindAddress("172.16.8.10"));
+
+      config = createBasicConfig()
+         .addConnectorConfiguration("netty", new TransportConfiguration(NettyConnectorFactory.class.getName()))
+         .addDiscoveryGroupConfiguration("mygroup", dcg);
+
       HornetQServer server = createServer(false, config);
 
       deploymentManager = new FileDeploymentManager(config.getFileDeployerScanPeriod());
@@ -354,7 +358,6 @@ public class JMSServerDeployerTest extends ServiceTestBase
       context = new InVMNamingContext();
       jmsServer.setContext(context);
       jmsServer.start();
-
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSConfigurationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSConfigurationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSConfigurationTest.java
index ca823ea..b36463c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSConfigurationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSConfigurationTest.java
@@ -66,21 +66,25 @@ public class JMSConfigurationTest extends ServiceTestBase
       TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName());
       List<TransportConfiguration> transportConfigs = new ArrayList<TransportConfiguration>();
       transportConfigs.add(connectorConfig);
-      ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl(RandomUtil.randomString(),
-                                                                                       false,
-                                                                                       registerConnectors(coreServer, transportConfigs),
-                                                                                       "/cf/binding1",
-                                                                                       "/cf/binding2");
+
+      ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl()
+         .setName(RandomUtil.randomString())
+         .setConnectorNames(registerConnectors(coreServer, transportConfigs))
+         .setBindings("/cf/binding1", "/cf/binding2");
+
       jmsConfiguration.getConnectionFactoryConfigurations().add(cfConfig);
-      JMSQueueConfigurationImpl queueConfig = new JMSQueueConfigurationImpl(RandomUtil.randomString(),
-                                                                      null,
-                                                                      false,
-                                                                      "/queue/binding1",
-                                                                      "/queue/binding2");
+      JMSQueueConfigurationImpl queueConfig = new JMSQueueConfigurationImpl()
+         .setName(RandomUtil.randomString())
+         .setDurable(false)
+         .setBindings(
+            "/queue/binding1",
+            "/queue/binding2");
       jmsConfiguration.getQueueConfigurations().add(queueConfig);
-      TopicConfiguration topicConfig = new TopicConfigurationImpl(RandomUtil.randomString(),
-                                                                  "/topic/binding1",
-                                                                  "/topic/binding2");
+      TopicConfiguration topicConfig = new TopicConfigurationImpl()
+         .setName(RandomUtil.randomString())
+         .setBindings(
+            "/topic/binding1",
+            "/topic/binding2");
       jmsConfiguration.getTopicConfigurations().add(topicConfig);
 
       JMSServerManager server = new JMSServerManagerImpl(coreServer, jmsConfiguration);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSServerConfigParserTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSServerConfigParserTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSServerConfigParserTest.java
index 4dfdc5b..3cf9587 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSServerConfigParserTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/config/JMSServerConfigParserTest.java
@@ -51,10 +51,9 @@ public class JMSServerConfigParserTest extends ServiceTestBase
    @Test
    public void testParsing() throws Exception
    {
-      Configuration config = createDefaultConfig();
-
-      // anything so the parsing will work
-      config.getConnectorConfigurations().put("netty", new TransportConfiguration());
+      Configuration config = createDefaultConfig()
+         // anything so the parsing will work
+         .addConnectorConfiguration("netty", new TransportConfiguration());
 
       JMSServerConfigParser parser = new JMSServerConfigParserImpl();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/ConnectionFactoryControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/ConnectionFactoryControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/ConnectionFactoryControlTest.java
index 2945f70..89e12d0 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/ConnectionFactoryControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/server/management/ConnectionFactoryControlTest.java
@@ -11,12 +11,17 @@
  * permissions and limitations under the License.
  */
 package org.hornetq.tests.integration.jms.server.management;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.management.Notification;
+
 import org.junit.Before;
 import org.junit.After;
-
 import org.junit.Test;
-
 import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.management.ObjectNameBuilder;
+import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.api.jms.management.ConnectionFactoryControl;
 import org.hornetq.api.jms.management.JMSServerControl;
 import org.hornetq.core.config.Configuration;
@@ -24,6 +29,7 @@ import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
 import org.hornetq.jms.client.HornetQConnectionFactory;
 import org.hornetq.jms.server.impl.JMSServerManagerImpl;
+import org.hornetq.jms.server.management.JMSNotificationType;
 import org.hornetq.tests.integration.management.ManagementControlHelper;
 import org.hornetq.tests.integration.management.ManagementTestBase;
 import org.hornetq.tests.unit.util.InVMNamingContext;
@@ -84,6 +90,51 @@ public class ConnectionFactoryControlTest extends ManagementTestBase
 
    }
 
+   //make sure notifications are always received no matter whether
+   //a CF is created via JMSServerControl or by JMSServerManager directly.
+   @Test
+   public void testCreateCFNotification() throws Exception
+   {
+      JMSUtil.JMXListener listener = new JMSUtil.JMXListener();
+      this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getJMSServerObjectName(), listener, null, null);
+
+      List<String> connectors = new ArrayList<String>();
+      connectors.add("invm");
+
+      this.serverManager.createConnectionFactory("NewCF",
+                                                  false,
+                                                  JMSFactoryType.CF,
+                                                  connectors,
+                                                  "/NewConnectionFactory");
+
+      Notification notif = listener.getNotification();
+
+      assertEquals(JMSNotificationType.CONNECTION_FACTORY_CREATED.toString(), notif.getType());
+      assertEquals("NewCF", notif.getMessage());
+
+      this.serverManager.destroyConnectionFactory("NewCF");
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.CONNECTION_FACTORY_DESTROYED.toString(), notif.getType());
+      assertEquals("NewCF", notif.getMessage());
+
+      JMSServerControl control = createJMSControl();
+
+      control.createConnectionFactory("test", false, false, 0, "invm", "test");
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.CONNECTION_FACTORY_CREATED.toString(), notif.getType());
+      assertEquals("test", notif.getMessage());
+
+      control.destroyConnectionFactory("test");
+
+      notif = listener.getNotification();
+      assertEquals(JMSNotificationType.CONNECTION_FACTORY_DESTROYED.toString(), notif.getType());
+      assertEquals("test", notif.getMessage());
+   }
+
+
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
@@ -103,11 +154,11 @@ public class ConnectionFactoryControlTest extends ManagementTestBase
     */
    protected void startServer() throws Exception
    {
-      Configuration conf = createDefaultConfig(false);
-      conf.getConnectorConfigurations().put("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY));
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf = createDefaultConfig(false)
+         .addConnectorConfiguration("invm", new TransportConfiguration(INVM_CONNECTOR_FACTORY))
+         .setSecurityEnabled(false)
+         .setJMXManagementEnabled(true)
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       server = HornetQServers.newHornetQServer(conf, mbeanServer, true);
       server.start();
 


[33/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManager.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManager.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManager.java
new file mode 100644
index 0000000..320651e
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManager.java
@@ -0,0 +1,756 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import javax.jms.InvalidClientIDException;
+
+import io.netty.channel.ChannelPipeline;
+
+import org.apache.activemq.advisory.AdvisorySupport;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ActiveMQMessage;
+import org.apache.activemq.command.ActiveMQTopic;
+import org.apache.activemq.command.BrokerId;
+import org.apache.activemq.command.Command;
+import org.apache.activemq.command.CommandTypes;
+import org.apache.activemq.command.ConnectionId;
+import org.apache.activemq.command.ConnectionInfo;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.ConsumerInfo;
+import org.apache.activemq.command.DestinationInfo;
+import org.apache.activemq.command.MessageDispatch;
+import org.apache.activemq.command.MessageId;
+import org.apache.activemq.command.ProducerId;
+import org.apache.activemq.command.ProducerInfo;
+import org.apache.activemq.command.SessionId;
+import org.apache.activemq.command.SessionInfo;
+import org.apache.activemq.command.TransactionId;
+import org.apache.activemq.command.TransactionInfo;
+import org.apache.activemq.command.WireFormatInfo;
+import org.apache.activemq.command.XATransactionId;
+import org.apache.activemq.openwire.OpenWireFormat;
+import org.apache.activemq.openwire.OpenWireFormatFactory;
+import org.apache.activemq.state.ConnectionState;
+import org.apache.activemq.state.ProducerState;
+import org.apache.activemq.state.SessionState;
+import org.apache.activemq.util.IdGenerator;
+import org.apache.activemq.util.InetAddressUtil;
+import org.apache.activemq.util.LongSequenceGenerator;
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.journal.IOAsyncTask;
+import org.hornetq.core.protocol.openwire.amq.AMQConnectionContext;
+import org.hornetq.core.protocol.openwire.amq.AMQPersistenceAdapter;
+import org.hornetq.core.protocol.openwire.amq.AMQProducerBrokerExchange;
+import org.hornetq.core.protocol.openwire.amq.AMQServerSession;
+import org.hornetq.core.protocol.openwire.amq.AMQSession;
+import org.hornetq.core.protocol.openwire.amq.AMQTransportConnectionState;
+import org.hornetq.core.remoting.impl.netty.NettyServerConnection;
+import org.hornetq.core.security.CheckType;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.spi.core.protocol.ConnectionEntry;
+import org.hornetq.spi.core.protocol.MessageConverter;
+import org.hornetq.spi.core.protocol.ProtocolManager;
+import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.remoting.Acceptor;
+import org.hornetq.spi.core.remoting.Connection;
+import org.hornetq.spi.core.security.HornetQSecurityManager;
+
+public class OpenWireProtocolManager implements ProtocolManager
+{
+   private static final IdGenerator BROKER_ID_GENERATOR = new IdGenerator();
+   private static final IdGenerator ID_GENERATOR = new IdGenerator();
+
+   private final LongSequenceGenerator messageIdGenerator = new LongSequenceGenerator();
+   private final HornetQServer server;
+
+   private OpenWireFormatFactory wireFactory;
+
+   private boolean tightEncodingEnabled = true;
+
+   private boolean prefixPacketSize = true;
+
+   private BrokerState brokerState;
+
+   private BrokerId brokerId;
+   protected final ProducerId advisoryProducerId = new ProducerId();
+
+   // from broker
+   protected final Map<ConnectionId, ConnectionState> brokerConnectionStates = Collections
+         .synchronizedMap(new HashMap<ConnectionId, ConnectionState>());
+
+   private final CopyOnWriteArrayList<OpenWireConnection> connections = new CopyOnWriteArrayList<OpenWireConnection>();
+
+   protected final ConcurrentHashMap<ConnectionId, ConnectionInfo> connectionInfos = new ConcurrentHashMap<ConnectionId, ConnectionInfo>();
+
+   private final Map<String, AMQConnectionContext> clientIdSet = new HashMap<String, AMQConnectionContext>();
+
+   private String brokerName;
+
+   private Map<SessionId, AMQSession> sessions = new ConcurrentHashMap<SessionId, AMQSession>();
+
+   private Map<TransactionId, AMQSession> transactions = new ConcurrentHashMap<TransactionId, AMQSession>();
+
+   public OpenWireProtocolManager(HornetQServer server)
+   {
+      this.server = server;
+      this.wireFactory = new OpenWireFormatFactory();
+      // preferred prop, should be done via config
+      wireFactory.setCacheEnabled(false);
+      brokerState = new BrokerState();
+      advisoryProducerId.setConnectionId(ID_GENERATOR.generateId());
+   }
+
+   @Override
+   public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed,
+         Connection connection)
+   {
+      OpenWireFormat wf = (OpenWireFormat) wireFactory.createWireFormat();
+      OpenWireConnection owConn = new OpenWireConnection(acceptorUsed,
+            connection, this, wf);
+      owConn.init();
+
+      return new ConnectionEntry(owConn, null, System.currentTimeMillis(),
+            1 * 60 * 1000);
+   }
+
+   @Override
+   public MessageConverter getConverter()
+   {
+      return new OpenWireMessageConverter();
+   }
+
+   @Override
+   public void removeHandler(String name)
+   {
+      // TODO Auto-generated method stub
+   }
+
+   @Override
+   public void handleBuffer(RemotingConnection connection, HornetQBuffer buffer)
+   {
+   }
+
+   @Override
+   public void addChannelHandlers(ChannelPipeline pipeline)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   @Override
+   public boolean isProtocol(byte[] array)
+   {
+      if (array.length < 8)
+      {
+         throw new IllegalArgumentException("Protocol header length changed "
+               + array.length);
+      }
+
+      int start = this.prefixPacketSize ? 4 : 0;
+      int j = 0;
+      // type
+      if (array[start] != WireFormatInfo.DATA_STRUCTURE_TYPE)
+      {
+         return false;
+      }
+      start++;
+      WireFormatInfo info = new WireFormatInfo();
+      final byte[] magic = info.getMagic();
+      int remainingLen = array.length - start;
+      int useLen = remainingLen > magic.length ? magic.length : remainingLen;
+      useLen += start;
+      // magic
+      for (int i = start; i < useLen; i++)
+      {
+         if (array[i] != magic[j])
+         {
+            return false;
+         }
+         j++;
+      }
+      return true;
+   }
+
+   @Override
+   public void handshake(NettyServerConnection connection, HornetQBuffer buffer)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   public void handleCommand(OpenWireConnection openWireConnection,
+         Object command)
+   {
+      Command amqCmd = (Command) command;
+      byte type = amqCmd.getDataStructureType();
+      switch (type)
+      {
+         case CommandTypes.CONNECTION_INFO:
+            break;
+         default:
+            throw new IllegalStateException("Cannot handle command: " + command);
+      }
+   }
+
+   public void sendReply(final OpenWireConnection connection,
+         final Command command)
+   {
+      server.getStorageManager().afterCompleteOperations(new IOAsyncTask()
+      {
+         public void onError(final int errorCode, final String errorMessage)
+         {
+            HornetQServerLogger.LOGGER.errorProcessingIOCallback(errorCode,
+                  errorMessage);
+         }
+
+         public void done()
+         {
+            send(connection, command);
+         }
+      });
+   }
+
+   public boolean send(final OpenWireConnection connection, final Command command)
+   {
+      if (HornetQServerLogger.LOGGER.isTraceEnabled())
+      {
+         HornetQServerLogger.LOGGER.trace("sending " + command);
+      }
+      synchronized (connection)
+      {
+         if (connection.isDestroyed())
+         {
+            return false;
+         }
+
+         try
+         {
+            connection.physicalSend(command);
+         }
+         catch (Exception e)
+         {
+            return false;
+         }
+         catch (Throwable t)
+         {
+            return false;
+         }
+         return true;
+      }
+   }
+
+   public Map<ConnectionId, ConnectionState> getConnectionStates()
+   {
+      return this.brokerConnectionStates;
+   }
+
+   public void addConnection(AMQConnectionContext context, ConnectionInfo info) throws Exception
+   {
+      String username = info.getUserName();
+      String password = info.getPassword();
+
+      if (!this.validateUser(username, password))
+      {
+         throw new SecurityException("User name [" + username + "] or password is invalid.");
+      }
+      String clientId = info.getClientId();
+      if (clientId == null)
+      {
+         throw new InvalidClientIDException(
+               "No clientID specified for connection request");
+      }
+      synchronized (clientIdSet)
+      {
+         AMQConnectionContext oldContext = clientIdSet.get(clientId);
+         if (oldContext != null)
+         {
+            if (context.isAllowLinkStealing())
+            {
+               clientIdSet.remove(clientId);
+               if (oldContext.getConnection() != null)
+               {
+                  OpenWireConnection connection = oldContext.getConnection();
+                  connection.disconnect(true);
+               }
+               else
+               {
+                  // log error
+               }
+            }
+            else
+            {
+               throw new InvalidClientIDException("Broker: " + getBrokerName()
+                     + " - Client: " + clientId + " already connected from "
+                     + oldContext.getConnection().getRemoteAddress());
+            }
+         }
+         else
+         {
+            clientIdSet.put(clientId, context);
+         }
+      }
+
+      connections.add(context.getConnection());
+
+      ActiveMQTopic topic = AdvisorySupport.getConnectionAdvisoryTopic();
+      // do not distribute passwords in advisory messages. usernames okay
+      ConnectionInfo copy = info.copy();
+      copy.setPassword("");
+      fireAdvisory(context, topic, copy);
+      connectionInfos.put(copy.getConnectionId(), copy);
+
+      // init the conn
+      addSessions(context.getConnection(), context.getConnectionState()
+            .getSessionIds());
+   }
+
+   private void fireAdvisory(AMQConnectionContext context, ActiveMQTopic topic,
+         Command copy) throws Exception
+   {
+      this.fireAdvisory(context, topic, copy, null);
+   }
+
+   public BrokerId getBrokerId()
+   {
+      if (brokerId == null)
+      {
+         brokerId = new BrokerId(BROKER_ID_GENERATOR.generateId());
+      }
+      return brokerId;
+   }
+
+   /*
+    * See AdvisoryBroker.fireAdvisory()
+    */
+   private void fireAdvisory(AMQConnectionContext context, ActiveMQTopic topic,
+         Command command, ConsumerId targetConsumerId) throws Exception
+   {
+      ActiveMQMessage advisoryMessage = new ActiveMQMessage();
+      advisoryMessage.setStringProperty(
+            AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_NAME, getBrokerName());
+      String id = getBrokerId() != null ? getBrokerId().getValue() : "NOT_SET";
+      advisoryMessage.setStringProperty(
+            AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_ID, id);
+
+      String url = "tcp://localhost:61616";
+
+      advisoryMessage.setStringProperty(
+            AdvisorySupport.MSG_PROPERTY_ORIGIN_BROKER_URL, url);
+
+      // set the data structure
+      advisoryMessage.setDataStructure(command);
+      advisoryMessage.setPersistent(false);
+      advisoryMessage.setType(AdvisorySupport.ADIVSORY_MESSAGE_TYPE);
+      advisoryMessage.setMessageId(new MessageId(advisoryProducerId,
+            messageIdGenerator.getNextSequenceId()));
+      advisoryMessage.setTargetConsumerId(targetConsumerId);
+      advisoryMessage.setDestination(topic);
+      advisoryMessage.setResponseRequired(false);
+      advisoryMessage.setProducerId(advisoryProducerId);
+      boolean originalFlowControl = context.isProducerFlowControl();
+      final AMQProducerBrokerExchange producerExchange = new AMQProducerBrokerExchange();
+      producerExchange.setConnectionContext(context);
+      producerExchange.setMutable(true);
+      producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
+      try
+      {
+         context.setProducerFlowControl(false);
+         AMQSession sess = context.getConnection().getAdvisorySession();
+         if (sess != null)
+         {
+            sess.send(producerExchange, advisoryMessage, false);
+         }
+      }
+      finally
+      {
+         context.setProducerFlowControl(originalFlowControl);
+      }
+   }
+
+   public String getBrokerName()
+   {
+      if (brokerName == null)
+      {
+         try
+         {
+            brokerName = InetAddressUtil.getLocalHostName().toLowerCase(
+                  Locale.ENGLISH);
+         }
+         catch (Exception e)
+         {
+            brokerName = "localhost";
+         }
+      }
+      return brokerName;
+   }
+
+   public boolean isFaultTolerantConfiguration()
+   {
+      return false;
+   }
+
+   public void postProcessDispatch(MessageDispatch md)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   public boolean isStopped()
+   {
+      // TODO Auto-generated method stub
+      return false;
+   }
+
+   public void preProcessDispatch(MessageDispatch messageDispatch)
+   {
+      // TODO Auto-generated method stub
+
+   }
+
+   public boolean isStopping()
+   {
+      return false;
+   }
+
+   public void addProducer(OpenWireConnection theConn, ProducerInfo info)
+   {
+      SessionId sessionId = info.getProducerId().getParentId();
+      ConnectionId connectionId = sessionId.getParentId();
+      AMQTransportConnectionState cs = theConn
+            .lookupConnectionState(connectionId);
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot add a producer to a connection that had not been registered: "
+                     + connectionId);
+      }
+      SessionState ss = cs.getSessionState(sessionId);
+      if (ss == null)
+      {
+         throw new IllegalStateException(
+               "Cannot add a producer to a session that had not been registered: "
+                     + sessionId);
+      }
+      // Avoid replaying dup commands
+      if (!ss.getProducerIds().contains(info.getProducerId()))
+      {
+         ActiveMQDestination destination = info.getDestination();
+         if (destination != null
+               && !AdvisorySupport.isAdvisoryTopic(destination))
+         {
+            if (theConn.getProducerCount(connectionId) >= theConn
+                  .getMaximumProducersAllowedPerConnection())
+            {
+               throw new IllegalStateException(
+                     "Can't add producer on connection " + connectionId
+                           + ": at maximum limit: "
+                           + theConn.getMaximumProducersAllowedPerConnection());
+            }
+         }
+
+         AMQSession amqSession = sessions.get(sessionId);
+         if (amqSession == null)
+         {
+            throw new IllegalStateException("Session not exist! : " + sessionId);
+         }
+
+         amqSession.createProducer(info);
+
+         try
+         {
+            ss.addProducer(info);
+         }
+         catch (IllegalStateException e)
+         {
+            amqSession.removeProducer(info);
+         }
+
+      }
+
+   }
+
+   public void addConsumer(OpenWireConnection theConn, ConsumerInfo info) throws Exception
+   {
+      // Todo: add a destination interceptors holder here (amq supports this)
+      SessionId sessionId = info.getConsumerId().getParentId();
+      ConnectionId connectionId = sessionId.getParentId();
+      AMQTransportConnectionState cs = theConn
+            .lookupConnectionState(connectionId);
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot add a consumer to a connection that had not been registered: "
+                     + connectionId);
+      }
+      SessionState ss = cs.getSessionState(sessionId);
+      if (ss == null)
+      {
+         throw new IllegalStateException(
+               this.server
+                     + " Cannot add a consumer to a session that had not been registered: "
+                     + sessionId);
+      }
+      // Avoid replaying dup commands
+      if (!ss.getConsumerIds().contains(info.getConsumerId()))
+      {
+         ActiveMQDestination destination = info.getDestination();
+         if (destination != null
+               && !AdvisorySupport.isAdvisoryTopic(destination))
+         {
+            if (theConn.getConsumerCount(connectionId) >= theConn
+                  .getMaximumConsumersAllowedPerConnection())
+            {
+               throw new IllegalStateException(
+                     "Can't add consumer on connection " + connectionId
+                           + ": at maximum limit: "
+                           + theConn.getMaximumConsumersAllowedPerConnection());
+            }
+         }
+
+         AMQSession amqSession = sessions.get(sessionId);
+         if (amqSession == null)
+         {
+            throw new IllegalStateException("Session not exist! : " + sessionId);
+         }
+
+         amqSession.createConsumer(info);
+
+         try
+         {
+            ss.addConsumer(info);
+            theConn.addConsumerBrokerExchange(info.getConsumerId());
+         }
+         catch (IllegalStateException e)
+         {
+            amqSession.removeConsumer(info);
+         }
+      }
+   }
+
+   public void addSessions(OpenWireConnection theConn, Set<SessionId> sessionSet)
+   {
+      Iterator<SessionId> iter = sessionSet.iterator();
+      while (iter.hasNext())
+      {
+         SessionId sid = iter.next();
+         addSession(theConn, theConn.getState().getSessionState(sid).getInfo(),
+               true);
+      }
+   }
+
+   public AMQSession addSession(OpenWireConnection theConn, SessionInfo ss)
+   {
+      return addSession(theConn, ss, false);
+   }
+
+   public AMQSession addSession(OpenWireConnection theConn, SessionInfo ss,
+         boolean internal)
+   {
+      AMQSession amqSession = new AMQSession(theConn.getState().getInfo(), ss,
+            server, theConn, this);
+      amqSession.initialize();
+      amqSession.setInternal(internal);
+      sessions.put(ss.getSessionId(), amqSession);
+      return amqSession;
+   }
+
+   public void removeConnection(AMQConnectionContext context,
+         ConnectionInfo info, Throwable error)
+   {
+      // todo roll back tx
+      this.connections.remove(context.getConnection());
+      this.connectionInfos.remove(info.getConnectionId());
+      String clientId = info.getClientId();
+      if (clientId != null)
+      {
+         this.clientIdSet.remove(clientId);
+      }
+   }
+
+   public void removeSession(AMQConnectionContext context, SessionInfo info) throws Exception
+   {
+      AMQSession session = sessions.remove(info.getSessionId());
+      if (session != null)
+      {
+         session.close();
+      }
+   }
+
+   public void removeConsumer(AMQConnectionContext context, ConsumerInfo info) throws Exception
+   {
+      SessionId sessionId = info.getConsumerId().getParentId();
+      AMQSession session = sessions.get(sessionId);
+      session.removeConsumer(info);
+   }
+
+   public void removeProducer(ProducerId id)
+   {
+      SessionId sessionId = id.getParentId();
+      AMQSession session = sessions.get(sessionId);
+      session.removeProducer(id);
+   }
+
+   public AMQPersistenceAdapter getPersistenceAdapter()
+   {
+      // TODO Auto-generated method stub
+      return null;
+   }
+
+   public AMQSession getSession(SessionId sessionId)
+   {
+      return sessions.get(sessionId);
+   }
+
+   public void addDestination(OpenWireConnection connection,
+         DestinationInfo info) throws Exception
+   {
+      ActiveMQDestination dest = info.getDestination();
+      if (dest.isQueue())
+      {
+         SimpleString qName = new SimpleString("jms.queue."
+               + dest.getPhysicalName());
+         ConnectionState state = connection.brokerConnectionStates.get(info.getConnectionId());
+         ConnectionInfo connInfo = state.getInfo();
+         if (connInfo != null)
+         {
+            String user = connInfo.getUserName();
+            String pass = connInfo.getPassword();
+
+            AMQServerSession fakeSession = new AMQServerSession(user, pass);
+            CheckType checkType = dest.isTemporary() ? CheckType.CREATE_NON_DURABLE_QUEUE : CheckType.CREATE_DURABLE_QUEUE;
+            ((HornetQServerImpl)server).getSecurityStore().check(qName, checkType, fakeSession);
+         }
+         this.server.createQueue(qName, qName, null, false, true);
+         if (dest.isTemporary())
+         {
+            connection.registerTempQueue(qName);
+         }
+      }
+
+      if (!AdvisorySupport.isAdvisoryTopic(dest))
+      {
+         AMQConnectionContext context = connection.getConext();
+         DestinationInfo advInfo = new DestinationInfo(context.getConnectionId(), DestinationInfo.ADD_OPERATION_TYPE, dest);
+
+         ActiveMQTopic topic = AdvisorySupport.getDestinationAdvisoryTopic(dest);
+         fireAdvisory(context, topic, advInfo);
+      }
+   }
+
+   public void deleteQueue(String q) throws Exception
+   {
+      server.destroyQueue(new SimpleString(q));
+   }
+
+   public void commitTransactionOnePhase(TransactionInfo info) throws Exception
+   {
+      AMQSession txSession = transactions.get(info.getTransactionId());
+
+      if (txSession != null)
+      {
+         txSession.commitOnePhase(info);
+      }
+      transactions.remove(info.getTransactionId());
+   }
+
+   public void prepareTransaction(TransactionInfo info) throws Exception
+   {
+      XATransactionId xid = (XATransactionId) info.getTransactionId();
+      AMQSession txSession = transactions.get(xid);
+      if (txSession != null)
+      {
+         txSession.prepareTransaction(xid);
+      }
+   }
+
+   public void commitTransactionTwoPhase(TransactionInfo info) throws Exception
+   {
+      XATransactionId xid = (XATransactionId) info.getTransactionId();
+      AMQSession txSession = transactions.get(xid);
+      if (txSession != null)
+      {
+         txSession.commitTwoPhase(xid);
+      }
+      transactions.remove(xid);
+   }
+
+   public void rollbackTransaction(TransactionInfo info) throws Exception
+   {
+      AMQSession txSession = transactions.get(info.getTransactionId());
+      if (txSession != null)
+      {
+         txSession.rollback(info);
+      }
+      transactions.remove(info.getTransactionId());
+   }
+
+   public TransactionId[] recoverTransactions(Set<SessionId> sIds)
+   {
+      List<TransactionId> recovered = new ArrayList<TransactionId>();
+      if (sIds != null)
+      {
+         for (SessionId sid : sIds)
+         {
+            AMQSession s = this.sessions.get(sid);
+            if (s != null)
+            {
+               s.recover(recovered);
+            }
+         }
+      }
+      return recovered.toArray(new TransactionId[0]);
+   }
+
+   public boolean validateUser(String login, String passcode)
+   {
+      boolean validated = true;
+
+      HornetQSecurityManager sm = server.getSecurityManager();
+
+      if (sm != null && server.getConfiguration().isSecurityEnabled())
+      {
+         validated = sm.validateUser(login, passcode);
+      }
+
+      return validated;
+   }
+
+   public void forgetTransaction(TransactionId xid) throws Exception
+   {
+      AMQSession txSession = transactions.get(xid);
+      if (txSession != null)
+      {
+         txSession.forget(xid);
+      }
+      transactions.remove(xid);
+   }
+
+   public void registerTx(TransactionId txId, AMQSession amqSession)
+   {
+      transactions.put(txId, amqSession);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManagerFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManagerFactory.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManagerFactory.java
new file mode 100644
index 0000000..f8542bc
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireProtocolManagerFactory.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import java.util.List;
+
+import org.hornetq.api.core.Interceptor;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.spi.core.protocol.ProtocolManager;
+import org.hornetq.spi.core.protocol.ProtocolManagerFactory;
+
+/**
+ * A OpenWireProtocolManagerFactory
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ *
+ */
+public class OpenWireProtocolManagerFactory implements ProtocolManagerFactory
+{
+   public static final String OPENWIRE_PROTOCOL_NAME = "OPENWIRE";
+
+   private static String[] SUPPORTED_PROTOCOLS = {OPENWIRE_PROTOCOL_NAME};
+
+   public ProtocolManager createProtocolManager(final HornetQServer server, final List<Interceptor> incomingInterceptors, List<Interceptor> outgoingInterceptors)
+   {
+      return new OpenWireProtocolManager(server);
+   }
+
+   @Override
+   public String[] getProtocols()
+   {
+      return SUPPORTED_PROTOCOLS;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireUtil.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireUtil.java
new file mode 100644
index 0000000..8662dc1
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireUtil.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.util.ByteSequence;
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.HornetQBuffers;
+import org.hornetq.api.core.SimpleString;
+
+public class OpenWireUtil
+{
+
+   public static HornetQBuffer toHornetQBuffer(ByteSequence bytes)
+   {
+      HornetQBuffer buffer = HornetQBuffers.fixedBuffer(bytes.length);
+
+      buffer.writeBytes(bytes.data, bytes.offset, bytes.length);
+      return buffer;
+   }
+
+
+   public static SimpleString toCoreAddress(ActiveMQDestination dest)
+   {
+      if (dest.isQueue())
+      {
+         return new SimpleString("jms.queue." + dest.getPhysicalName());
+      }
+      else
+      {
+         return new SimpleString("jms.topic." + dest.getPhysicalName());
+      }
+   }
+
+   /*
+    *This util converts amq wildcards to compatible core wildcards
+    *The conversion is like this:
+    *AMQ * wildcard --> Core * wildcard (no conversion)
+    *AMQ > wildcard --> Core # wildcard
+    */
+   public static String convertWildcard(String physicalName)
+   {
+      return physicalName.replaceAll("(\\.>)+", ".#");
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/SendingResult.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/SendingResult.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/SendingResult.java
new file mode 100644
index 0000000..158bc62
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/SendingResult.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.paging.impl.PagingStoreImpl;
+import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
+
+/**
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ */
+public class SendingResult
+{
+   private boolean blockNextSend;
+   private PagingStoreImpl blockPagingStore;
+   private SimpleString blockingAddress;
+
+   public void setBlockNextSend(boolean block)
+   {
+      this.blockNextSend = block;
+   }
+
+   public boolean isBlockNextSend()
+   {
+      return this.blockNextSend;
+   }
+
+   public void setBlockPagingStore(PagingStoreImpl store)
+   {
+      this.blockPagingStore = store;
+   }
+
+   public PagingStoreImpl getBlockPagingStore()
+   {
+      return this.blockPagingStore;
+   }
+
+   public void setBlockingAddress(SimpleString address)
+   {
+      this.blockingAddress = address;
+   }
+
+   public SimpleString getBlockingAddress()
+   {
+      return this.blockingAddress;
+   }
+
+   public boolean isSendFailIfNoSpace()
+   {
+      AddressFullMessagePolicy policy = this.blockPagingStore.getAddressFullMessagePolicy();
+      return policy == AddressFullMessagePolicy.FAIL;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java
new file mode 100644
index 0000000..29c490f
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQAbstractDeadLetterStrategy.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.ActiveMQMessageAudit;
+import org.apache.activemq.command.Message;
+
+public abstract class AMQAbstractDeadLetterStrategy implements AMQDeadLetterStrategy
+{
+   private boolean processNonPersistent = false;
+   private boolean processExpired = true;
+   private boolean enableAudit = true;
+   private final ActiveMQMessageAudit messageAudit = new ActiveMQMessageAudit();
+
+   @Override
+   public void rollback(Message message)
+   {
+      if (message != null && this.enableAudit)
+      {
+         messageAudit.rollback(message);
+      }
+   }
+
+   @Override
+   public boolean isSendToDeadLetterQueue(Message message)
+   {
+      boolean result = false;
+      if (message != null)
+      {
+         result = true;
+         if (enableAudit && messageAudit.isDuplicate(message))
+         {
+            result = false;
+            // LOG.debug("Not adding duplicate to DLQ: {}, dest: {}",
+            // message.getMessageId(), message.getDestination());
+         }
+         if (!message.isPersistent() && !processNonPersistent)
+         {
+            result = false;
+         }
+         if (message.isExpired() && !processExpired)
+         {
+            result = false;
+         }
+      }
+      return result;
+   }
+
+   /**
+    * @return the processExpired
+    */
+   @Override
+   public boolean isProcessExpired()
+   {
+      return this.processExpired;
+   }
+
+   /**
+    * @param processExpired
+    *           the processExpired to set
+    */
+   @Override
+   public void setProcessExpired(boolean processExpired)
+   {
+      this.processExpired = processExpired;
+   }
+
+   /**
+    * @return the processNonPersistent
+    */
+   @Override
+   public boolean isProcessNonPersistent()
+   {
+      return this.processNonPersistent;
+   }
+
+   /**
+    * @param processNonPersistent
+    *           the processNonPersistent to set
+    */
+   @Override
+   public void setProcessNonPersistent(boolean processNonPersistent)
+   {
+      this.processNonPersistent = processNonPersistent;
+   }
+
+   public boolean isEnableAudit()
+   {
+      return enableAudit;
+   }
+
+   public void setEnableAudit(boolean enableAudit)
+   {
+      this.enableAudit = enableAudit;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQBrokerStoppedException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQBrokerStoppedException.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQBrokerStoppedException.java
new file mode 100644
index 0000000..22eb20e
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQBrokerStoppedException.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+public class AMQBrokerStoppedException extends IllegalStateException
+{
+
+   private static final long serialVersionUID = -7543507221414251115L;
+
+   public AMQBrokerStoppedException()
+   {
+      super();
+   }
+
+   public AMQBrokerStoppedException(String message, Throwable cause)
+   {
+      super(message);
+      initCause(cause);
+   }
+
+   public AMQBrokerStoppedException(String s)
+   {
+      super(s);
+   }
+
+   public AMQBrokerStoppedException(Throwable cause)
+   {
+      initCause(cause);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectionContext.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectionContext.java
new file mode 100644
index 0000000..435d3b9
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectionContext.java
@@ -0,0 +1,393 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.io.IOException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.activemq.broker.region.MessageReference;
+import org.apache.activemq.command.ConnectionId;
+import org.apache.activemq.command.ConnectionInfo;
+import org.apache.activemq.command.TransactionId;
+import org.apache.activemq.command.WireFormatInfo;
+import org.apache.activemq.command.XATransactionId;
+import org.apache.activemq.filter.MessageEvaluationContext;
+import org.apache.activemq.state.ConnectionState;
+import org.hornetq.core.protocol.openwire.OpenWireConnection;
+import org.hornetq.core.protocol.openwire.OpenWireProtocolManager;
+
+public class AMQConnectionContext
+{
+   private OpenWireConnection connection;
+   private AMQConnector connector;
+   private OpenWireProtocolManager broker; //use protocol manager to represent the broker
+   private boolean inRecoveryMode;
+   private AMQTransaction transaction;
+   private ConcurrentHashMap<TransactionId, AMQTransaction> transactions;
+   private AMQSecurityContext securityContext;
+   private ConnectionId connectionId;
+   private String clientId;
+   private String userName;
+   private boolean reconnect;
+   private WireFormatInfo wireFormatInfo;
+   private Object longTermStoreContext;
+   private boolean producerFlowControl = true;
+   private AMQMessageAuthorizationPolicy messageAuthorizationPolicy;
+   private boolean networkConnection;
+   private boolean faultTolerant;
+   private final AtomicBoolean stopping = new AtomicBoolean();
+   private final MessageEvaluationContext messageEvaluationContext;
+   private boolean dontSendReponse;
+   private boolean clientMaster = true;
+   private ConnectionState connectionState;
+   private XATransactionId xid;
+
+   public AMQConnectionContext()
+   {
+      this.messageEvaluationContext = new MessageEvaluationContext();
+   }
+
+   public AMQConnectionContext(MessageEvaluationContext messageEvaluationContext)
+   {
+      this.messageEvaluationContext = messageEvaluationContext;
+   }
+
+   public AMQConnectionContext(ConnectionInfo info)
+   {
+      this();
+      setClientId(info.getClientId());
+      setUserName(info.getUserName());
+      setConnectionId(info.getConnectionId());
+   }
+
+   public AMQConnectionContext copy()
+   {
+      AMQConnectionContext rc = new AMQConnectionContext(
+            this.messageEvaluationContext);
+      rc.connection = this.connection;
+      rc.connector = this.connector;
+      rc.broker = this.broker;
+      rc.inRecoveryMode = this.inRecoveryMode;
+      rc.transaction = this.transaction;
+      rc.transactions = this.transactions;
+      rc.securityContext = this.securityContext;
+      rc.connectionId = this.connectionId;
+      rc.clientId = this.clientId;
+      rc.userName = this.userName;
+      rc.reconnect = this.reconnect;
+      rc.wireFormatInfo = this.wireFormatInfo;
+      rc.longTermStoreContext = this.longTermStoreContext;
+      rc.producerFlowControl = this.producerFlowControl;
+      rc.messageAuthorizationPolicy = this.messageAuthorizationPolicy;
+      rc.networkConnection = this.networkConnection;
+      rc.faultTolerant = this.faultTolerant;
+      rc.stopping.set(this.stopping.get());
+      rc.dontSendReponse = this.dontSendReponse;
+      rc.clientMaster = this.clientMaster;
+      return rc;
+   }
+
+   public AMQSecurityContext getSecurityContext()
+   {
+      return securityContext;
+   }
+
+   public void setSecurityContext(AMQSecurityContext subject)
+   {
+      this.securityContext = subject;
+      if (subject != null)
+      {
+         setUserName(subject.getUserName());
+      }
+      else
+      {
+         setUserName(null);
+      }
+   }
+
+   /**
+    * @return the broker being used.
+    */
+   public OpenWireProtocolManager getBroker()
+   {
+      return broker;
+   }
+
+   /**
+    * @param broker
+    *           being used
+    */
+   public void setBroker(OpenWireProtocolManager broker)
+   {
+      this.broker = broker;
+   }
+
+   /**
+    * @return the connection being used
+    */
+   public OpenWireConnection getConnection()
+   {
+      return connection;
+   }
+
+   /**
+    * @param connection
+    *           being used
+    */
+   public void setConnection(OpenWireConnection connection)
+   {
+      this.connection = connection;
+   }
+
+   /**
+    * @return the transaction being used.
+    */
+   public AMQTransaction getTransaction()
+   {
+      return transaction;
+   }
+
+   /**
+    * @param transaction
+    *           being used.
+    */
+   public void setTransaction(AMQTransaction transaction)
+   {
+      this.transaction = transaction;
+   }
+
+   /**
+    * @return the connector being used.
+    */
+   public AMQConnector getConnector()
+   {
+      return connector;
+   }
+
+   /**
+    * @param connector
+    *           being used.
+    */
+   public void setConnector(AMQConnector connector)
+   {
+      this.connector = connector;
+   }
+
+   public AMQMessageAuthorizationPolicy getMessageAuthorizationPolicy()
+   {
+      return messageAuthorizationPolicy;
+   }
+
+   /**
+    * Sets the policy used to decide if the current connection is authorized to
+    * consume a given message
+    */
+   public void setMessageAuthorizationPolicy(
+         AMQMessageAuthorizationPolicy messageAuthorizationPolicy)
+   {
+      this.messageAuthorizationPolicy = messageAuthorizationPolicy;
+   }
+
+   /**
+    * @return
+    */
+   public boolean isInRecoveryMode()
+   {
+      return inRecoveryMode;
+   }
+
+   public void setInRecoveryMode(boolean inRecoveryMode)
+   {
+      this.inRecoveryMode = inRecoveryMode;
+   }
+
+   public ConcurrentHashMap<TransactionId, AMQTransaction> getTransactions()
+   {
+      return transactions;
+   }
+
+   public void setTransactions(
+         ConcurrentHashMap<TransactionId, AMQTransaction> transactions)
+   {
+      this.transactions = transactions;
+   }
+
+   public boolean isInTransaction()
+   {
+      return transaction != null;
+   }
+
+   public String getClientId()
+   {
+      return clientId;
+   }
+
+   public void setClientId(String clientId)
+   {
+      this.clientId = clientId;
+   }
+
+   public boolean isReconnect()
+   {
+      return reconnect;
+   }
+
+   public void setReconnect(boolean reconnect)
+   {
+      this.reconnect = reconnect;
+   }
+
+   public WireFormatInfo getWireFormatInfo()
+   {
+      return wireFormatInfo;
+   }
+
+   public void setWireFormatInfo(WireFormatInfo wireFormatInfo)
+   {
+      this.wireFormatInfo = wireFormatInfo;
+   }
+
+   public ConnectionId getConnectionId()
+   {
+      return connectionId;
+   }
+
+   public void setConnectionId(ConnectionId connectionId)
+   {
+      this.connectionId = connectionId;
+   }
+
+   public String getUserName()
+   {
+      return userName;
+   }
+
+   public void setUserName(String userName)
+   {
+      this.userName = userName;
+   }
+
+   public MessageEvaluationContext getMessageEvaluationContext()
+   {
+      return messageEvaluationContext;
+   }
+
+   public Object getLongTermStoreContext()
+   {
+      return longTermStoreContext;
+   }
+
+   public void setLongTermStoreContext(Object longTermStoreContext)
+   {
+      this.longTermStoreContext = longTermStoreContext;
+   }
+
+   public boolean isProducerFlowControl()
+   {
+      return producerFlowControl;
+   }
+
+   public void setProducerFlowControl(boolean disableProducerFlowControl)
+   {
+      this.producerFlowControl = disableProducerFlowControl;
+   }
+
+   public boolean isAllowedToConsume(MessageReference n) throws IOException
+   {
+      if (messageAuthorizationPolicy != null)
+      {
+         return messageAuthorizationPolicy.isAllowedToConsume(this,
+               n.getMessage());
+      }
+      return true;
+   }
+
+   public synchronized boolean isNetworkConnection()
+   {
+      return networkConnection;
+   }
+
+   public synchronized void setNetworkConnection(boolean networkConnection)
+   {
+      this.networkConnection = networkConnection;
+   }
+
+   public AtomicBoolean getStopping()
+   {
+      return stopping;
+   }
+
+   public void setDontSendReponse(boolean b)
+   {
+      this.dontSendReponse = b;
+   }
+
+   public boolean isDontSendReponse()
+   {
+      return dontSendReponse;
+   }
+
+   /**
+    * @return the clientMaster
+    */
+   public boolean isClientMaster()
+   {
+      return this.clientMaster;
+   }
+
+   /**
+    * @param clientMaster
+    *           the clientMaster to set
+    */
+   public void setClientMaster(boolean clientMaster)
+   {
+      this.clientMaster = clientMaster;
+   }
+
+   public boolean isFaultTolerant()
+   {
+      return faultTolerant;
+   }
+
+   public void setFaultTolerant(boolean faultTolerant)
+   {
+      this.faultTolerant = faultTolerant;
+   }
+
+   public void setConnectionState(ConnectionState connectionState)
+   {
+      this.connectionState = connectionState;
+   }
+
+   public ConnectionState getConnectionState()
+   {
+      return this.connectionState;
+   }
+
+   public void setXid(XATransactionId id)
+   {
+      this.xid = id;
+   }
+
+   public XATransactionId getXid()
+   {
+      return xid;
+   }
+
+   public boolean isAllowLinkStealing()
+   {
+      return connector != null && connector.isAllowLinkStealing();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnector.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnector.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnector.java
new file mode 100644
index 0000000..e256736
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnector.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.command.BrokerInfo;
+import org.apache.activemq.command.ConnectionControl;
+import org.hornetq.core.protocol.openwire.OpenWireConnection;
+
+public interface AMQConnector
+{
+   /**
+    * @return brokerInfo
+    */
+   BrokerInfo getBrokerInfo();
+
+   /**
+    * @return the statistics for this connector
+    */
+   AMQConnectorStatistics getStatistics();
+
+   /**
+    * @return true if update client connections when brokers leave/join a
+    *         cluster
+    */
+   boolean isUpdateClusterClients();
+
+   /**
+    * @return true if clients should be re-balanced across the cluster
+    */
+   boolean isRebalanceClusterClients();
+
+   /**
+    * Update all the connections with information about the connected brokers in
+    * the cluster
+    */
+   void updateClientClusterInfo();
+
+   /**
+    * @return true if clients should be updated when a broker is removed from a
+    *         broker
+    */
+   boolean isUpdateClusterClientsOnRemove();
+
+   int connectionCount();
+
+   /**
+    * If enabled, older connections with the same clientID are stopped
+    *
+    * @return true/false if link stealing is enabled
+    */
+   boolean isAllowLinkStealing();
+
+   //see TransportConnector
+   ConnectionControl getConnectionControl();
+
+   void onStarted(OpenWireConnection connection);
+
+   void onStopped(OpenWireConnection connection);
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectorStatistics.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectorStatistics.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectorStatistics.java
new file mode 100644
index 0000000..ffe477b
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConnectorStatistics.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.management.CountStatisticImpl;
+import org.apache.activemq.management.PollCountStatisticImpl;
+import org.apache.activemq.management.StatsImpl;
+
+public class AMQConnectorStatistics extends StatsImpl
+{
+
+   protected CountStatisticImpl enqueues;
+   protected CountStatisticImpl dequeues;
+   protected CountStatisticImpl consumers;
+   protected CountStatisticImpl messages;
+   protected PollCountStatisticImpl messagesCached;
+
+   public AMQConnectorStatistics()
+   {
+
+      enqueues = new CountStatisticImpl("enqueues",
+            "The number of messages that have been sent to the destination");
+      dequeues = new CountStatisticImpl("dequeues",
+            "The number of messages that have been dispatched from the destination");
+      consumers = new CountStatisticImpl(
+            "consumers",
+            "The number of consumers that that are subscribing to messages from the destination");
+      messages = new CountStatisticImpl("messages",
+            "The number of messages that that are being held by the destination");
+      messagesCached = new PollCountStatisticImpl("messagesCached",
+            "The number of messages that are held in the destination's memory cache");
+
+      addStatistic("enqueues", enqueues);
+      addStatistic("dequeues", dequeues);
+      addStatistic("consumers", consumers);
+      addStatistic("messages", messages);
+      addStatistic("messagesCached", messagesCached);
+   }
+
+   public CountStatisticImpl getEnqueues()
+   {
+      return enqueues;
+   }
+
+   public CountStatisticImpl getDequeues()
+   {
+      return dequeues;
+   }
+
+   public CountStatisticImpl getConsumers()
+   {
+      return consumers;
+   }
+
+   public PollCountStatisticImpl getMessagesCached()
+   {
+      return messagesCached;
+   }
+
+   public CountStatisticImpl getMessages()
+   {
+      return messages;
+   }
+
+   public void reset()
+   {
+      super.reset();
+      enqueues.reset();
+      dequeues.reset();
+   }
+
+   public void setEnabled(boolean enabled)
+   {
+      super.setEnabled(enabled);
+      enqueues.setEnabled(enabled);
+      dequeues.setEnabled(enabled);
+      consumers.setEnabled(enabled);
+      messages.setEnabled(enabled);
+      messagesCached.setEnabled(enabled);
+   }
+
+   public void setParent(AMQConnectorStatistics parent)
+   {
+      if (parent != null)
+      {
+         enqueues.setParent(parent.enqueues);
+         dequeues.setParent(parent.dequeues);
+         consumers.setParent(parent.consumers);
+         messagesCached.setParent(parent.messagesCached);
+         messages.setParent(parent.messages);
+      }
+      else
+      {
+         enqueues.setParent(null);
+         dequeues.setParent(null);
+         consumers.setParent(null);
+         messagesCached.setParent(null);
+         messages.setParent(null);
+      }
+   }
+
+   public void setMessagesCached(PollCountStatisticImpl messagesCached)
+   {
+      this.messagesCached = messagesCached;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumer.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumer.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumer.java
new file mode 100644
index 0000000..60e1ec2
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumer.java
@@ -0,0 +1,390 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.ConsumerInfo;
+import org.apache.activemq.command.MessageAck;
+import org.apache.activemq.command.MessageDispatch;
+import org.apache.activemq.command.MessageId;
+import org.apache.activemq.command.TransactionId;
+import org.apache.activemq.wireformat.WireFormat;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.protocol.openwire.OpenWireMessageConverter;
+import org.hornetq.core.protocol.openwire.OpenWireUtil;
+import org.hornetq.core.server.QueueQueryResult;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.jms.client.HornetQDestination;
+
+public class AMQConsumer implements BrowserListener
+{
+   private AMQSession session;
+   private ActiveMQDestination actualDest;
+   private ConsumerInfo info;
+   private long nativeId = -1;
+   private SimpleString subQueueName = null;
+
+   private final int prefetchSize;
+   private AtomicInteger currentSize;
+   private final java.util.Queue<MessageInfo> deliveringRefs = new ConcurrentLinkedQueue<MessageInfo>();
+
+   public AMQConsumer(AMQSession amqSession, ActiveMQDestination d, ConsumerInfo info)
+   {
+      this.session = amqSession;
+      this.actualDest = d;
+      this.info = info;
+      this.prefetchSize = info.getPrefetchSize();
+      this.currentSize = new AtomicInteger(0);
+   }
+
+   public void init() throws Exception
+   {
+      AMQServerSession coreSession = session.getCoreSession();
+
+      SimpleString selector = info.getSelector() == null ? null : new SimpleString(info.getSelector());
+
+      nativeId = session.getCoreServer().getStorageManager().generateID();
+
+      SimpleString address = new SimpleString(this.actualDest.getPhysicalName());
+
+      if (this.actualDest.isTopic())
+      {
+         String physicalName = this.actualDest.getPhysicalName();
+         if (physicalName.contains(".>"))
+         {
+            //wildcard
+            physicalName = OpenWireUtil.convertWildcard(physicalName);
+         }
+
+         // on recreate we don't need to create queues
+         address = new SimpleString("jms.topic." + physicalName);
+         if (info.isDurable())
+         {
+            subQueueName = new SimpleString(
+                  HornetQDestination.createQueueNameForDurableSubscription(
+                        true, info.getClientId(), info.getSubscriptionName()));
+
+            QueueQueryResult result = coreSession.executeQueueQuery(subQueueName);
+            if (result.isExists())
+            {
+               // Already exists
+               if (result.getConsumerCount() > 0)
+               {
+                  throw new IllegalStateException(
+                        "Cannot create a subscriber on the durable subscription since it already has subscriber(s)");
+               }
+
+               SimpleString oldFilterString = result.getFilterString();
+
+               boolean selectorChanged = selector == null
+                     && oldFilterString != null || oldFilterString == null
+                     && selector != null || oldFilterString != null
+                     && selector != null && !oldFilterString.equals(selector);
+
+               SimpleString oldTopicName = result.getAddress();
+
+               boolean topicChanged = !oldTopicName.equals(address);
+
+               if (selectorChanged || topicChanged)
+               {
+                  // Delete the old durable sub
+                  coreSession.deleteQueue(subQueueName);
+
+                  // Create the new one
+                  coreSession.createQueue(address, subQueueName, selector,
+                        false, true);
+               }
+
+            }
+            else
+            {
+               coreSession.createQueue(address, subQueueName, selector, false,
+                     true);
+            }
+         }
+         else
+         {
+            subQueueName = new SimpleString(UUID.randomUUID().toString());
+
+            coreSession.createQueue(address, subQueueName, selector, true, false);
+         }
+
+         coreSession.createConsumer(nativeId, subQueueName, null, info.isBrowser(), false, Integer.MAX_VALUE);
+      }
+      else
+      {
+         SimpleString queueName = new SimpleString("jms.queue." + this.actualDest.getPhysicalName());
+         coreSession.createConsumer(nativeId, queueName, selector, info.isBrowser(), false, Integer.MAX_VALUE);
+      }
+
+      if (info.isBrowser())
+      {
+         AMQServerConsumer coreConsumer = coreSession.getConsumer(nativeId);
+         coreConsumer.setBrowserListener(this);
+      }
+
+   }
+
+   public long getNativeId()
+   {
+      return this.nativeId;
+   }
+
+   public ConsumerId getId()
+   {
+      return info.getConsumerId();
+   }
+
+   public WireFormat getMarshaller()
+   {
+      return this.session.getMarshaller();
+   }
+
+   public void acquireCredit(int n) throws Exception
+   {
+      this.currentSize.addAndGet(-n);
+      if (currentSize.get() < prefetchSize)
+      {
+         AtomicInteger credits = session.getCoreSession().getConsumerCredits(nativeId);
+         credits.set(0);
+         session.getCoreSession().receiveConsumerCredits(nativeId, Integer.MAX_VALUE);
+      }
+   }
+
+   public void checkCreditOnDelivery() throws Exception
+   {
+      this.currentSize.incrementAndGet();
+
+      if (currentSize.get() == prefetchSize)
+      {
+         //stop because reach prefetchSize
+         session.getCoreSession().receiveConsumerCredits(nativeId, 0);
+      }
+   }
+
+   public int handleDeliver(ServerMessage message, int deliveryCount)
+   {
+      MessageDispatch dispatch;
+      try
+      {
+         //decrement deliveryCount as AMQ client tends to add 1.
+         dispatch = OpenWireMessageConverter.createMessageDispatch(message, deliveryCount - 1, this);
+         int size = dispatch.getMessage().getSize();
+         this.deliveringRefs.add(new MessageInfo(dispatch.getMessage().getMessageId(), message.getMessageID(), size));
+         session.deliverMessage(dispatch);
+         checkCreditOnDelivery();
+         return size;
+      }
+      catch (IOException e)
+      {
+         return 0;
+      }
+      catch (Throwable t)
+      {
+         return 0;
+      }
+   }
+
+   public void acknowledge(MessageAck ack) throws Exception
+   {
+      MessageId first = ack.getFirstMessageId();
+      MessageId lastm = ack.getLastMessageId();
+      TransactionId tid = ack.getTransactionId();
+      boolean isLocalTx = (tid != null) && tid.isLocalTransaction();
+      boolean single = lastm.equals(first);
+
+      MessageInfo mi = null;
+      int n = 0;
+
+      if (ack.isIndividualAck())
+      {
+         Iterator<MessageInfo> iter = deliveringRefs.iterator();
+         while (iter.hasNext())
+         {
+            mi = iter.next();
+            if (mi.amqId.equals(lastm))
+            {
+               n++;
+               iter.remove();
+               session.getCoreSession().individualAcknowledge(nativeId, mi.nativeId);
+               session.getCoreSession().commit();
+               break;
+            }
+         }
+      }
+      else if (ack.isRedeliveredAck())
+      {
+         //client tells that this message is for redlivery.
+         //do nothing until poisoned.
+         n = 1;
+      }
+      else if (ack.isPoisonAck())
+      {
+         //send to dlq
+         Iterator<MessageInfo> iter = deliveringRefs.iterator();
+         boolean firstFound = false;
+         while (iter.hasNext())
+         {
+            mi = iter.next();
+            if (mi.amqId.equals(first))
+            {
+               n++;
+               iter.remove();
+               session.getCoreSession().moveToDeadLetterAddress(nativeId, mi.nativeId, ack.getPoisonCause());
+               session.getCoreSession().commit();
+               if (single)
+               {
+                  break;
+               }
+               firstFound = true;
+            }
+            else if (firstFound || first == null)
+            {
+               n++;
+               iter.remove();
+               session.getCoreSession().moveToDeadLetterAddress(nativeId, mi.nativeId, ack.getPoisonCause());
+               session.getCoreSession().commit();
+               if (mi.amqId.equals(lastm))
+               {
+                  break;
+               }
+            }
+         }
+      }
+      else if (ack.isDeliveredAck() || ack.isExpiredAck())
+      {
+         //ToDo: implement with tests
+         n = 1;
+      }
+      else
+      {
+         Iterator<MessageInfo> iter = deliveringRefs.iterator();
+         boolean firstFound = false;
+         while (iter.hasNext())
+         {
+            MessageInfo ami = iter.next();
+            if (ami.amqId.equals(first))
+            {
+               n++;
+               if (!isLocalTx)
+               {
+                  iter.remove();
+               }
+               else
+               {
+                  ami.setLocalAcked(true);
+               }
+               if (single)
+               {
+                  mi = ami;
+                  break;
+               }
+               firstFound = true;
+            }
+            else if (firstFound || first == null)
+            {
+               n++;
+               if (!isLocalTx)
+               {
+                  iter.remove();
+               }
+               else
+               {
+                  ami.setLocalAcked(true);
+               }
+               if (ami.amqId.equals(lastm))
+               {
+                  mi = ami;
+                  break;
+               }
+            }
+         }
+         if (mi != null && !isLocalTx)
+         {
+            session.getCoreSession().acknowledge(nativeId, mi.nativeId);
+         }
+      }
+
+      acquireCredit(n);
+   }
+
+   @Override
+   public void browseFinished()
+   {
+      MessageDispatch md = new MessageDispatch();
+      md.setConsumerId(info.getConsumerId());
+      md.setMessage(null);
+      md.setDestination(null);
+
+      session.deliverMessage(md);
+   }
+
+   public boolean handledTransactionalMsg()
+   {
+      // TODO Auto-generated method stub
+      return false;
+   }
+
+   //this is called before session commit a local tx
+   public void finishTx() throws Exception
+   {
+      MessageInfo lastMi = null;
+
+      MessageInfo mi = null;
+      Iterator<MessageInfo> iter = deliveringRefs.iterator();
+      while (iter.hasNext())
+      {
+         mi = iter.next();
+         if (mi.isLocalAcked())
+         {
+            iter.remove();
+            lastMi = mi;
+         }
+      }
+
+      if (lastMi != null)
+      {
+         session.getCoreSession().acknowledge(nativeId, lastMi.nativeId);
+      }
+   }
+
+   public void rollbackTx(Set<Long> acked) throws Exception
+   {
+      MessageInfo lastMi = null;
+
+      MessageInfo mi = null;
+      Iterator<MessageInfo> iter = deliveringRefs.iterator();
+      while (iter.hasNext())
+      {
+         mi = iter.next();
+         if (mi.isLocalAcked())
+         {
+            acked.add(mi.nativeId);
+            lastMi = mi;
+         }
+      }
+
+      if (lastMi != null)
+      {
+         session.getCoreSession().acknowledge(nativeId, lastMi.nativeId);
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java
new file mode 100644
index 0000000..4c8c29e
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+public class AMQConsumerBrokerExchange
+{
+   private AMQConnectionContext connectionContext;
+   private AMQDestination regionDestination;
+   private AMQSubscription subscription;
+   private boolean wildcard;
+
+   /**
+    * @return the connectionContext
+    */
+   public AMQConnectionContext getConnectionContext()
+   {
+      return this.connectionContext;
+   }
+
+   /**
+    * @param connectionContext
+    *           the connectionContext to set
+    */
+   public void setConnectionContext(AMQConnectionContext connectionContext)
+   {
+      this.connectionContext = connectionContext;
+   }
+
+   /**
+    * @return the regionDestination
+    */
+   public AMQDestination getRegionDestination()
+   {
+      return this.regionDestination;
+   }
+
+   /**
+    * @param regionDestination
+    *           the regionDestination to set
+    */
+   public void setRegionDestination(AMQDestination regionDestination)
+   {
+      this.regionDestination = regionDestination;
+   }
+
+   /**
+    * @return the subscription
+    */
+   public AMQSubscription getSubscription()
+   {
+      return this.subscription;
+   }
+
+   /**
+    * @param subscription
+    *           the subscription to set
+    */
+   public void setSubscription(AMQSubscription subscription)
+   {
+      this.subscription = subscription;
+   }
+
+   /**
+    * @return the wildcard
+    */
+   public boolean isWildcard()
+   {
+      return this.wildcard;
+   }
+
+   /**
+    * @param wildcard
+    *           the wildcard to set
+    */
+   public void setWildcard(boolean wildcard)
+   {
+      this.wildcard = wildcard;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDeadLetterStrategy.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDeadLetterStrategy.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDeadLetterStrategy.java
new file mode 100644
index 0000000..7df132d
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDeadLetterStrategy.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.Message;
+
+public interface AMQDeadLetterStrategy
+{
+
+   /**
+    * Allow pluggable strategy for deciding if message should be sent to a dead letter queue
+    * for example, you might not want to ignore expired or non-persistent messages
+    * @param message
+    * @return true if message should be sent to a dead letter queue
+    */
+   boolean isSendToDeadLetterQueue(Message message);
+
+   /**
+    * Returns the dead letter queue for the given message and subscription.
+    */
+   ActiveMQDestination getDeadLetterQueueFor(Message message, AMQSubscription subscription);
+
+   /**
+    * @return true if processes expired messages
+    */
+   boolean isProcessExpired();
+
+   /**
+    * @param processExpired the processExpired to set
+    */
+   void setProcessExpired(boolean processExpired);
+
+   /**
+    * @return the processNonPersistent
+    */
+   boolean isProcessNonPersistent();
+
+   /**
+    * @param processNonPersistent the processNonPersistent to set
+    */
+   void setProcessNonPersistent(boolean processNonPersistent);
+
+   boolean isDLQ(ActiveMQDestination destination);
+
+   /**
+    * Allows for a Message that was already processed by a DLQ to be rolled back in case
+    * of a move or a retry of that message, otherwise the Message would be considered a
+    * duplicate if this strategy is doing Message Auditing.
+    *
+    * @param message
+    */
+   void rollback(Message message);
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestination.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestination.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestination.java
new file mode 100644
index 0000000..b2c5ad2
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQDestination.java
@@ -0,0 +1,240 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.activemq.broker.region.MessageReference;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.Message;
+import org.apache.activemq.command.MessageAck;
+import org.apache.activemq.command.MessageDispatchNotification;
+import org.apache.activemq.command.ProducerInfo;
+import org.apache.activemq.usage.MemoryUsage;
+import org.apache.activemq.usage.Usage;
+
+public interface AMQDestination
+{
+   AMQDeadLetterStrategy DEFAULT_DEAD_LETTER_STRATEGY = new AMQSharedDeadLetterStrategy();
+   long DEFAULT_BLOCKED_PRODUCER_WARNING_INTERVAL = 30000;
+
+   void addSubscription(AMQConnectionContext context, AMQSubscription sub) throws Exception;
+
+   void removeSubscription(AMQConnectionContext context, AMQSubscription sub,
+         long lastDeliveredSequenceId) throws Exception;
+
+   void addProducer(AMQConnectionContext context, ProducerInfo info) throws Exception;
+
+   void removeProducer(AMQConnectionContext context, ProducerInfo info) throws Exception;
+
+   void send(AMQProducerBrokerExchange producerExchange, Message messageSend) throws Exception;
+
+   void acknowledge(AMQConnectionContext context, AMQSubscription sub,
+         final MessageAck ack, final MessageReference node) throws IOException;
+
+   long getInactiveTimoutBeforeGC();
+
+   void markForGC(long timeStamp);
+
+   boolean canGC();
+
+   void gc();
+
+   ActiveMQDestination getActiveMQDestination();
+
+   MemoryUsage getMemoryUsage();
+
+   void setMemoryUsage(MemoryUsage memoryUsage);
+
+   void dispose(AMQConnectionContext context) throws IOException;
+
+   boolean isDisposed();
+
+   AMQDestinationStatistics getDestinationStatistics();
+
+   AMQDeadLetterStrategy getDeadLetterStrategy();
+
+   Message[] browse();
+
+   String getName();
+
+   AMQMessageStore getMessageStore();
+
+   boolean isProducerFlowControl();
+
+   void setProducerFlowControl(boolean value);
+
+   boolean isAlwaysRetroactive();
+
+   void setAlwaysRetroactive(boolean value);
+
+   /**
+    * Set's the interval at which warnings about producers being blocked by
+    * resource usage will be triggered. Values of 0 or less will disable
+    * warnings
+    *
+    * @param blockedProducerWarningInterval
+    *           the interval at which warning about blocked producers will be
+    *           triggered.
+    */
+   void setBlockedProducerWarningInterval(long blockedProducerWarningInterval);
+
+   /**
+    *
+    * @return the interval at which warning about blocked producers will be
+    *         triggered.
+    */
+   long getBlockedProducerWarningInterval();
+
+   int getMaxProducersToAudit();
+
+   void setMaxProducersToAudit(int maxProducersToAudit);
+
+   int getMaxAuditDepth();
+
+   void setMaxAuditDepth(int maxAuditDepth);
+
+   boolean isEnableAudit();
+
+   void setEnableAudit(boolean enableAudit);
+
+   boolean isActive();
+
+   int getMaxPageSize();
+
+   void setMaxPageSize(int maxPageSize);
+
+   int getMaxBrowsePageSize();
+
+   void setMaxBrowsePageSize(int maxPageSize);
+
+   boolean isUseCache();
+
+   void setUseCache(boolean useCache);
+
+   int getMinimumMessageSize();
+
+   void setMinimumMessageSize(int minimumMessageSize);
+
+   int getCursorMemoryHighWaterMark();
+
+   void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark);
+
+   /**
+    * optionally called by a Subscriber - to inform the Destination its ready
+    * for more messages
+    */
+   void wakeup();
+
+   /**
+    * @return true if lazyDispatch is enabled
+    */
+   boolean isLazyDispatch();
+
+   /**
+    * set the lazy dispatch - default is false
+    *
+    * @param value
+    */
+   void setLazyDispatch(boolean value);
+
+   /**
+    * Inform the Destination a message has expired
+    *
+    * @param context
+    * @param subs
+    * @param node
+    */
+   void messageExpired(AMQConnectionContext context, AMQSubscription subs,
+         MessageReference node);
+
+   /**
+    * called when message is consumed
+    *
+    * @param context
+    * @param messageReference
+    */
+   void messageConsumed(AMQConnectionContext context,
+         MessageReference messageReference);
+
+   /**
+    * Called when message is delivered to the broker
+    *
+    * @param context
+    * @param messageReference
+    */
+   void messageDelivered(AMQConnectionContext context,
+         MessageReference messageReference);
+
+   /**
+    * Called when a message is discarded - e.g. running low on memory This will
+    * happen only if the policy is enabled - e.g. non durable topics
+    *
+    * @param context
+    * @param messageReference
+    * @param sub
+    */
+   void messageDiscarded(AMQConnectionContext context, AMQSubscription sub,
+         MessageReference messageReference);
+
+   /**
+    * Called when there is a slow consumer
+    *
+    * @param context
+    * @param subs
+    */
+   void slowConsumer(AMQConnectionContext context, AMQSubscription subs);
+
+   /**
+    * Called to notify a producer is too fast
+    *
+    * @param context
+    * @param producerInfo
+    */
+   void fastProducer(AMQConnectionContext context, ProducerInfo producerInfo);
+
+   /**
+    * Called when a Usage reaches a limit
+    *
+    * @param context
+    * @param usage
+    */
+   void isFull(AMQConnectionContext context, Usage<?> usage);
+
+   List<AMQSubscription> getConsumers();
+
+   /**
+    * called on Queues in slave mode to allow dispatch to follow subscription
+    * choice of master
+    *
+    * @param messageDispatchNotification
+    * @throws Exception
+    */
+   void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception;
+
+   boolean isPrioritizedMessages();
+
+   AMQSlowConsumerStrategy getSlowConsumerStrategy();
+
+   boolean isDoOptimzeMessageStorage();
+
+   void setDoOptimzeMessageStorage(boolean doOptimzeMessageStorage);
+
+   void clearPendingMessages();
+
+   boolean isDLQ();
+
+   void duplicateFromStore(Message message, AMQSubscription subscription);
+
+}


[50/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/assembly/dep.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/assembly/dep.xml b/distribution/hornetq/src/main/assembly/dep.xml
index f2ee1d1..ff2b80f 100644
--- a/distribution/hornetq/src/main/assembly/dep.xml
+++ b/distribution/hornetq/src/main/assembly/dep.xml
@@ -21,473 +21,92 @@
     <format>tar.gz</format>
   </formats>
   <includeBaseDirectory>true</includeBaseDirectory>
-   <moduleSets>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-commons</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-journal</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-       <moduleSet>
-           <useAllReactorProjects>true</useAllReactorProjects>
-           <includes>
-               <include>org.hornetq:hornetq-native</include>
-           </includes>
-           <binaries>
-               <includeDependencies>false</includeDependencies>
-               <outputDirectory>lib</outputDirectory>
-               <unpack>false</unpack>
-               <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-           </binaries>
-       </moduleSet>
-       <moduleSet>
-           <useAllReactorProjects>true</useAllReactorProjects>
-           <includes>
-               <include>org.hornetq:hornetq-tools</include>
-           </includes>
-           <binaries>
-               <includeDependencies>false</includeDependencies>
-               <outputDirectory>lib</outputDirectory>
-               <unpack>false</unpack>
-               <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-           </binaries>
-       </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-bootstrap</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-server</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory></outputDirectory>
-            <unpack>true</unpack>
-            <unpackOptions>
-               <includes>
-                  <include>**/*.xsd</include>
-               </includes>
-            </unpackOptions>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-native</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>bin</outputDirectory>
-            <unpack>true</unpack>
-            <unpackOptions>
-               <includes>
-                  <include>**/*.so</include>
-               </includes>
-            </unpackOptions>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-core-client</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-server</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-jboss-as-integration</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-jms-client</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-jms-server</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-jms-server</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory></outputDirectory>
-            <unpack>true</unpack>
-            <unpackOptions>
-               <includes>
-                  <include>**/*.xsd</include>
-               </includes>
-            </unpackOptions>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-jms-client</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-ra</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-service-sar</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-spring-integration</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-twitter-integration</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-vertx-integration</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq.rest:hornetq-rest</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-       <moduleSet>
-           <useAllReactorProjects>true</useAllReactorProjects>
-           <includes>
-               <include>org.hornetq:hornetq-amqp-protocol</include>
-           </includes>
-           <binaries>
-               <includeDependencies>false</includeDependencies>
-               <outputDirectory>lib</outputDirectory>
-               <unpack>false</unpack>
-               <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-           </binaries>
-       </moduleSet>
-       <moduleSet>
-           <useAllReactorProjects>true</useAllReactorProjects>
-           <includes>
-               <include>org.hornetq:hornetq-aerogear-integration</include>
-           </includes>
-           <binaries>
-               <includeDependencies>false</includeDependencies>
-               <outputDirectory>lib</outputDirectory>
-               <unpack>false</unpack>
-               <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-           </binaries>
-       </moduleSet>
-       <moduleSet>
-           <useAllReactorProjects>true</useAllReactorProjects>
-           <includes>
-               <include>org.hornetq:hornetq-stomp-protocol</include>
-           </includes>
-           <binaries>
-               <includeDependencies>false</includeDependencies>
-               <outputDirectory>lib</outputDirectory>
-               <unpack>false</unpack>
-               <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-           </binaries>
-       </moduleSet>
-       <moduleSet>
-           <useAllReactorProjects>true</useAllReactorProjects>
-           <includes>
-               <include>org.hornetq:hornetq-selector</include>
-           </includes>
-           <binaries>
-               <includeDependencies>false</includeDependencies>
-               <outputDirectory>lib</outputDirectory>
-               <unpack>false</unpack>
-               <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-           </binaries>
-       </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:jnp-client</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:jboss-mc</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:jboss-mc</include>
-         </includes>
-         <binaries>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>lib</outputDirectory>
-            <unpack>false</unpack>
-            <outputFileNameMapping>${module.artifactId}.${module.extension}</outputFileNameMapping>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-core-client</include>
-         </includes>
-         <binaries>
-            <attachmentClassifier>javadoc</attachmentClassifier>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>docs/api/hornetq-client</outputDirectory>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-server</include>
-         </includes>
-         <binaries>
-            <attachmentClassifier>javadoc</attachmentClassifier>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>docs/api/hornetq-server</outputDirectory>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-jms-client</include>
-         </includes>
-         <binaries>
-            <attachmentClassifier>javadoc</attachmentClassifier>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>docs/api/hornetq-jms-client</outputDirectory>
-         </binaries>
-      </moduleSet>
-      <moduleSet>
-         <useAllReactorProjects>true</useAllReactorProjects>
-         <includes>
-            <include>org.hornetq:hornetq-jms-server</include>
-         </includes>
-         <binaries>
-            <attachmentClassifier>javadoc</attachmentClassifier>
-            <includeDependencies>false</includeDependencies>
-            <outputDirectory>docs/api/hornetq-jms-server</outputDirectory>
-         </binaries>
-      </moduleSet>
-   </moduleSets>
    <dependencySets>
       <dependencySet>
          <includes>
+            <!-- modules -->
+            <include>org.hornetq:*</include>
+            <include>org.hornetq.rest:hornetq-rest</include>
+            <!-- dependencies -->
             <include>org.jboss.spec.javax.jms:jboss-jms-api_2.0_spec</include>
-         </includes>
+            <include>org.jboss.naming:jnpserver</include>
+            <include>org.jboss.logmanager:jboss-logmanager</include>
+            <include>org.jboss:jboss-common-core</include>
+            <include>io.netty:netty-all</include>
+            <include>org.apache.qpid:proton-j</include>
+            <include>org.apache.qpid:proton-jms</include>
+            <include>org.apache.activemq:activemq-client</include>
+            <include>org.slf4j:slf4j-api</include>
+            <include>io.airlift:airline</include>
+            <include>com.google.guava:guava</include>
+            <include>javax.inject:javax.inject</include>
+            <include>com.fasterxml.jackson.core:jackson-*</include>
+         </includes>
+         <excludes>
+           <exclude>*:javadoc</exclude>
+         </excludes>
          <outputDirectory>lib</outputDirectory>
          <unpack>false</unpack>
-         <outputFileNameMapping>jboss-jms-api.jar</outputFileNameMapping>
       </dependencySet>
+      <!-- native -->
       <dependencySet>
          <includes>
-            <include>org.jboss.naming:jnpserver</include>
+            <include>org.hornetq:hornetq-native</include>
          </includes>
-         <outputDirectory>lib</outputDirectory>
-         <unpack>false</unpack>
-         <outputFileNameMapping>jnpserver.jar</outputFileNameMapping>
+         <outputDirectory>bin</outputDirectory>
+         <unpack>true</unpack>
+         <unpackOptions>
+            <includes>
+               <include>**/*.so</include>
+            </includes>
+         </unpackOptions>
       </dependencySet>
+      <!-- javadoc -->
       <dependencySet>
-         <includes>
-            <include>io.netty:netty-all</include>
-         </includes>
-         <outputDirectory>lib</outputDirectory>
-         <unpack>false</unpack>
-         <outputFileNameMapping>netty.jar</outputFileNameMapping>
+        <includes>
+          <include>org.hornetq:hornetq-core-client:*:javadoc</include>
+          <include>org.hornetq:hornetq-server:*:javadoc</include>
+          <include>org.hornetq:hornetq-jms-server:*:javadoc</include>
+          <include>org.hornetq:hornetq-jms-client:*:javadoc</include>
+        </includes>
+        <outputDirectory>docs/api/${artifact.artifactId}</outputDirectory>
+        <unpack>true</unpack>
       </dependencySet>
-       <dependencySet>
-           <includes>
-               <include>org.apache.qpid:proton-api</include>
-           </includes>
-           <outputDirectory>lib</outputDirectory>
-           <unpack>false</unpack>
-           <outputFileNameMapping>proton-api.jar</outputFileNameMapping>
-       </dependencySet>
-       <dependencySet>
-           <includes>
-               <include>org.apache.qpid:proton-jms</include>
-           </includes>
-           <outputDirectory>lib</outputDirectory>
-           <unpack>false</unpack>
-           <outputFileNameMapping>proton-jms.jar</outputFileNameMapping>
-       </dependencySet>
-       <dependencySet>
-           <includes>
-               <include>org.apache.qpid:proton-j-impl</include>
-           </includes>
-           <outputDirectory>lib</outputDirectory>
-           <unpack>false</unpack>
-           <outputFileNameMapping>proton-j-impl.jar</outputFileNameMapping>
-       </dependencySet>
    </dependencySets>
-  <fileSets>
-    <fileSet>
-      <directory>src/main/resources/config</directory>
-      <outputDirectory>config</outputDirectory>
-      <lineEnding>keep</lineEnding>
-      <excludes>
-         <exclude>**/trunk/**</exclude>
-         <exclude>*.properties</exclude>
-      </excludes>
-    </fileSet>
-    <fileSet>
-      <directory>src/main/resources/bin</directory>
-      <outputDirectory>bin</outputDirectory>
-      <lineEnding>keep</lineEnding>
-    </fileSet>
-    <fileSet>
-      <directory>src/main/resources/licenses</directory>
-      <outputDirectory>licenses</outputDirectory>
-      <lineEnding>keep</lineEnding>
-    </fileSet>
-    <fileSet>
-      <directory>src/main/resources/examples</directory>
-      <outputDirectory>examples</outputDirectory>
-      <lineEnding>keep</lineEnding>
-    </fileSet>
-    <fileSet>
-      <directory>../../examples</directory>
-      <outputDirectory>examples</outputDirectory>
-      <lineEnding>keep</lineEnding>
-      <excludes>
+   <fileSets>
+     <!-- schema -->
+     <fileSet>
+       <directory>../../hornetq-server/src/main/resources/schema/</directory>
+       <outputDirectory>schema</outputDirectory>
+       <lineEnding>keep</lineEnding>
+     </fileSet>
+     <fileSet>
+       <directory>../../hornetq-jms-server/src/main/resources/schema/</directory>
+       <outputDirectory>schema</outputDirectory>
+       <lineEnding>keep</lineEnding>
+     </fileSet>
+     <!-- resources -->
+     <fileSet>
+       <directory>src/main/resources</directory>
+       <outputDirectory>/</outputDirectory>
+       <lineEnding>keep</lineEnding>
+       <includes>
+         <include>bin/*</include>
+         <include>config/**</include>
+         <include>licenses/*</include>
+       </includes>
+     </fileSet>
+     <fileSet>
+       <directory>../../examples</directory>
+       <outputDirectory>examples</outputDirectory>
+       <lineEnding>keep</lineEnding>
+       <excludes>
          <exclude>**/target/**</exclude>
          <exclude>**/**/*.iml</exclude>
          <exclude>**/**/*.dat</exclude>
-      </excludes>
-    </fileSet>
+       </excludes>
+     </fileSet>
+     <!-- docs -->
      <!--todo, this is crap, there must be better jdocbook assembly integration-->
       <fileSet>
          <directory>../../docs/user-manual/target/docbook/publish/en</directory>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/bin/hornetq
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/bin/hornetq b/distribution/hornetq/src/main/resources/bin/hornetq
new file mode 100755
index 0000000..a6abed2
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/bin/hornetq
@@ -0,0 +1,87 @@
+#!/bin/sh
+
+
+if [ -z "$HORNETQ_HOME" ] ; then
+
+  ## resolve links - $0 may be a link to hornetq's home
+  PRG="$0"
+  progname=`basename "$0"`
+  saveddir=`pwd`
+
+  # need this for relative symlinks
+  dirname_prg=`dirname "$PRG"`
+  cd "$dirname_prg"
+
+  while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '.*/.*' > /dev/null; then
+    PRG="$link"
+    else
+    PRG=`dirname "$PRG"`"/$link"
+    fi
+  done
+
+  HORNETQ_HOME=`dirname "$PRG"`
+  cd "$saveddir"
+
+  # make it fully qualified
+  HORNETQ_HOME=`cd "$HORNETQ_HOME/.." && pwd`
+fi
+
+# OS specific support.
+cygwin=false;
+darwin=false;
+case "`uname`" in
+  CYGWIN*) cygwin=true
+    OSTYPE=cygwin
+    export OSTYPE
+    ;;
+  Darwin*) darwin=true
+           if [ -z "$JAVA_HOME" ] ; then
+             JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Home
+           fi
+           ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+  [ -n "$HORNETQ_HOME" ] &&
+    HORNETQ_HOME=`cygpath --unix "$HORNETQ_HOME"`
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+  [ -n "$CLASSPATH" ] &&
+    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+if [ -z "$JAVACMD" ] ; then
+  if [ -n "$JAVA_HOME"  ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+      # IBM's JDK on AIX uses strange locations for the executables
+      JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+      JAVACMD="$JAVA_HOME/bin/java"
+    fi
+  else
+    JAVACMD=`which java 2> /dev/null `
+    if [ -z "$JAVACMD" ] ; then
+        JAVACMD=java
+    fi
+  fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+  echo "Error: JAVA_HOME is not defined correctly."
+  echo "  We cannot execute $JAVACMD"
+  exit 1
+fi
+
+for i in `ls $HORNETQ_HOME/lib/*.jar`; do
+	CLASSPATH=$i:$CLASSPATH
+done
+
+
+JAVA_ARGS="-XX:+UseParallelGC -XX:+AggressiveOpts -XX:+UseFastAccessorMethods -Xms512M -Xmx1024M -Djava.naming.factory.initial=org.jnp.interfaces.NamingContextFactory -Djava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces -Dhornetq.home=$HORNETQ_HOME -Ddata.dir=$HORNETQ_HOME/data -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=file:$HORNETQ_HOME/config/logging.properties -Djava.library.path=$HORNETQ_HOME/bin/lib/linux-i686:$HORNETQ_HOME/bin/lib/linux-x86_64"
+#JAVA_ARGS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005 -Djava.naming.factory.initial=org.jnp.interfaces.NamingContextFactory -Djava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces"
+
+exec "$JAVACMD" $JAVA_ARGS -classpath $CLASSPATH org.hornetq.cli.HornetQ $@
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/bin/hornetq-service
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/bin/hornetq-service b/distribution/hornetq/src/main/resources/bin/hornetq-service
new file mode 100755
index 0000000..5767556
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/bin/hornetq-service
@@ -0,0 +1,138 @@
+#!/bin/sh
+
+service=`basename "$0"`
+
+#
+# Discover the HORNETQ_BASE from the location of this script.
+#
+if [ -z "$HORNETQ_BASE" ] ; then
+
+  ## resolve links - $0 may be a link to HORNETQ's home
+  PRG="$0"
+  saveddir=`pwd`
+
+  # need this for relative symlinks
+  dirname_prg=`dirname "$PRG"`
+  cd "$dirname_prg"
+
+  while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '.*/.*' > /dev/null; then
+      PRG="$link"
+    else
+      PRG=`dirname "$PRG"`"/$link"
+    fi
+  done
+
+  HORNETQ_BASE=`dirname "$PRG"`
+  cd "$saveddir"
+
+  # make it fully qualified
+  HORNETQ_BASE=`cd "$HORNETQ_BASE/.." && pwd`
+  export HORNETQ_BASE
+
+fi
+
+PID_FILE="${HORNETQ_BASE}/data/hornetq.pid"
+
+if [ ! -d "${HORNETQ_BASE}/data/" ]; then
+    mkdir "${HORNETQ_BASE}/data/"
+fi
+
+status() {
+  if [ -f "${PID_FILE}" ] ; then
+    pid=`cat "${PID_FILE}"`
+    # check to see if it's gone...
+    ps -p ${pid} > /dev/null
+    if [ $? -eq 0 ] ; then
+      return 0
+    else
+      rm "${PID_FILE}"
+      return 3
+    fi
+  fi
+  return 3
+}
+
+stop() {
+  if [ -f "${PID_FILE}" ] ; then
+    pid=`cat "${PID_FILE}"`
+    kill $@ ${pid} > /dev/null
+  fi
+  for i in 1 2 3 4 5 ; do
+    status
+    if [ $? -ne 0 ] ; then
+      return 0
+    fi
+    sleep 1
+  done
+  echo "Could not stop process ${pid}"
+  return 1
+}
+
+start() {
+
+  status
+  if [ $? -eq 0 ] ; then
+    echo "Already running."
+    return 1
+  fi
+
+  nohup ${HORNETQ_BASE}/bin/hornetq run > /dev/null 2> /dev/null &
+
+  echo $! > "${PID_FILE}"
+
+  # check to see if stays up...
+  sleep 1
+  status
+  if [ $? -ne 0 ] ; then
+    echo "Could not start ${service}"
+    return 1
+  fi
+  echo "${service} is now running (${pid})"
+  return 0
+}
+
+case $1 in
+  start)
+    echo "Starting ${service}"
+    start
+    exit $?
+  ;;
+
+  force-stop)
+    echo "Forcibly Stopping ${service}"
+    stop -9
+    exit $?
+  ;;
+
+  stop)
+    echo "Gracefully Stopping ${service}"
+    stop
+    exit $?
+  ;;
+
+  restart)
+    echo "Restarting ${service}"
+    stop
+    start
+    exit $?
+  ;;
+
+  status)
+    status
+    rc=$?
+    if [ $rc -eq 0 ] ; then
+      echo "${service} is running (${pid})"
+    else
+      echo "${service} is stopped"
+    fi
+    exit $rc
+  ;;
+
+  *)
+    echo "Usage: $0 {start|stop|restart|force-stop|status}" >&2
+    exit 2
+  ;;
+esac
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/bin/hornetq.cmd
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/bin/hornetq.cmd b/distribution/hornetq/src/main/resources/bin/hornetq.cmd
new file mode 100755
index 0000000..00427d4
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/bin/hornetq.cmd
@@ -0,0 +1,58 @@
+@echo off
+
+setlocal
+
+if NOT "%HORNETQ_HOME%"=="" goto CHECK_HORNETQ_HOME
+PUSHD .
+CD %~dp0..
+set HORNETQ_HOME=%CD%
+POPD
+
+:CHECK_HORNETQ_HOME
+if exist "%HORNETQ_HOME%\bin\hornetq.cmd" goto CHECK_JAVA
+
+:NO_HOME
+echo HORNETQ_HOME environment variable is set incorrectly. Please set HORNETQ_HOME.
+goto END
+
+:CHECK_JAVA
+set _JAVACMD=%JAVACMD%
+
+if "%JAVA_HOME%" == "" goto NO_JAVA_HOME
+if not exist "%JAVA_HOME%\bin\java.exe" goto NO_JAVA_HOME
+if "%_JAVACMD%" == "" set _JAVACMD=%JAVA_HOME%\bin\java.exe
+goto RUN_JAVA
+
+:NO_JAVA_HOME
+if "%_JAVACMD%" == "" set _JAVACMD=java.exe
+echo.
+echo Warning: JAVA_HOME environment variable is not set.
+echo.
+
+:RUN_JAVA
+
+if "%JVM_FLAGS%" == "" set JVM_FLAGS=-XX:+UseParallelGC -XX:+AggressiveOpts -XX:+UseFastAccessorMethods -Xms512M -Xmx1024M -Djava.naming.factory.initial=org.jnp.interfaces.NamingContextFactory -Djava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces -Dhornetq.home=$HORNETQ_HOME -Ddata.dir=$HORNETQ_HOME/data -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration="file:%HORNETQ_HOME%\config\logging.properties" -Djava.library.path="%HORNETQ_HOME%/bin/lib/linux-i686:%HORNETQ_HOME%/bin/lib/linux-x86_64"
+
+if "x%HORNETQ_OPTS%" == "x" goto noHORNETQ_OPTS
+  set JVM_FLAGS=%JVM_FLAGS% %HORNETQ_OPTS%
+:noHORNETQ_OPTS
+
+if "x%HORNETQ_DEBUG%" == "x" goto noDEBUG
+  set JVM_FLAGS=%JVM_FLAGS% -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
+:noDEBUG
+
+if "x%HORNETQ_PROFILE%" == "x" goto noPROFILE
+  set JVM_FLAGS=-agentlib:yjpagent %JVM_FLAGS%
+:noPROFILE
+
+rem set JMX_OPTS=-Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
+
+set JVM_FLAGS=%JVM_FLAGS% %JMX_OPTS% -Dhornetq.home="%HORNETQ_HOME%" -classpath "%HORNETQ_HOME%\lib\*"
+
+"%_JAVACMD%" %JVM_FLAGS% org.hornetq.cli.HornetQ %*
+
+:END
+endlocal
+GOTO :EOF
+
+:EOF

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/bin/run.bat
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/bin/run.bat b/distribution/hornetq/src/main/resources/bin/run.bat
old mode 100644
new mode 100755
index 0772410..7e6a23f
--- a/distribution/hornetq/src/main/resources/bin/run.bat
+++ b/distribution/hornetq/src/main/resources/bin/run.bat
@@ -1,21 +1 @@
-@ echo off
-setlocal ENABLEDELAYEDEXPANSION
-set HORNETQ_HOME=..
-IF "a%1"== "a" ( 
-set CONFIG_DIR=%HORNETQ_HOME%\config\stand-alone\non-clustered
-) ELSE (
-SET CONFIG_DIR=%1
-)
-set CLASSPATH=%CONFIG_DIR%;%HORNETQ_HOME%\schemas\
-REM you can use the following line if you want to run with different ports
-REM set CLUSTER_PROPS="-Djnp.port=1099 -Djnp.rmiPort=1098 -Djnp.host=localhost -Dhornetq.remoting.netty.host=localhost -Dhornetq.remoting.netty.port=5445"
-set JVM_ARGS=%CLUSTER_PROPS% -XX:+UseParallelGC  -XX:+AggressiveOpts -XX:+UseFastAccessorMethods -Xms512M -Xmx1024M -Dhornetq.config.dir=%CONFIG_DIR% -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Djava.util.logging.config.file=%CONFIG_DIR%\logging.properties -Djava.library.path=.
-REM export JVM_ARGS="-Xmx512M -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Djava.util.logging.config.file=%CONFIG_DIR%\logging.properties -Dhornetq.config.dir=$CONFIG_DIR -Djava.library.path=. -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
-for /R ..\lib %%A in (*.jar) do (
-SET CLASSPATH=!CLASSPATH!;%%A
-)
-mkdir ..\logs
-echo ***********************************************************************************
-echo "java %JVM_ARGS% -classpath %CLASSPATH% org.hornetq.integration.bootstrap.HornetQBootstrapServer hornetq-beans.xml"
-echo ***********************************************************************************
-java %JVM_ARGS% -classpath "%CLASSPATH%" org.hornetq.integration.bootstrap.HornetQBootstrapServer hornetq-beans.xml
+hornetq.cmd run %*
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/bin/run.sh
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/bin/run.sh b/distribution/hornetq/src/main/resources/bin/run.sh
index 87e5aa8..781f954 100755
--- a/distribution/hornetq/src/main/resources/bin/run.sh
+++ b/distribution/hornetq/src/main/resources/bin/run.sh
@@ -1,35 +1,3 @@
 #!/bin/sh
-#------------------------------------------------
-# Simple shell-script to run HornetQ standalone
-#------------------------------------------------
 
-export HORNETQ_HOME=..
-mkdir -p ../logs
-
-# By default, the server is started in the non-clustered standalone configuration
-
-if [ a"$1" = a ]; then CONFIG_DIR=$HORNETQ_HOME/config/stand-alone/non-clustered; else CONFIG_DIR="$1"; fi
-if [ a"$2" = a ]; then FILENAME=hornetq-beans.xml; else FILENAME="$2"; fi
-
-if [ ! -d $CONFIG_DIR ]; then
-    echo script needs to be run from the HORNETQ_HOME/bin directory >&2
-    exit 1
-fi
-
-RESOLVED_CONFIG_DIR=`cd "$CONFIG_DIR"; pwd`
-export CLASSPATH=$RESOLVED_CONFIG_DIR:$HORNETQ_HOME/schemas/
-
-# Use the following line to run with different ports
-#export CLUSTER_PROPS="-Djnp.port=1099 -Djnp.rmiPort=1098 -Djnp.host=localhost -Dhornetq.remoting.netty.host=localhost -Dhornetq.remoting.netty.port=5445"
-
-export JVM_ARGS="$CLUSTER_PROPS -XX:+UseParallelGC -XX:+AggressiveOpts -XX:+UseFastAccessorMethods -Xms512M -Xmx1024M -Dhornetq.config.dir=$RESOLVED_CONFIG_DIR -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=file://$RESOLVED_CONFIG_DIR/logging.properties -Djava.library.path=./lib/linux-i686:./lib/linux-x86_64"
-#export JVM_ARGS="-Xmx512M -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Dlogging.configuration=$CONFIG_DIR/logging.properties -Dhornetq.config.dir=$CONFIG_DIR -Djava.library.path=. -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
-
-for i in `ls $HORNETQ_HOME/lib/*.jar`; do
-	CLASSPATH=$i:$CLASSPATH
-done
-
-echo "***********************************************************************************"
-echo "java $JVM_ARGS -classpath $CLASSPATH org.hornetq.integration.bootstrap.HornetQBootstrapServer $FILENAME"
-echo "***********************************************************************************"
-java $JVM_ARGS -classpath $CLASSPATH -Dcom.sun.management.jmxremote org.hornetq.integration.bootstrap.HornetQBootstrapServer $FILENAME
+./hornetq run $@

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/bin/stop.bat
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/bin/stop.bat b/distribution/hornetq/src/main/resources/bin/stop.bat
old mode 100644
new mode 100755
index 4a1aa8e..cd16950
--- a/distribution/hornetq/src/main/resources/bin/stop.bat
+++ b/distribution/hornetq/src/main/resources/bin/stop.bat
@@ -1,9 +1 @@
-@ echo off
-setlocal ENABLEDELAYEDEXPANSION
-set HORNETQ_HOME=..
-IF "a%1"== "a" ( 
-set CONFIG_DIR=%HORNETQ_HOME%\config\stand-alone\non-clustered
-) ELSE (
-SET CONFIG_DIR=%1
-)
-dir >> %CONFIG_DIR%\STOP_ME
\ No newline at end of file
+hornetq.cmd stop %*
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/bin/stop.sh
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/bin/stop.sh b/distribution/hornetq/src/main/resources/bin/stop.sh
index 9f55248..ce0270f 100755
--- a/distribution/hornetq/src/main/resources/bin/stop.sh
+++ b/distribution/hornetq/src/main/resources/bin/stop.sh
@@ -1,5 +1,3 @@
 #!/bin/sh
 
-export HORNETQ_HOME=..
-if [ a"$1" = a ]; then CONFIG_DIR=$HORNETQ_HOME/config/stand-alone/non-clustered; else CONFIG_DIR="$1"; fi
-touch $CONFIG_DIR/STOP_ME;
\ No newline at end of file
+./hornetq stop $@

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/clustered/bootstrap.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/clustered/bootstrap.xml b/distribution/hornetq/src/main/resources/config/clustered/bootstrap.xml
new file mode 100644
index 0000000..d5bc84d
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/clustered/bootstrap.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ Copyright 2005-2014 Red Hat, Inc.
+ Red Hat licenses this file to you under the Apache License, version
+ 2.0 (the "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+    http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied.  See the License for the specific language governing
+ permissions and limitations under the License.
+-->
+
+<broker xmlns="http://hornetq.org/schema">
+
+   <core configuration="file:${hornetq.home}/config/clustered/hornetq-configuration.xml"></core>
+   <jms configuration="file:${hornetq.home}/config/clustered/hornetq-jms.xml"></jms>
+
+   <basic-security/>
+
+   <naming bindAddress="localhost" port="1099" rmiBindAddress="localhost" rmiPort="1098"/>
+
+</broker>
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/clustered/hornetq-configuration.xml
new file mode 100644
index 0000000..474d507
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/clustered/hornetq-configuration.xml
@@ -0,0 +1,94 @@
+<configuration xmlns="urn:hornetq"
+               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
+   
+   <paging-directory>${data.dir:../data}/paging</paging-directory>
+   
+   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
+   
+   <journal-directory>${data.dir:../data}/journal</journal-directory>
+   
+   <journal-min-files>10</journal-min-files>
+   
+   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
+
+   <connectors>      
+      <connector name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </connector>
+      
+      <connector name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+      </connector>
+   </connectors>
+
+   <acceptors>
+      <acceptor name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </acceptor>
+      
+      <acceptor name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+         <param key="direct-deliver" value="false"/>
+      </acceptor>
+   </acceptors>
+
+   <broadcast-groups>
+      <broadcast-group name="bg-group1">
+         <group-address>231.7.7.7</group-address>
+         <group-port>9876</group-port>
+         <broadcast-period>5000</broadcast-period>
+         <connector-ref>netty</connector-ref>
+      </broadcast-group>
+   </broadcast-groups>
+
+   <discovery-groups>
+      <discovery-group name="dg-group1">
+         <group-address>231.7.7.7</group-address>
+         <group-port>9876</group-port>
+         <refresh-timeout>10000</refresh-timeout>
+      </discovery-group>
+   </discovery-groups>
+   
+   <cluster-connections>
+      <cluster-connection name="my-cluster">
+         <address>jms</address>	 
+         <connector-ref>netty</connector-ref>
+	      <discovery-group-ref discovery-group-name="dg-group1"/>
+      </cluster-connection>
+   </cluster-connections>
+   
+   <security-settings>
+      <security-setting match="#">
+         <permission type="createNonDurableQueue" roles="guest"/>
+         <permission type="deleteNonDurableQueue" roles="guest"/>
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+      </security-setting>
+   </security-settings>
+
+   <address-settings>
+      <!--default for catch all-->
+      <address-setting match="#">
+         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
+         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
+         <redelivery-delay>0</redelivery-delay>
+         <max-size-bytes>10485760</max-size-bytes>       
+         <message-counter-history-day-limit>10</message-counter-history-day-limit>
+         <address-full-policy>BLOCK</address-full-policy>
+      </address-setting>
+   </address-settings>
+
+   
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/clustered/hornetq-jms.xml
new file mode 100644
index 0000000..044d7e8
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/clustered/hornetq-jms.xml
@@ -0,0 +1,53 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
+
+   <connection-factory name="NettyXAConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/XAConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/ConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/XAThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/ThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+
+   <queue name="DLQ">
+      <entry name="/queue/DLQ"/>
+   </queue>
+   
+   <queue name="ExpiryQueue">
+      <entry name="/queue/ExpiryQueue"/>
+   </queue>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/clustered/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/clustered/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/clustered/hornetq-users.xml
new file mode 100644
index 0000000..934306c
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/clustered/hornetq-users.xml
@@ -0,0 +1,7 @@
+<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
+   <!-- the default user.  this is used where username is null-->
+   <defaultuser name="guest" password="guest">
+      <role name="guest"/>
+   </defaultuser>
+</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/clustered/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/clustered/jndi.properties b/distribution/hornetq/src/main/resources/config/clustered/jndi.properties
new file mode 100644
index 0000000..e2a9832
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/clustered/jndi.properties
@@ -0,0 +1,2 @@
+java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
+java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-configuration.xml
deleted file mode 100644
index fb54135..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-configuration.xml
+++ /dev/null
@@ -1,122 +0,0 @@
-<!--
-  ~ Copyright 2009 Red Hat, Inc.
-  ~  Red Hat licenses this file to you under the Apache License, version
-  ~  2.0 (the "License"); you may not use this file except in compliance
-  ~  with the License.  You may obtain a copy of the License at
-  ~     http://www.apache.org/licenses/LICENSE-2.0
-  ~  Unless required by applicable law or agreed to in writing, software
-  ~  distributed under the License is distributed on an "AS IS" BASIS,
-  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-  ~  implied.  See the License for the specific language governing
-  ~  permissions and limitations under the License.
-  -->
-
-<configuration xmlns="urn:hornetq"
-               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-
-   <!--  Don't change this name.
-         This is used by the dependency framework on the deployers,
-         to make sure this deployment is done before any other deployment -->
-   <name>HornetQ.main.config</name>
-
-   <bindings-directory>${jboss.server.data.dir}/${hornetq.data.dir:hornetq}/bindings</bindings-directory>
-
-   <journal-directory>${jboss.server.data.dir}/${hornetq.data.dir:hornetq}/journal</journal-directory>
-   
-   <journal-min-files>10</journal-min-files>
-
-   <large-messages-directory>${jboss.server.data.dir}/${hornetq.data.dir:hornetq}/largemessages</large-messages-directory>
-
-   <paging-directory>${jboss.server.data.dir}/${hornetq.data.dir:hornetq}/paging</paging-directory>
-
-   <connectors>
-      <connector name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </connector>
-      
-      <connector name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-      </connector>
-
-      <connector name="in-vm">
-         <factory-class>org.hornetq.core.remoting.impl.invm.InVMConnectorFactory</factory-class>
-         <param key="server-id" value="${hornetq.server-id:0}"/>
-      </connector>
-
-   </connectors>
-
-   <acceptors>
-      <acceptor name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </acceptor>
-      
-      <acceptor name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-         <param key="direct-deliver" value="false"/>
-      </acceptor>
-
-      <acceptor name="in-vm">
-        <factory-class>org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory</factory-class>
-        <param key="server-id" value="0"/>
-      </acceptor>
-
-   </acceptors>
-
-   <broadcast-groups>
-      <broadcast-group name="bg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <broadcast-period>5000</broadcast-period>
-         <connector-ref>netty</connector-ref>
-      </broadcast-group>
-   </broadcast-groups>
-
-   <discovery-groups>
-      <discovery-group name="dg-group1">
-         <group-address>231.7.7.7</group-address>
-         <group-port>9876</group-port>
-         <refresh-timeout>10000</refresh-timeout>
-      </discovery-group>
-   </discovery-groups>
-   
-   <cluster-connections>
-      <cluster-connection name="my-cluster">
-         <address>jms</address>	 
-         <connector-ref>netty</connector-ref>
-	      <discovery-group-ref discovery-group-name="dg-group1"/>
-      </cluster-connection>
-   </cluster-connections>
-   
-   <security-settings>
-      <security-setting match="#">
-         <permission type="createNonDurableQueue" roles="guest"/>
-         <permission type="deleteNonDurableQueue" roles="guest"/>
-         <permission type="consume" roles="guest"/>
-         <permission type="send" roles="guest"/>
-      </security-setting>
-   </security-settings>
-
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jboss-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jboss-beans.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jboss-beans.xml
deleted file mode 100644
index 50768e0..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jboss-beans.xml
+++ /dev/null
@@ -1,62 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="org.jboss.mx.util.MBeanServerLocator"
-                   factoryMethod="locateJBoss"/>
-   </bean>
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-      <property name="configurationUrl">${jboss.server.home.url}/deploy/hornetq/hornetq-configuration.xml</property>
-   </bean>
-
-	<!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.integration.jboss.security.JBossASSecurityManager">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-      <depends>JBossSecurityJNDIContextEstablishment</depends>
-      <property name="allowClientLogin">false</property>
-      <property name="authoriseOnClientLogin">false</property>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>   
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-
-   <!-- POJO which ensures HornetQ Resource Adapter is stopped before HornetQServer -->
-   <bean name="HornetQRAService" class="org.hornetq.ra.HornetQRAService">
-      <constructor>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>jboss.jca:name='jms-ra.rar',service=RARDeployment</parameter>
-      </constructor>
-      <depends>HornetQServer</depends>
-   </bean>
-
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jms.xml
deleted file mode 100644
index 8d4bd7a..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/hornetq-jms.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-
-   <connection-factory name="NettyConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/ConnectionFactory"/>
-         <entry name="/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>true</xa>
-	   <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-	   </connectors>
-		<entries>
-			<entry name="/ThroughputConnectionFactory"/>
-			<entry name="/XAThroughputConnectionFactory"/>
-		</entries>
-	</connection-factory>
-   
-   <connection-factory name="InVMConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="in-vm"/>
-      </connectors>
-      <entries>
-         <entry name="java:/ConnectionFactory"/>
-         <entry name="java:/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-
-   <queue name="DLQ">
-      <entry name="/queue/DLQ"/>
-   </queue>
-   
-   <queue name="ExpiryQueue">
-      <entry name="/queue/ExpiryQueue"/>
-   </queue>
-
-</configuration>
-

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/jms-ds.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/jms-ds.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/jms-ds.xml
deleted file mode 100644
index f387cf9..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/clustered/jms-ds.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<connection-factories>
-   <!--
-    JMS Stuff
-   -->
-
-   <mbean code="org.jboss.jms.jndi.JMSProviderLoader" name="hornetq:service=JMSProviderLoader,name=JMSProvider">
-      <attribute name="ProviderName">DefaultJMSProvider</attribute>
-      <attribute name="ProviderAdapterClass">org.jboss.jms.jndi.JNDIProviderAdapter</attribute>
-      <attribute name="FactoryRef">java:/XAConnectionFactory</attribute>
-      <attribute name="QueueFactoryRef">java:/XAConnectionFactory</attribute>
-      <attribute name="TopicFactoryRef">java:/XAConnectionFactory</attribute>
-   </mbean>
-   <!--
-    JMS XA Resource adapter, use this to get transacted JMS in beans
-   -->
-   <tx-connection-factory>
-      <jndi-name>JmsXA</jndi-name>
-      <xa-transaction/>
-      <rar-name>jms-ra.rar</rar-name>
-      <connection-definition>org.hornetq.ra.HornetQRAConnectionFactory</connection-definition>
-      <config-property name="SessionDefaultType" type="java.lang.String">javax.jms.Topic</config-property>
-      <config-property name="JmsProviderAdapterJNDI" type="java.lang.String">java:/DefaultJMSProvider</config-property>
-      <max-pool-size>20</max-pool-size>
-      <security-domain-and-application>JmsXARealm</security-domain-and-application>
-   </tx-connection-factory>
-</connection-factories>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-configuration.xml
deleted file mode 100644
index a92796f..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-configuration.xml
+++ /dev/null
@@ -1,97 +0,0 @@
-<!--
-  ~ Copyright 2009 Red Hat, Inc.
-  ~  Red Hat licenses this file to you under the Apache License, version
-  ~  2.0 (the "License"); you may not use this file except in compliance
-  ~  with the License.  You may obtain a copy of the License at
-  ~     http://www.apache.org/licenses/LICENSE-2.0
-  ~  Unless required by applicable law or agreed to in writing, software
-  ~  distributed under the License is distributed on an "AS IS" BASIS,
-  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-  ~  implied.  See the License for the specific language governing
-  ~  permissions and limitations under the License.
-  -->
-
-<configuration xmlns="urn:hornetq"
-               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-
-   <!--  Don't change this name.
-         This is used by the dependency framework on the deployers,
-         to make sure this deployment is done before any other deployment -->
-   <name>HornetQ.main.config</name>
-   
-   <bindings-directory>${jboss.server.data.dir}/hornetq/bindings</bindings-directory>
-
-   <journal-directory>${jboss.server.data.dir}/hornetq/journal</journal-directory>
-   
-   <journal-min-files>10</journal-min-files>
-
-   <large-messages-directory>${jboss.server.data.dir}/hornetq/largemessages</large-messages-directory>
-
-   <paging-directory>${jboss.server.data.dir}/hornetq/paging</paging-directory>
-
-   <connectors>
-      <connector name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </connector>
-      
-      <connector name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-      </connector>
-
-      <connector name="in-vm">
-         <factory-class>org.hornetq.core.remoting.impl.invm.InVMConnectorFactory</factory-class>
-         <param key="server-id" value="${hornetq.server-id:0}"/>
-      </connector>
-
-   </connectors>
-
-   <acceptors>   
-      <acceptor name="netty">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-      </acceptor>
-      
-      <acceptor name="netty-throughput">
-         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-         <param key="host"  value="${jboss.bind.address:localhost}"/>
-         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
-         <param key="batch-delay" value="50"/>
-         <param key="direct-deliver" value="false"/>
-      </acceptor>
-
-      <acceptor name="in-vm">
-        <factory-class>org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory</factory-class>
-        <param key="server-id" value="0"/>
-      </acceptor>
-
-   </acceptors>
-
-   <security-settings>
-      <security-setting match="#">
-         <permission type="createNonDurableQueue" roles="guest"/>
-         <permission type="deleteNonDurableQueue" roles="guest"/>
-         <permission type="consume" roles="guest"/>
-         <permission type="send" roles="guest"/>
-      </security-setting>
-   </security-settings>
-
-   <address-settings>
-      <!--default for catch all-->
-      <address-setting match="#">
-         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-         <redelivery-delay>0</redelivery-delay>
-         <max-size-bytes>10485760</max-size-bytes>       
-         <message-counter-history-day-limit>10</message-counter-history-day-limit>
-         <address-full-policy>BLOCK</address-full-policy>
-      </address-setting>
-   </address-settings>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jboss-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jboss-beans.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jboss-beans.xml
deleted file mode 100644
index 238792c..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jboss-beans.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="org.jboss.mx.util.MBeanServerLocator"
-                   factoryMethod="locateJBoss"/>
-   </bean>
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-      <property name="configurationUrl">${jboss.server.home.url}/deploy/hornetq/hornetq-configuration.xml</property>
-   </bean>
-
-	<!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.integration.jboss.security.JBossASSecurityManager">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-      <depends>JBossSecurityJNDIContextEstablishment</depends>
-      <property name="allowClientLogin">false</property>
-      <property name="authoriseOnClientLogin">false</property>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>          
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-
-   <!-- POJO which ensures HornetQ Resource Adapter is stopped before HornetQServer -->
-   <bean name="HornetQRAService" class="org.hornetq.ra.HornetQRAService">
-      <constructor>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>jboss.jca:name='jms-ra.rar',service=RARDeployment</parameter>
-      </constructor>
-      <depends>HornetQServer</depends>
-   </bean>
-</deployment>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jms.xml
deleted file mode 100644
index 8fcc227..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/hornetq-jms.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-<configuration xmlns="urn:hornetq"
-            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-
-   <connection-factory name="NettyConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="netty"/>
-      </connectors>
-      <entries>
-         <entry name="/ConnectionFactory"/>
-         <entry name="/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <connection-factory name="NettyThroughputConnectionFactory">
-      <xa>true</xa>
-	   <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-	   </connectors>
-		<entries>
-			<entry name="/ThroughputConnectionFactory"/>
-			<entry name="/XAThroughputConnectionFactory"/>
-		</entries>
-	</connection-factory>
-   
-   <connection-factory name="InVMConnectionFactory">
-      <xa>true</xa>
-      <connectors>
-         <connector-ref connector-name="in-vm"/>
-      </connectors>
-      <entries>
-         <entry name="java:/ConnectionFactory"/>
-         <entry name="java:/XAConnectionFactory"/>
-      </entries>
-   </connection-factory>
-   
-   <queue name="DLQ">
-      <entry name="/queue/DLQ"/>
-   </queue>
-   
-   <queue name="ExpiryQueue">
-      <entry name="/queue/ExpiryQueue"/>
-   </queue>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/jms-ds.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/jms-ds.xml b/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/jms-ds.xml
deleted file mode 100644
index f387cf9..0000000
--- a/distribution/hornetq/src/main/resources/config/jboss-as-6/non-clustered/jms-ds.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<connection-factories>
-   <!--
-    JMS Stuff
-   -->
-
-   <mbean code="org.jboss.jms.jndi.JMSProviderLoader" name="hornetq:service=JMSProviderLoader,name=JMSProvider">
-      <attribute name="ProviderName">DefaultJMSProvider</attribute>
-      <attribute name="ProviderAdapterClass">org.jboss.jms.jndi.JNDIProviderAdapter</attribute>
-      <attribute name="FactoryRef">java:/XAConnectionFactory</attribute>
-      <attribute name="QueueFactoryRef">java:/XAConnectionFactory</attribute>
-      <attribute name="TopicFactoryRef">java:/XAConnectionFactory</attribute>
-   </mbean>
-   <!--
-    JMS XA Resource adapter, use this to get transacted JMS in beans
-   -->
-   <tx-connection-factory>
-      <jndi-name>JmsXA</jndi-name>
-      <xa-transaction/>
-      <rar-name>jms-ra.rar</rar-name>
-      <connection-definition>org.hornetq.ra.HornetQRAConnectionFactory</connection-definition>
-      <config-property name="SessionDefaultType" type="java.lang.String">javax.jms.Topic</config-property>
-      <config-property name="JmsProviderAdapterJNDI" type="java.lang.String">java:/DefaultJMSProvider</config-property>
-      <max-pool-size>20</max-pool-size>
-      <security-domain-and-application>JmsXARealm</security-domain-and-application>
-   </tx-connection-factory>
-</connection-factories>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/logging.properties b/distribution/hornetq/src/main/resources/config/logging.properties
new file mode 100644
index 0000000..b3f37aa
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/logging.properties
@@ -0,0 +1,56 @@
+#
+# JBoss, Home of Professional Open Source.
+# Copyright 2010, Red Hat, Inc., and individual contributors
+# as indicated by the @author tags. See the copyright.txt file 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.
+#
+
+# Additional logger names to configure (root logger is always configured)
+# Root logger option
+loggers=org.jboss.logging,org.hornetq.core.server,org.hornetq.utils,org.hornetq.journal,org.hornetq.jms.server,org.hornetq.integration.bootstrap
+
+# Root logger level
+logger.level=INFO
+# HornetQ logger levels
+logger.org.hornetq.core.server.level=INFO
+logger.org.hornetq.journal.level=INFO
+logger.org.hornetq.utils.level=INFO
+logger.org.hornetq.jms.level=INFO
+logger.org.hornetq.integration.bootstrap.level=INFO
+# Root logger handlers
+logger.handlers=FILE,CONSOLE
+
+# Console handler configuration
+handler.CONSOLE=org.jboss.logmanager.handlers.ConsoleHandler
+handler.CONSOLE.properties=autoFlush
+handler.CONSOLE.level=DEBUG
+handler.CONSOLE.autoFlush=true
+handler.CONSOLE.formatter=PATTERN
+
+# File handler configuration
+handler.FILE=org.jboss.logmanager.handlers.FileHandler
+handler.FILE.level=DEBUG
+handler.FILE.properties=autoFlush,fileName
+handler.FILE.autoFlush=true
+handler.FILE.fileName=${hornetq.home}/logs/hornetq.log
+handler.FILE.formatter=PATTERN
+
+# Formatter pattern configuration
+formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
+formatter.PATTERN.properties=pattern
+formatter.PATTERN.pattern=%d{HH:mm:ss,SSS} %-5p [%c] %s%E%n

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/non-clustered/bootstrap.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/non-clustered/bootstrap.xml b/distribution/hornetq/src/main/resources/config/non-clustered/bootstrap.xml
new file mode 100644
index 0000000..30e3761
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/non-clustered/bootstrap.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ Copyright 2005-2014 Red Hat, Inc.
+ Red Hat licenses this file to you under the Apache License, version
+ 2.0 (the "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+    http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied.  See the License for the specific language governing
+ permissions and limitations under the License.
+-->
+
+<broker xmlns="http://hornetq.org/schema">
+
+   <core configuration="file:${hornetq.home}/config/non-clustered/hornetq-configuration.xml"></core>
+   <jms configuration="file:${hornetq.home}/config/non-clustered/hornetq-jms.xml"></jms>
+
+   <basic-security/>
+
+   <naming bindAddress="localhost" port="1099" rmiBindAddress="localhost" rmiPort="1098"/>
+
+</broker>
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-configuration.xml
new file mode 100644
index 0000000..8b0922d
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-configuration.xml
@@ -0,0 +1,67 @@
+<configuration xmlns="urn:hornetq"
+               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
+
+   <paging-directory>${data.dir:../data}/paging</paging-directory>
+   
+   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
+   
+   <journal-directory>${data.dir:../data}/journal</journal-directory>
+   
+   <journal-min-files>10</journal-min-files>
+   
+   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
+   
+   <connectors>
+      <connector name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </connector>
+      
+      <connector name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+      </connector>
+   </connectors>
+
+   <acceptors>
+      <acceptor name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </acceptor>
+      
+      <acceptor name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+         <param key="direct-deliver" value="false"/>
+      </acceptor>
+   </acceptors>
+
+   <security-settings>
+      <security-setting match="#">
+         <permission type="createNonDurableQueue" roles="guest"/>
+         <permission type="deleteNonDurableQueue" roles="guest"/>
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+      </security-setting>
+   </security-settings>
+
+   <address-settings>
+      <!--default for catch all-->
+      <address-setting match="#">
+         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
+         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
+         <redelivery-delay>0</redelivery-delay>
+         <max-size-bytes>10485760</max-size-bytes>       
+         <message-counter-history-day-limit>10</message-counter-history-day-limit>
+         <address-full-policy>BLOCK</address-full-policy>
+      </address-setting>
+   </address-settings>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-jms.xml
new file mode 100644
index 0000000..044d7e8
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-jms.xml
@@ -0,0 +1,53 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
+
+   <connection-factory name="NettyXAConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/XAConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty"/>
+      </connectors>
+      <entries>
+         <entry name="/ConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>true</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/XAThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+   
+   <connection-factory name="NettyThroughputConnectionFactory">
+      <xa>false</xa>
+      <connectors>
+         <connector-ref connector-name="netty-throughput"/>
+      </connectors>
+      <entries>
+         <entry name="/ThroughputConnectionFactory"/>
+      </entries>
+   </connection-factory>
+
+   <queue name="DLQ">
+      <entry name="/queue/DLQ"/>
+   </queue>
+   
+   <queue name="ExpiryQueue">
+      <entry name="/queue/ExpiryQueue"/>
+   </queue>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-users.xml
new file mode 100644
index 0000000..934306c
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/non-clustered/hornetq-users.xml
@@ -0,0 +1,7 @@
+<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
+   <!-- the default user.  this is used where username is null-->
+   <defaultuser name="guest" password="guest">
+      <role name="guest"/>
+   </defaultuser>
+</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/non-clustered/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/non-clustered/jndi.properties b/distribution/hornetq/src/main/resources/config/non-clustered/jndi.properties
new file mode 100644
index 0000000..e2a9832
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/non-clustered/jndi.properties
@@ -0,0 +1,2 @@
+java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
+java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/replicated/bootstrap.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/replicated/bootstrap.xml b/distribution/hornetq/src/main/resources/config/replicated/bootstrap.xml
new file mode 100644
index 0000000..62a253c
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/replicated/bootstrap.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ Copyright 2005-2014 Red Hat, Inc.
+ Red Hat licenses this file to you under the Apache License, version
+ 2.0 (the "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+    http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied.  See the License for the specific language governing
+ permissions and limitations under the License.
+-->
+
+<broker xmlns="http://hornetq.org/schema">
+
+   <core configuration="file:${hornetq.home}/config/replicated/hornetq-configuration.xml"></core>
+   <jms configuration="file:${hornetq.home}/config/replicated/hornetq-jms.xml"></jms>
+
+   <basic-security/>
+
+   <naming bindAddress="localhost" port="1099" rmiBindAddress="localhost" rmiPort="1098"/>
+
+</broker>
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/replicated/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/replicated/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/replicated/hornetq-configuration.xml
new file mode 100644
index 0000000..7a048cf
--- /dev/null
+++ b/distribution/hornetq/src/main/resources/config/replicated/hornetq-configuration.xml
@@ -0,0 +1,104 @@
+<configuration xmlns="urn:hornetq"
+               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+               xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
+   <!--
+   if you want to run this as a backup on different ports you would need to set the following variable
+   export CLUSTER_PROPS="-Djnp.port=1199 -Djnp.rmiPort=1198 -Djnp.host=localhost -Dhornetq.remoting.netty.host=localhost -Dhornetq.remoting.netty.port=5545 -Dhornetq.remoting.netty.batch.port=5555 -Dhornetq.backup=true"
+   -->
+
+   <paging-directory>${data.dir:../data}/paging</paging-directory>
+   
+   <bindings-directory>${data.dir:../data}/bindings</bindings-directory>
+   
+   <journal-directory>${data.dir:../data}/journal</journal-directory>
+   
+   <journal-min-files>10</journal-min-files>
+   
+   <large-messages-directory>${data.dir:../data}/large-messages</large-messages-directory>
+
+   <connectors>      
+      <connector name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </connector>
+      
+      <connector name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+      </connector>
+   </connectors>
+
+   <acceptors>
+      <acceptor name="netty">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
+      </acceptor>
+      
+      <acceptor name="netty-throughput">
+         <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
+         <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
+         <param key="port"  value="${hornetq.remoting.netty.batch.port:5455}"/>
+         <param key="batch-delay" value="50"/>
+         <param key="direct-deliver" value="false"/>
+      </acceptor>
+   </acceptors>
+
+   <broadcast-groups>
+      <broadcast-group name="bg-group1">
+         <group-address>231.7.7.7</group-address>
+         <group-port>9876</group-port>
+         <broadcast-period>5000</broadcast-period>
+         <connector-ref>netty</connector-ref>
+      </broadcast-group>
+   </broadcast-groups>
+
+   <discovery-groups>
+      <discovery-group name="dg-group1">
+         <group-address>231.7.7.7</group-address>
+         <group-port>9876</group-port>
+         <refresh-timeout>10000</refresh-timeout>
+      </discovery-group>
+   </discovery-groups>
+   
+   <cluster-connections>
+      <cluster-connection name="my-cluster">
+         <address>jms</address>	 
+         <connector-ref>netty</connector-ref>
+	      <discovery-group-ref discovery-group-name="dg-group1"/>
+      </cluster-connection>
+   </cluster-connections>
+
+   <ha-policy>
+      <replication>
+         <master/>
+      </replication>
+   </ha-policy>
+   
+   <security-settings>
+      <security-setting match="#">
+         <permission type="createNonDurableQueue" roles="guest"/>
+         <permission type="deleteNonDurableQueue" roles="guest"/>
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+      </security-setting>
+   </security-settings>
+
+   <address-settings>
+      <!--default for catch all-->
+      <address-setting match="#">
+         <dead-letter-address>jms.queue.DLQ</dead-letter-address>
+         <expiry-address>jms.queue.ExpiryQueue</expiry-address>
+         <redelivery-delay>0</redelivery-delay>
+         <max-size-bytes>10485760</max-size-bytes>       
+         <message-counter-history-day-limit>10</message-counter-history-day-limit>
+         <address-full-policy>BLOCK</address-full-policy>
+      </address-setting>
+   </address-settings>
+
+   
+
+</configuration>


[38/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/ConnectionFactoryConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/ConnectionFactoryConfiguration.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/ConnectionFactoryConfiguration.java
index 478417d..747b72a 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/ConnectionFactoryConfiguration.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/ConnectionFactoryConfiguration.java
@@ -18,154 +18,155 @@ import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.core.journal.EncodingSupport;
 
 /**
- * A ConnectionFactoryConfiguration for {@link ConnectionFactory} objects.
+ * A ConnectionFactoryConfiguration for {@link javax.jms.ConnectionFactory} objects.
  *
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  */
 public interface ConnectionFactoryConfiguration extends EncodingSupport
 {
-
    boolean isPersisted();
 
    String getName();
 
+   ConnectionFactoryConfiguration setName(String name);
+
    String[] getBindings();
 
-   void setBindings(String[] bindings);
+   ConnectionFactoryConfiguration setBindings(String... bindings);
 
    String getDiscoveryGroupName();
 
-   void setDiscoveryGroupName(String discoveryGroupName);
+   ConnectionFactoryConfiguration setDiscoveryGroupName(String discoveryGroupName);
 
    List<String> getConnectorNames();
 
-   void setConnectorNames(List<String> connectorNames);
+   ConnectionFactoryConfiguration setConnectorNames(List<String> connectorNames);
 
    boolean isHA();
 
-   void setHA(boolean ha);
+   ConnectionFactoryConfiguration setHA(boolean ha);
 
    String getClientID();
 
-   void setClientID(String clientID);
+   ConnectionFactoryConfiguration setClientID(String clientID);
 
    long getClientFailureCheckPeriod();
 
-   void setClientFailureCheckPeriod(long clientFailureCheckPeriod);
+   ConnectionFactoryConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod);
 
    long getConnectionTTL();
 
-   void setConnectionTTL(long connectionTTL);
+   ConnectionFactoryConfiguration setConnectionTTL(long connectionTTL);
 
    long getCallTimeout();
 
-   void setCallTimeout(long callTimeout);
+   ConnectionFactoryConfiguration setCallTimeout(long callTimeout);
 
    long getCallFailoverTimeout();
 
-   void setCallFailoverTimeout(long callFailoverTimeout);
+   ConnectionFactoryConfiguration setCallFailoverTimeout(long callFailoverTimeout);
 
    boolean isCacheLargeMessagesClient();
 
-   void setCacheLargeMessagesClient(boolean cacheLargeMessagesClient);
+   ConnectionFactoryConfiguration setCacheLargeMessagesClient(boolean cacheLargeMessagesClient);
 
    int getMinLargeMessageSize();
 
-   void setMinLargeMessageSize(int minLargeMessageSize);
+   ConnectionFactoryConfiguration setMinLargeMessageSize(int minLargeMessageSize);
 
    boolean isCompressLargeMessages();
 
-   void setCompressLargeMessages(boolean avoidLargeMessages);
+   ConnectionFactoryConfiguration setCompressLargeMessages(boolean avoidLargeMessages);
 
    int getConsumerWindowSize();
 
-   void setConsumerWindowSize(int consumerWindowSize);
+   ConnectionFactoryConfiguration setConsumerWindowSize(int consumerWindowSize);
 
    int getConsumerMaxRate();
 
-   void setConsumerMaxRate(int consumerMaxRate);
+   ConnectionFactoryConfiguration setConsumerMaxRate(int consumerMaxRate);
 
    int getConfirmationWindowSize();
 
-   void setConfirmationWindowSize(int confirmationWindowSize);
+   ConnectionFactoryConfiguration setConfirmationWindowSize(int confirmationWindowSize);
 
    int getProducerWindowSize();
 
-   void setProducerWindowSize(int producerWindowSize);
+   ConnectionFactoryConfiguration setProducerWindowSize(int producerWindowSize);
 
    int getProducerMaxRate();
 
-   void setProducerMaxRate(int producerMaxRate);
+   ConnectionFactoryConfiguration setProducerMaxRate(int producerMaxRate);
 
    boolean isBlockOnAcknowledge();
 
-   void setBlockOnAcknowledge(boolean blockOnAcknowledge);
+   ConnectionFactoryConfiguration setBlockOnAcknowledge(boolean blockOnAcknowledge);
 
    boolean isBlockOnDurableSend();
 
-   void setBlockOnDurableSend(boolean blockOnDurableSend);
+   ConnectionFactoryConfiguration setBlockOnDurableSend(boolean blockOnDurableSend);
 
    boolean isBlockOnNonDurableSend();
 
-   void setBlockOnNonDurableSend(boolean blockOnNonDurableSend);
+   ConnectionFactoryConfiguration setBlockOnNonDurableSend(boolean blockOnNonDurableSend);
 
    boolean isAutoGroup();
 
-   void setAutoGroup(boolean autoGroup);
+   ConnectionFactoryConfiguration setAutoGroup(boolean autoGroup);
 
    boolean isPreAcknowledge();
 
-   void setPreAcknowledge(boolean preAcknowledge);
+   ConnectionFactoryConfiguration setPreAcknowledge(boolean preAcknowledge);
 
    String getLoadBalancingPolicyClassName();
 
-   void setLoadBalancingPolicyClassName(String loadBalancingPolicyClassName);
+   ConnectionFactoryConfiguration setLoadBalancingPolicyClassName(String loadBalancingPolicyClassName);
 
    int getTransactionBatchSize();
 
-   void setTransactionBatchSize(int transactionBatchSize);
+   ConnectionFactoryConfiguration setTransactionBatchSize(int transactionBatchSize);
 
    int getDupsOKBatchSize();
 
-   void setDupsOKBatchSize(int dupsOKBatchSize);
+   ConnectionFactoryConfiguration setDupsOKBatchSize(int dupsOKBatchSize);
 
    boolean isUseGlobalPools();
 
-   void setUseGlobalPools(boolean useGlobalPools);
+   ConnectionFactoryConfiguration setUseGlobalPools(boolean useGlobalPools);
 
    int getScheduledThreadPoolMaxSize();
 
-   void setScheduledThreadPoolMaxSize(int scheduledThreadPoolMaxSize);
+   ConnectionFactoryConfiguration setScheduledThreadPoolMaxSize(int scheduledThreadPoolMaxSize);
 
    int getThreadPoolMaxSize();
 
-   void setThreadPoolMaxSize(int threadPoolMaxSize);
+   ConnectionFactoryConfiguration setThreadPoolMaxSize(int threadPoolMaxSize);
 
    long getRetryInterval();
 
-   void setRetryInterval(long retryInterval);
+   ConnectionFactoryConfiguration setRetryInterval(long retryInterval);
 
    double getRetryIntervalMultiplier();
 
-   void setRetryIntervalMultiplier(double retryIntervalMultiplier);
+   ConnectionFactoryConfiguration setRetryIntervalMultiplier(double retryIntervalMultiplier);
 
    long getMaxRetryInterval();
 
-   void setMaxRetryInterval(long maxRetryInterval);
+   ConnectionFactoryConfiguration setMaxRetryInterval(long maxRetryInterval);
 
    int getReconnectAttempts();
 
-   void setReconnectAttempts(int reconnectAttempts);
+   ConnectionFactoryConfiguration setReconnectAttempts(int reconnectAttempts);
 
    boolean isFailoverOnInitialConnection();
 
-   void setFailoverOnInitialConnection(boolean failover);
+   ConnectionFactoryConfiguration setFailoverOnInitialConnection(boolean failover);
 
    String getGroupID();
 
-   void setGroupID(String groupID);
+   ConnectionFactoryConfiguration setGroupID(String groupID);
 
-   void setFactoryType(JMSFactoryType factType);
+   ConnectionFactoryConfiguration setFactoryType(JMSFactoryType factType);
 
    JMSFactoryType getFactoryType();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSConfiguration.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSConfiguration.java
index 06ba294..a7f332a 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSConfiguration.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSConfiguration.java
@@ -25,15 +25,23 @@ import javax.naming.Context;
  */
 public interface JMSConfiguration
 {
-   void setContext(Context context);
+   JMSConfiguration setContext(Context context);
 
    Context getContext();
 
    List<JMSQueueConfiguration> getQueueConfigurations();
 
+   JMSConfiguration setQueueConfigurations(List<JMSQueueConfiguration> queueConfigurations);
+
    List<TopicConfiguration> getTopicConfigurations();
 
+   JMSConfiguration setTopicConfigurations(List<TopicConfiguration> topicConfigurations);
+
    List<ConnectionFactoryConfiguration> getConnectionFactoryConfigurations();
 
+   JMSConfiguration setConnectionFactoryConfigurations(List<ConnectionFactoryConfiguration> connectionFactoryConfigurations);
+
    String getDomain();
+
+   JMSConfiguration setDomain(String domain);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSQueueConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSQueueConfiguration.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSQueueConfiguration.java
index 8d4579b..1f810b1 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSQueueConfiguration.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/JMSQueueConfiguration.java
@@ -23,9 +23,17 @@ public interface JMSQueueConfiguration
 {
    String getName();
 
+   JMSQueueConfiguration setName(String name);
+
    String getSelector();
 
+   JMSQueueConfiguration setSelector(String selector);
+
    boolean isDurable();
 
+   JMSQueueConfiguration setDurable(boolean durable);
+
    String[] getBindings();
+
+   JMSQueueConfiguration setBindings(String[] bindings);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/TopicConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/TopicConfiguration.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/TopicConfiguration.java
index 93ea4de..0675262 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/TopicConfiguration.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/TopicConfiguration.java
@@ -21,5 +21,9 @@ public interface TopicConfiguration
 {
    String getName();
 
+   TopicConfiguration setName(String name);
+
    String[] getBindings();
+
+   TopicConfiguration setBindings(String... bindings);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java
index 9aef0d7..08fc42f 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/ConnectionFactoryConfigurationImpl.java
@@ -38,15 +38,15 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
 
    // Attributes ----------------------------------------------------
 
-   private String name;
+   private String name = null;
 
-   private boolean persisted;
+   private boolean persisted = false;
 
-   private String[] bindings;
+   private String[] bindings = null;
 
-   private List<String> connectorNames;
+   private List<String> connectorNames = null;
 
-   private String discoveryGroupName;
+   private String discoveryGroupName = null;
 
    private String clientID = null;
 
@@ -118,30 +118,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
 
    // Constructors --------------------------------------------------
 
-   /**
-    * To be used on persistence only
-    */
    public ConnectionFactoryConfigurationImpl()
    {
    }
 
-   public ConnectionFactoryConfigurationImpl(final String name,
-                                             final boolean ha,
-                                             final List<String> connectorNames,
-                                             final String... bindings)
-   {
-      this(name, ha, bindings);
-      this.connectorNames = connectorNames;
-   }
-
-   public ConnectionFactoryConfigurationImpl(final String name, final boolean ha, final String... bindings)
-   {
-      this.name = name;
-      this.ha = ha;
-      this.bindings = new String[bindings.length];
-      System.arraycopy(bindings, 0, this.bindings, 0, bindings.length);
-   }
-
    // ConnectionFactoryConfiguration implementation -----------------
 
    public String[] getBindings()
@@ -149,9 +129,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return bindings;
    }
 
-   public void setBindings(final String[] bindings)
+   public ConnectionFactoryConfiguration setBindings(final String... bindings)
    {
       this.bindings = bindings;
+      return this;
    }
 
    public String getName()
@@ -159,6 +140,12 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return name;
    }
 
+   public ConnectionFactoryConfiguration setName(String name)
+   {
+      this.name = name;
+      return this;
+   }
+
    public boolean isPersisted()
    {
       return persisted;
@@ -175,9 +162,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
    /**
     * @param discoveryGroupName the discoveryGroupName to set
     */
-   public void setDiscoveryGroupName(String discoveryGroupName)
+   public ConnectionFactoryConfiguration setDiscoveryGroupName(String discoveryGroupName)
    {
       this.discoveryGroupName = discoveryGroupName;
+      return this;
    }
 
    public List<String> getConnectorNames()
@@ -185,9 +173,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return connectorNames;
    }
 
-   public void setConnectorNames(final List<String> connectorNames)
+   public ConnectionFactoryConfiguration setConnectorNames(final List<String> connectorNames)
    {
       this.connectorNames = connectorNames;
+      return this;
    }
 
    public boolean isHA()
@@ -195,9 +184,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return ha;
    }
 
-   public void setHA(final boolean ha)
+   public ConnectionFactoryConfiguration setHA(final boolean ha)
    {
       this.ha = ha;
+      return this;
    }
 
    public String getClientID()
@@ -205,9 +195,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return clientID;
    }
 
-   public void setClientID(final String clientID)
+   public ConnectionFactoryConfiguration setClientID(final String clientID)
    {
       this.clientID = clientID;
+      return this;
    }
 
    public long getClientFailureCheckPeriod()
@@ -215,9 +206,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return clientFailureCheckPeriod;
    }
 
-   public void setClientFailureCheckPeriod(final long clientFailureCheckPeriod)
+   public ConnectionFactoryConfiguration setClientFailureCheckPeriod(final long clientFailureCheckPeriod)
    {
       this.clientFailureCheckPeriod = clientFailureCheckPeriod;
+      return this;
    }
 
    public long getConnectionTTL()
@@ -225,9 +217,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return connectionTTL;
    }
 
-   public void setConnectionTTL(final long connectionTTL)
+   public ConnectionFactoryConfiguration setConnectionTTL(final long connectionTTL)
    {
       this.connectionTTL = connectionTTL;
+      return this;
    }
 
    public long getCallTimeout()
@@ -235,9 +228,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return callTimeout;
    }
 
-   public void setCallTimeout(final long callTimeout)
+   public ConnectionFactoryConfiguration setCallTimeout(final long callTimeout)
    {
       this.callTimeout = callTimeout;
+      return this;
    }
 
    public long getCallFailoverTimeout()
@@ -245,9 +239,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return callFailoverTimeout;
    }
 
-   public void setCallFailoverTimeout(long callFailoverTimeout)
+   public ConnectionFactoryConfiguration setCallFailoverTimeout(long callFailoverTimeout)
    {
       this.callFailoverTimeout = callFailoverTimeout;
+      return this;
    }
 
    public boolean isCacheLargeMessagesClient()
@@ -255,9 +250,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return cacheLargeMessagesClient;
    }
 
-   public void setCacheLargeMessagesClient(final boolean cacheLargeMessagesClient)
+   public ConnectionFactoryConfiguration setCacheLargeMessagesClient(final boolean cacheLargeMessagesClient)
    {
       this.cacheLargeMessagesClient = cacheLargeMessagesClient;
+      return this;
    }
 
    public int getMinLargeMessageSize()
@@ -265,9 +261,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return minLargeMessageSize;
    }
 
-   public void setMinLargeMessageSize(final int minLargeMessageSize)
+   public ConnectionFactoryConfiguration setMinLargeMessageSize(final int minLargeMessageSize)
    {
       this.minLargeMessageSize = minLargeMessageSize;
+      return this;
    }
 
    public int getConsumerWindowSize()
@@ -275,9 +272,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return consumerWindowSize;
    }
 
-   public void setConsumerWindowSize(final int consumerWindowSize)
+   public ConnectionFactoryConfiguration setConsumerWindowSize(final int consumerWindowSize)
    {
       this.consumerWindowSize = consumerWindowSize;
+      return this;
    }
 
    public int getConsumerMaxRate()
@@ -285,9 +283,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return consumerMaxRate;
    }
 
-   public void setConsumerMaxRate(final int consumerMaxRate)
+   public ConnectionFactoryConfiguration setConsumerMaxRate(final int consumerMaxRate)
    {
       this.consumerMaxRate = consumerMaxRate;
+      return this;
    }
 
    public int getConfirmationWindowSize()
@@ -295,9 +294,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return confirmationWindowSize;
    }
 
-   public void setConfirmationWindowSize(final int confirmationWindowSize)
+   public ConnectionFactoryConfiguration setConfirmationWindowSize(final int confirmationWindowSize)
    {
       this.confirmationWindowSize = confirmationWindowSize;
+      return this;
    }
 
    public int getProducerMaxRate()
@@ -305,9 +305,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return producerMaxRate;
    }
 
-   public void setProducerMaxRate(final int producerMaxRate)
+   public ConnectionFactoryConfiguration setProducerMaxRate(final int producerMaxRate)
    {
       this.producerMaxRate = producerMaxRate;
+      return this;
    }
 
    public int getProducerWindowSize()
@@ -315,9 +316,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return producerWindowSize;
    }
 
-   public void setProducerWindowSize(final int producerWindowSize)
+   public ConnectionFactoryConfiguration setProducerWindowSize(final int producerWindowSize)
    {
       this.producerWindowSize = producerWindowSize;
+      return this;
    }
 
    public boolean isBlockOnAcknowledge()
@@ -325,9 +327,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return blockOnAcknowledge;
    }
 
-   public void setBlockOnAcknowledge(final boolean blockOnAcknowledge)
+   public ConnectionFactoryConfiguration setBlockOnAcknowledge(final boolean blockOnAcknowledge)
    {
       this.blockOnAcknowledge = blockOnAcknowledge;
+      return this;
    }
 
    public boolean isBlockOnDurableSend()
@@ -335,9 +338,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return blockOnDurableSend;
    }
 
-   public void setBlockOnDurableSend(final boolean blockOnDurableSend)
+   public ConnectionFactoryConfiguration setBlockOnDurableSend(final boolean blockOnDurableSend)
    {
       this.blockOnDurableSend = blockOnDurableSend;
+      return this;
    }
 
    public boolean isBlockOnNonDurableSend()
@@ -345,9 +349,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return blockOnNonDurableSend;
    }
 
-   public void setBlockOnNonDurableSend(final boolean blockOnNonDurableSend)
+   public ConnectionFactoryConfiguration setBlockOnNonDurableSend(final boolean blockOnNonDurableSend)
    {
       this.blockOnNonDurableSend = blockOnNonDurableSend;
+      return this;
    }
 
    public boolean isAutoGroup()
@@ -355,9 +360,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return autoGroup;
    }
 
-   public void setAutoGroup(final boolean autoGroup)
+   public ConnectionFactoryConfiguration setAutoGroup(final boolean autoGroup)
    {
       this.autoGroup = autoGroup;
+      return this;
    }
 
    public boolean isPreAcknowledge()
@@ -365,9 +371,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return preAcknowledge;
    }
 
-   public void setPreAcknowledge(final boolean preAcknowledge)
+   public ConnectionFactoryConfiguration setPreAcknowledge(final boolean preAcknowledge)
    {
       this.preAcknowledge = preAcknowledge;
+      return this;
    }
 
    public String getLoadBalancingPolicyClassName()
@@ -375,9 +382,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return loadBalancingPolicyClassName;
    }
 
-   public void setLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName)
+   public ConnectionFactoryConfiguration setLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName)
    {
       this.loadBalancingPolicyClassName = loadBalancingPolicyClassName;
+      return this;
    }
 
    public int getTransactionBatchSize()
@@ -385,9 +393,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return transactionBatchSize;
    }
 
-   public void setTransactionBatchSize(final int transactionBatchSize)
+   public ConnectionFactoryConfiguration setTransactionBatchSize(final int transactionBatchSize)
    {
       this.transactionBatchSize = transactionBatchSize;
+      return this;
    }
 
    public int getDupsOKBatchSize()
@@ -395,9 +404,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return dupsOKBatchSize;
    }
 
-   public void setDupsOKBatchSize(final int dupsOKBatchSize)
+   public ConnectionFactoryConfiguration setDupsOKBatchSize(final int dupsOKBatchSize)
    {
       this.dupsOKBatchSize = dupsOKBatchSize;
+      return this;
    }
 
    public long getInitialWaitTimeout()
@@ -405,9 +415,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return initialWaitTimeout;
    }
 
-   public void setInitialWaitTimeout(final long initialWaitTimeout)
+   public ConnectionFactoryConfiguration setInitialWaitTimeout(final long initialWaitTimeout)
    {
       this.initialWaitTimeout = initialWaitTimeout;
+      return this;
    }
 
    public boolean isUseGlobalPools()
@@ -415,9 +426,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return useGlobalPools;
    }
 
-   public void setUseGlobalPools(final boolean useGlobalPools)
+   public ConnectionFactoryConfiguration setUseGlobalPools(final boolean useGlobalPools)
    {
       this.useGlobalPools = useGlobalPools;
+      return this;
    }
 
    public int getScheduledThreadPoolMaxSize()
@@ -425,9 +437,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return scheduledThreadPoolMaxSize;
    }
 
-   public void setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize)
+   public ConnectionFactoryConfiguration setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize)
    {
       this.scheduledThreadPoolMaxSize = scheduledThreadPoolMaxSize;
+      return this;
    }
 
    public int getThreadPoolMaxSize()
@@ -435,9 +448,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return threadPoolMaxSize;
    }
 
-   public void setThreadPoolMaxSize(final int threadPoolMaxSize)
+   public ConnectionFactoryConfiguration setThreadPoolMaxSize(final int threadPoolMaxSize)
    {
       this.threadPoolMaxSize = threadPoolMaxSize;
+      return this;
    }
 
    public long getRetryInterval()
@@ -445,9 +459,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return retryInterval;
    }
 
-   public void setRetryInterval(final long retryInterval)
+   public ConnectionFactoryConfiguration setRetryInterval(final long retryInterval)
    {
       this.retryInterval = retryInterval;
+      return this;
    }
 
    public double getRetryIntervalMultiplier()
@@ -455,9 +470,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return retryIntervalMultiplier;
    }
 
-   public void setRetryIntervalMultiplier(final double retryIntervalMultiplier)
+   public ConnectionFactoryConfiguration setRetryIntervalMultiplier(final double retryIntervalMultiplier)
    {
       this.retryIntervalMultiplier = retryIntervalMultiplier;
+      return this;
    }
 
    public long getMaxRetryInterval()
@@ -465,9 +481,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return maxRetryInterval;
    }
 
-   public void setMaxRetryInterval(final long maxRetryInterval)
+   public ConnectionFactoryConfiguration setMaxRetryInterval(final long maxRetryInterval)
    {
       this.maxRetryInterval = maxRetryInterval;
+      return this;
    }
 
    public int getReconnectAttempts()
@@ -475,9 +492,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return reconnectAttempts;
    }
 
-   public void setReconnectAttempts(final int reconnectAttempts)
+   public ConnectionFactoryConfiguration setReconnectAttempts(final int reconnectAttempts)
    {
       this.reconnectAttempts = reconnectAttempts;
+      return this;
    }
 
    public boolean isFailoverOnInitialConnection()
@@ -485,9 +503,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return failoverOnInitialConnection;
    }
 
-   public void setFailoverOnInitialConnection(final boolean failover)
+   public ConnectionFactoryConfiguration setFailoverOnInitialConnection(final boolean failover)
    {
       failoverOnInitialConnection = failover;
+      return this;
    }
 
    public String getGroupID()
@@ -495,9 +514,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return groupID;
    }
 
-   public void setGroupID(final String groupID)
+   public ConnectionFactoryConfiguration setGroupID(final String groupID)
    {
       this.groupID = groupID;
+      return this;
    }
 
    // Encoding Support Implementation --------------------------------------------------------------
@@ -790,9 +810,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
       return size;
    }
 
-   public void setFactoryType(final JMSFactoryType factoryType)
+   public ConnectionFactoryConfiguration setFactoryType(final JMSFactoryType factoryType)
    {
       this.factoryType = factoryType;
+      return this;
    }
 
    public JMSFactoryType getFactoryType()
@@ -801,9 +822,10 @@ public class ConnectionFactoryConfigurationImpl implements ConnectionFactoryConf
    }
 
    @Override
-   public void setCompressLargeMessages(boolean compressLargeMessage)
+   public ConnectionFactoryConfiguration setCompressLargeMessages(boolean compressLargeMessage)
    {
       this.compressLargeMessage = compressLargeMessage;
+      return this;
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSConfigurationImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSConfigurationImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSConfigurationImpl.java
index 002cdd7..eaa8761 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSConfigurationImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSConfigurationImpl.java
@@ -30,38 +30,31 @@ import org.hornetq.jms.server.config.TopicConfiguration;
  */
 public class JMSConfigurationImpl implements JMSConfiguration
 {
+   private List<ConnectionFactoryConfiguration> connectionFactoryConfigurations = new ArrayList<ConnectionFactoryConfiguration>();
 
-   private final List<ConnectionFactoryConfiguration> connectionFactoryConfigurations = new ArrayList<ConnectionFactoryConfiguration>();
+   private List<JMSQueueConfiguration> queueConfigurations = new ArrayList<JMSQueueConfiguration>();
 
-   private final List<JMSQueueConfiguration> queueConfigurations = new ArrayList<JMSQueueConfiguration>();
+   private List<TopicConfiguration> topicConfigurations = new ArrayList<TopicConfiguration>();
 
-   private final List<TopicConfiguration> topicConfigurations = new ArrayList<TopicConfiguration>();
-
-   private final String domain;
+   private String domain = HornetQDefaultConfiguration.getDefaultJmxDomain();
 
    private Context context = null;
 
+   // JMSConfiguration implementation -------------------------------
+
    public JMSConfigurationImpl()
    {
-      domain = HornetQDefaultConfiguration.getDefaultJmxDomain();
    }
 
-   public JMSConfigurationImpl(final List<ConnectionFactoryConfiguration> connectionFactoryConfigurations,
-                               final List<JMSQueueConfiguration> queueConfigurations,
-                               final List<TopicConfiguration> topicConfigurations,
-                               final String domain)
+   public List<ConnectionFactoryConfiguration> getConnectionFactoryConfigurations()
    {
-      this.connectionFactoryConfigurations.addAll(connectionFactoryConfigurations);
-      this.queueConfigurations.addAll(queueConfigurations);
-      this.topicConfigurations.addAll(topicConfigurations);
-      this.domain = domain != null ? domain : HornetQDefaultConfiguration.getDefaultJmxDomain();
+      return connectionFactoryConfigurations;
    }
 
-   // JMSConfiguration implementation -------------------------------
-
-   public List<ConnectionFactoryConfiguration> getConnectionFactoryConfigurations()
+   public JMSConfigurationImpl setConnectionFactoryConfigurations(List<ConnectionFactoryConfiguration> connectionFactoryConfigurations)
    {
-      return connectionFactoryConfigurations;
+      this.connectionFactoryConfigurations = connectionFactoryConfigurations;
+      return this;
    }
 
    public List<JMSQueueConfiguration> getQueueConfigurations()
@@ -69,23 +62,42 @@ public class JMSConfigurationImpl implements JMSConfiguration
       return queueConfigurations;
    }
 
+   public JMSConfigurationImpl setQueueConfigurations(List<JMSQueueConfiguration> queueConfigurations)
+   {
+      this.queueConfigurations = queueConfigurations;
+      return this;
+   }
+
    public List<TopicConfiguration> getTopicConfigurations()
    {
       return topicConfigurations;
    }
 
+   public JMSConfigurationImpl setTopicConfigurations(List<TopicConfiguration> topicConfigurations)
+   {
+      this.topicConfigurations = topicConfigurations;
+      return this;
+   }
+
    public Context getContext()
    {
       return context;
    }
 
-   public void setContext(final Context context)
+   public JMSConfigurationImpl setContext(final Context context)
    {
       this.context = context;
+      return this;
    }
 
    public String getDomain()
    {
       return domain;
    }
+
+   public JMSConfigurationImpl setDomain(final String domain)
+   {
+      this.domain = domain;
+      return this;
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSQueueConfigurationImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSQueueConfigurationImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSQueueConfigurationImpl.java
index f3ced90..2fccc6f 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSQueueConfigurationImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/JMSQueueConfigurationImpl.java
@@ -29,28 +29,20 @@ public class JMSQueueConfigurationImpl implements JMSQueueConfiguration
 
    // Attributes ----------------------------------------------------
 
-   private final String name;
+   private String name = null;
 
-   private final String selector;
+   private String selector = null;
 
-   private final boolean durable;
+   private boolean durable = true;
 
-   private final String[] bindings;
+   private String[] bindings = null;
 
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
 
-   public JMSQueueConfigurationImpl(final String name,
-                                 final String selector,
-                                 final boolean durable,
-                                 final String... bindings)
+   public JMSQueueConfigurationImpl()
    {
-      this.name = name;
-      this.selector = selector;
-      this.durable = durable;
-      this.bindings = new String[bindings.length];
-      System.arraycopy(bindings, 0, this.bindings, 0, bindings.length);
    }
 
    // QueueConfiguration implementation -----------------------------
@@ -60,21 +52,45 @@ public class JMSQueueConfigurationImpl implements JMSQueueConfiguration
       return bindings;
    }
 
+   public JMSQueueConfigurationImpl setBindings(String... bindings)
+   {
+      this.bindings = bindings;
+      return this;
+   }
+
    public String getName()
    {
       return name;
    }
 
+   public JMSQueueConfigurationImpl setName(String name)
+   {
+      this.name = name;
+      return this;
+   }
+
    public String getSelector()
    {
       return selector;
    }
 
+   public JMSQueueConfigurationImpl setSelector(String selector)
+   {
+      this.selector = selector;
+      return this;
+   }
+
    public boolean isDurable()
    {
       return durable;
    }
 
+   public JMSQueueConfigurationImpl setDurable(boolean durable)
+   {
+      this.durable = durable;
+      return this;
+   }
+
    // Public --------------------------------------------------------
 
    // Package protected ---------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/TopicConfigurationImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/TopicConfigurationImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/TopicConfigurationImpl.java
index b6a3727..e105437 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/TopicConfigurationImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/config/impl/TopicConfigurationImpl.java
@@ -29,19 +29,16 @@ public class TopicConfigurationImpl implements TopicConfiguration
 
    // Attributes ----------------------------------------------------
 
-   private final String name;
+   private String name;
 
-   private final String[] bindings;
+   private String[] bindings;
 
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
 
-   public TopicConfigurationImpl(final String name, final String... bindings)
+   public TopicConfigurationImpl()
    {
-      this.name = name;
-      this.bindings = new String[bindings.length];
-      System.arraycopy(bindings, 0, this.bindings, 0, bindings.length);
    }
 
    // TopicConfiguration implementation -----------------------------
@@ -51,11 +48,23 @@ public class TopicConfigurationImpl implements TopicConfiguration
       return bindings;
    }
 
+   public TopicConfigurationImpl setBindings(String... bindings)
+   {
+      this.bindings = bindings;
+      return this;
+   }
+
    public String getName()
    {
       return name;
    }
 
+   public TopicConfigurationImpl setName(String name)
+   {
+      this.name = name;
+      return this;
+   }
+
    // Public --------------------------------------------------------
 
    // Package protected ---------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerConfigParserImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerConfigParserImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerConfigParserImpl.java
index 5380bdc..c0b9583 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerConfigParserImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerConfigParserImpl.java
@@ -369,10 +369,8 @@ public final class JMSServerConfigParserImpl implements JMSServerConfigParser
 
       if (discoveryGroupName != null)
       {
-         cfConfig = new ConnectionFactoryConfigurationImpl(name,
-                                                           ha,
-                                                           strbindings);
-         cfConfig.setDiscoveryGroupName(discoveryGroupName);
+         cfConfig = new ConnectionFactoryConfigurationImpl()
+            .setDiscoveryGroupName(discoveryGroupName);
       }
       else
       {
@@ -381,40 +379,46 @@ public final class JMSServerConfigParserImpl implements JMSServerConfigParser
          {
             connectors.add(connectorName);
          }
-         cfConfig = new ConnectionFactoryConfigurationImpl(name, ha, connectors, strbindings);
+         cfConfig = new ConnectionFactoryConfigurationImpl()
+            .setConnectorNames(connectors);
       }
 
-      cfConfig.setFactoryType(factType);
-      cfConfig.setClientID(clientID);
-      cfConfig.setClientFailureCheckPeriod(clientFailureCheckPeriod);
-      cfConfig.setConnectionTTL(connectionTTL);
-      cfConfig.setCallTimeout(callTimeout);
-      cfConfig.setCallFailoverTimeout(callFailoverTimeout);
-      cfConfig.setCacheLargeMessagesClient(cacheLargeMessagesClient);
-      cfConfig.setMinLargeMessageSize(minLargeMessageSize);
-      cfConfig.setCompressLargeMessages(compressLargeMessages);
-      cfConfig.setConsumerWindowSize(consumerWindowSize);
-      cfConfig.setConsumerMaxRate(consumerMaxRate);
-      cfConfig.setConfirmationWindowSize(confirmationWindowSize);
-      cfConfig.setProducerWindowSize(producerWindowSize);
-      cfConfig.setProducerMaxRate(producerMaxRate);
-      cfConfig.setBlockOnAcknowledge(blockOnAcknowledge);
-      cfConfig.setBlockOnDurableSend(blockOnDurableSend);
-      cfConfig.setBlockOnNonDurableSend(blockOnNonDurableSend);
-      cfConfig.setAutoGroup(autoGroup);
-      cfConfig.setPreAcknowledge(preAcknowledge);
-      cfConfig.setLoadBalancingPolicyClassName(connectionLoadBalancingPolicyClassName);
-      cfConfig.setTransactionBatchSize(transactionBatchSize);
-      cfConfig.setDupsOKBatchSize(dupsOKBatchSize);
-      cfConfig.setUseGlobalPools(useGlobalPools);
-      cfConfig.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize);
-      cfConfig.setThreadPoolMaxSize(threadPoolMaxSize);
-      cfConfig.setRetryInterval(retryInterval);
-      cfConfig.setRetryIntervalMultiplier(retryIntervalMultiplier);
-      cfConfig.setMaxRetryInterval(maxRetryInterval);
-      cfConfig.setReconnectAttempts(reconnectAttempts);
-      cfConfig.setFailoverOnInitialConnection(failoverOnInitialConnection);
-      cfConfig.setGroupID(groupid);
+      cfConfig
+         .setName(name)
+         .setHA(ha)
+         .setBindings(strbindings)
+         .setFactoryType(factType)
+         .setClientID(clientID)
+         .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+         .setConnectionTTL(connectionTTL)
+         .setCallTimeout(callTimeout)
+         .setCallFailoverTimeout(callFailoverTimeout)
+         .setCacheLargeMessagesClient(cacheLargeMessagesClient)
+         .setMinLargeMessageSize(minLargeMessageSize)
+         .setCompressLargeMessages(compressLargeMessages)
+         .setConsumerWindowSize(consumerWindowSize)
+         .setConsumerMaxRate(consumerMaxRate)
+         .setConfirmationWindowSize(confirmationWindowSize)
+         .setProducerWindowSize(producerWindowSize)
+         .setProducerMaxRate(producerMaxRate)
+         .setBlockOnAcknowledge(blockOnAcknowledge)
+         .setBlockOnDurableSend(blockOnDurableSend)
+         .setBlockOnNonDurableSend(blockOnNonDurableSend)
+         .setAutoGroup(autoGroup)
+         .setPreAcknowledge(preAcknowledge)
+         .setLoadBalancingPolicyClassName(connectionLoadBalancingPolicyClassName)
+         .setTransactionBatchSize(transactionBatchSize)
+         .setDupsOKBatchSize(dupsOKBatchSize)
+         .setUseGlobalPools(useGlobalPools)
+         .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize)
+         .setThreadPoolMaxSize(threadPoolMaxSize)
+         .setRetryInterval(retryInterval)
+         .setRetryIntervalMultiplier(retryIntervalMultiplier)
+         .setMaxRetryInterval(maxRetryInterval)
+         .setReconnectAttempts(reconnectAttempts)
+         .setFailoverOnInitialConnection(failoverOnInitialConnection)
+         .setGroupID(groupid);
+
       return cfConfig;
    }
 
@@ -466,7 +470,9 @@ public final class JMSServerConfigParserImpl implements JMSServerConfigParser
     */
    protected TopicConfiguration newTopic(final String topicName, final String[] strBindings)
    {
-      return new TopicConfigurationImpl(topicName, strBindings);
+      return new TopicConfigurationImpl()
+         .setName(topicName)
+         .setBindings(strBindings);
    }
 
    /**
@@ -483,7 +489,11 @@ public final class JMSServerConfigParserImpl implements JMSServerConfigParser
                                             final boolean durable,
                                             final String[] jndiArray)
    {
-      return new JMSQueueConfigurationImpl(queueName, selectorString, durable, jndiArray);
+      return new JMSQueueConfigurationImpl().
+         setName(queueName).
+         setSelector(selectorString).
+         setDurable(durable).
+         setBindings(jndiArray);
    }
 
    /**
@@ -499,7 +509,10 @@ public final class JMSServerConfigParserImpl implements JMSServerConfigParser
                                         final ArrayList<TopicConfiguration> topics,
                                         final ArrayList<ConnectionFactoryConfiguration> cfs, String domain)
    {
-      JMSConfiguration value = new JMSConfigurationImpl(cfs, queues, topics, domain);
-      return value;
+      return new JMSConfigurationImpl()
+         .setConnectionFactoryConfigurations(cfs)
+         .setQueueConfigurations(queues)
+         .setTopicConfigurations(topics)
+         .setDomain(domain);
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerManagerImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerManagerImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerManagerImpl.java
index 592a31a..08c6a27 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerManagerImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/JMSServerManagerImpl.java
@@ -16,6 +16,7 @@ import javax.naming.Context;
 import javax.naming.InitialContext;
 import javax.naming.NamingException;
 import javax.transaction.xa.Xid;
+
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
@@ -52,6 +53,7 @@ import org.hornetq.core.server.ActivateCallback;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.Queue;
 import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.management.Notification;
 import org.hornetq.core.settings.impl.AddressSettings;
 import org.hornetq.core.transaction.ResourceManager;
 import org.hornetq.core.transaction.Transaction;
@@ -77,10 +79,12 @@ import org.hornetq.jms.server.config.JMSQueueConfiguration;
 import org.hornetq.jms.server.config.TopicConfiguration;
 import org.hornetq.jms.server.config.impl.ConnectionFactoryConfigurationImpl;
 import org.hornetq.jms.server.management.JMSManagementService;
+import org.hornetq.jms.server.management.JMSNotificationType;
 import org.hornetq.jms.server.management.impl.JMSManagementServiceImpl;
 import org.hornetq.jms.transaction.JMSTransactionDetail;
 import org.hornetq.spi.core.naming.BindingRegistry;
 import org.hornetq.utils.TimeAndCounterIDGenerator;
+import org.hornetq.utils.TypedProperties;
 import org.hornetq.utils.json.JSONArray;
 import org.hornetq.utils.json.JSONObject;
 
@@ -338,6 +342,12 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
       }
    }
 
+   @Override
+   public void activationComplete()
+   {
+
+   }
+
    public void recoverJndiBindings(String name, PersistedType type) throws NamingException
    {
       List<String> bindings = unRecoveredJndi.get(name);
@@ -628,6 +638,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
          }
       });
 
+      sendNotification(JMSNotificationType.QUEUE_CREATED, queueName);
       return true;
    }
 
@@ -683,6 +694,7 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
          }
       });
 
+      sendNotification(JMSNotificationType.TOPIC_CREATED, topicName);
       return true;
 
    }
@@ -901,18 +913,28 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
    {
       checkInitialised();
 
-      removeFromJNDI(queues, queueJNDI, name);
+      server.destroyQueue(HornetQDestination.createQueueAddressFromName(name), null, !removeConsumers, removeConsumers);
 
-      queues.remove(name);
-      queueJNDI.remove(name);
+      // if the queue has consumers and 'removeConsumers' is false then the queue won't actually be removed
+      // therefore only remove the queue from JNDI, etc. if the queue is actually removed
+      if (this.server.getPostOffice().getBinding(HornetQDestination.createQueueAddressFromName(name)) == null)
+      {
+         removeFromJNDI(queues, queueJNDI, name);
 
-      jmsManagementService.unregisterQueue(name);
+         queues.remove(name);
+         queueJNDI.remove(name);
 
-      server.destroyQueue(HornetQDestination.createQueueAddressFromName(name), null, false, removeConsumers);
+         jmsManagementService.unregisterQueue(name);
 
-      storage.deleteDestination(PersistedType.Queue, name);
+         storage.deleteDestination(PersistedType.Queue, name);
 
-      return true;
+         sendNotification(JMSNotificationType.QUEUE_DESTROYED, name);
+         return true;
+      }
+      else
+      {
+         return false;
+      }
    }
 
    public synchronized boolean destroyTopic(final String name) throws Exception
@@ -923,14 +945,6 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
    public synchronized boolean destroyTopic(final String name, final boolean removeConsumers) throws Exception
    {
       checkInitialised();
-
-      removeFromJNDI(topics, topicJNDI, name);
-
-      topics.remove(name);
-      topicJNDI.remove(name);
-
-      jmsManagementService.unregisterTopic(name);
-
       AddressControl addressControl = (AddressControl) server.getManagementService()
          .getResource(ResourceNames.CORE_ADDRESS + HornetQDestination.createTopicAddressFromName(name));
       if (addressControl != null)
@@ -950,9 +964,30 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
                server.destroyQueue(SimpleString.toSimpleString(queueName), null, !removeConsumers, removeConsumers);
             }
          }
+
+         if (addressControl.getQueueNames().length == 0)
+         {
+            removeFromJNDI(topics, topicJNDI, name);
+
+            topics.remove(name);
+            topicJNDI.remove(name);
+
+            jmsManagementService.unregisterTopic(name);
+
+            storage.deleteDestination(PersistedType.Topic, name);
+
+            sendNotification(JMSNotificationType.TOPIC_DESTROYED, name);
+            return true;
+         }
+         else
+         {
+            return false;
+         }
+      }
+      else
+      {
+         return false;
       }
-      storage.deleteDestination(PersistedType.Topic, name);
-      return true;
    }
 
    public synchronized void createConnectionFactory(final String name,
@@ -965,8 +1000,12 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
       HornetQConnectionFactory cf = connectionFactories.get(name);
       if (cf == null)
       {
-         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl(name, ha, connectorNames);
-         configuration.setFactoryType(cfType);
+         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl()
+            .setName(name)
+            .setHA(ha)
+            .setConnectorNames(connectorNames)
+            .setFactoryType(cfType);
+
          createConnectionFactory(true, configuration, jndiBindings);
       }
    }
@@ -1011,37 +1050,41 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
       HornetQConnectionFactory cf = connectionFactories.get(name);
       if (cf == null)
       {
-         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl(name, ha, connectorNames);
-         configuration.setClientID(clientID);
-         configuration.setClientFailureCheckPeriod(clientFailureCheckPeriod);
-         configuration.setConnectionTTL(connectionTTL);
-         configuration.setFactoryType(cfType);
-         configuration.setCallTimeout(callTimeout);
-         configuration.setCallFailoverTimeout(callFailoverTimeout);
-         configuration.setCacheLargeMessagesClient(cacheLargeMessagesClient);
-         configuration.setMinLargeMessageSize(minLargeMessageSize);
-         configuration.setConsumerWindowSize(consumerWindowSize);
-         configuration.setConsumerMaxRate(consumerMaxRate);
-         configuration.setConfirmationWindowSize(confirmationWindowSize);
-         configuration.setProducerWindowSize(producerWindowSize);
-         configuration.setProducerMaxRate(producerMaxRate);
-         configuration.setBlockOnAcknowledge(blockOnAcknowledge);
-         configuration.setBlockOnDurableSend(blockOnDurableSend);
-         configuration.setBlockOnNonDurableSend(blockOnNonDurableSend);
-         configuration.setAutoGroup(autoGroup);
-         configuration.setPreAcknowledge(preAcknowledge);
-         configuration.setLoadBalancingPolicyClassName(loadBalancingPolicyClassName);
-         configuration.setTransactionBatchSize(transactionBatchSize);
-         configuration.setDupsOKBatchSize(dupsOKBatchSize);
-         configuration.setUseGlobalPools(useGlobalPools);
-         configuration.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize);
-         configuration.setThreadPoolMaxSize(threadPoolMaxSize);
-         configuration.setRetryInterval(retryInterval);
-         configuration.setRetryIntervalMultiplier(retryIntervalMultiplier);
-         configuration.setMaxRetryInterval(maxRetryInterval);
-         configuration.setReconnectAttempts(reconnectAttempts);
-         configuration.setFailoverOnInitialConnection(failoverOnInitialConnection);
-         configuration.setGroupID(groupId);
+         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl()
+            .setName(name)
+            .setHA(ha)
+            .setConnectorNames(connectorNames)
+            .setClientID(clientID)
+            .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+            .setConnectionTTL(connectionTTL)
+            .setFactoryType(cfType)
+            .setCallTimeout(callTimeout)
+            .setCallFailoverTimeout(callFailoverTimeout)
+            .setCacheLargeMessagesClient(cacheLargeMessagesClient)
+            .setMinLargeMessageSize(minLargeMessageSize)
+            .setConsumerWindowSize(consumerWindowSize)
+            .setConsumerMaxRate(consumerMaxRate)
+            .setConfirmationWindowSize(confirmationWindowSize)
+            .setProducerWindowSize(producerWindowSize)
+            .setProducerMaxRate(producerMaxRate)
+            .setBlockOnAcknowledge(blockOnAcknowledge)
+            .setBlockOnDurableSend(blockOnDurableSend)
+            .setBlockOnNonDurableSend(blockOnNonDurableSend)
+            .setAutoGroup(autoGroup)
+            .setPreAcknowledge(preAcknowledge)
+            .setLoadBalancingPolicyClassName(loadBalancingPolicyClassName)
+            .setTransactionBatchSize(transactionBatchSize)
+            .setDupsOKBatchSize(dupsOKBatchSize)
+            .setUseGlobalPools(useGlobalPools)
+            .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize)
+            .setThreadPoolMaxSize(threadPoolMaxSize)
+            .setRetryInterval(retryInterval)
+            .setRetryIntervalMultiplier(retryIntervalMultiplier)
+            .setMaxRetryInterval(maxRetryInterval)
+            .setReconnectAttempts(reconnectAttempts)
+            .setFailoverOnInitialConnection(failoverOnInitialConnection)
+            .setGroupID(groupId);
+
          createConnectionFactory(true, configuration, jndiBindings);
       }
    }
@@ -1086,38 +1129,41 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
       HornetQConnectionFactory cf = connectionFactories.get(name);
       if (cf == null)
       {
-         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl(name, ha, jndiBindings);
-         configuration.setDiscoveryGroupName(discoveryGroupName);
-         configuration.setFactoryType(cfType);
-         configuration.setClientID(clientID);
-         configuration.setClientFailureCheckPeriod(clientFailureCheckPeriod);
-         configuration.setConnectionTTL(connectionTTL);
-         configuration.setCallTimeout(callTimeout);
-         configuration.setCallFailoverTimeout(callFailoverTimeout);
-         configuration.setCacheLargeMessagesClient(cacheLargeMessagesClient);
-         configuration.setMinLargeMessageSize(minLargeMessageSize);
-         configuration.setCompressLargeMessages(compressLargeMessages);
-         configuration.setConsumerWindowSize(consumerWindowSize);
-         configuration.setConsumerMaxRate(consumerMaxRate);
-         configuration.setConfirmationWindowSize(confirmationWindowSize);
-         configuration.setProducerWindowSize(producerWindowSize);
-         configuration.setProducerMaxRate(producerMaxRate);
-         configuration.setBlockOnAcknowledge(blockOnAcknowledge);
-         configuration.setBlockOnDurableSend(blockOnDurableSend);
-         configuration.setBlockOnNonDurableSend(blockOnNonDurableSend);
-         configuration.setAutoGroup(autoGroup);
-         configuration.setPreAcknowledge(preAcknowledge);
-         configuration.setLoadBalancingPolicyClassName(loadBalancingPolicyClassName);
-         configuration.setTransactionBatchSize(transactionBatchSize);
-         configuration.setDupsOKBatchSize(dupsOKBatchSize);
-         configuration.setUseGlobalPools(useGlobalPools);
-         configuration.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize);
-         configuration.setThreadPoolMaxSize(threadPoolMaxSize);
-         configuration.setRetryInterval(retryInterval);
-         configuration.setRetryIntervalMultiplier(retryIntervalMultiplier);
-         configuration.setMaxRetryInterval(maxRetryInterval);
-         configuration.setReconnectAttempts(reconnectAttempts);
-         configuration.setFailoverOnInitialConnection(failoverOnInitialConnection);
+         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl()
+            .setName(name)
+            .setHA(ha)
+            .setBindings(jndiBindings)
+            .setDiscoveryGroupName(discoveryGroupName)
+            .setFactoryType(cfType)
+            .setClientID(clientID)
+            .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+            .setConnectionTTL(connectionTTL)
+            .setCallTimeout(callTimeout)
+            .setCallFailoverTimeout(callFailoverTimeout)
+            .setCacheLargeMessagesClient(cacheLargeMessagesClient)
+            .setMinLargeMessageSize(minLargeMessageSize)
+            .setCompressLargeMessages(compressLargeMessages)
+            .setConsumerWindowSize(consumerWindowSize)
+            .setConsumerMaxRate(consumerMaxRate)
+            .setConfirmationWindowSize(confirmationWindowSize)
+            .setProducerWindowSize(producerWindowSize)
+            .setProducerMaxRate(producerMaxRate)
+            .setBlockOnAcknowledge(blockOnAcknowledge)
+            .setBlockOnDurableSend(blockOnDurableSend)
+            .setBlockOnNonDurableSend(blockOnNonDurableSend)
+            .setAutoGroup(autoGroup)
+            .setPreAcknowledge(preAcknowledge)
+            .setLoadBalancingPolicyClassName(loadBalancingPolicyClassName)
+            .setTransactionBatchSize(transactionBatchSize)
+            .setDupsOKBatchSize(dupsOKBatchSize)
+            .setUseGlobalPools(useGlobalPools)
+            .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize)
+            .setThreadPoolMaxSize(threadPoolMaxSize)
+            .setRetryInterval(retryInterval)
+            .setRetryIntervalMultiplier(retryIntervalMultiplier)
+            .setMaxRetryInterval(maxRetryInterval)
+            .setReconnectAttempts(reconnectAttempts)
+            .setFailoverOnInitialConnection(failoverOnInitialConnection);
          createConnectionFactory(true, configuration, jndiBindings);
       }
    }
@@ -1132,8 +1178,11 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
       HornetQConnectionFactory cf = connectionFactories.get(name);
       if (cf == null)
       {
-         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl(name, ha, jndiBindings);
-         configuration.setDiscoveryGroupName(discoveryGroupName);
+         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl()
+            .setName(name)
+            .setHA(ha)
+            .setBindings(jndiBindings)
+            .setDiscoveryGroupName(discoveryGroupName);
          createConnectionFactory(true, configuration, jndiBindings);
       }
    }
@@ -1205,10 +1254,26 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
             }
 
             JMSServerManagerImpl.this.recoverJndiBindings(cfConfig.getName(), PersistedType.ConnectionFactory);
+            sendNotification(JMSNotificationType.CONNECTION_FACTORY_CREATED, cfConfig.getName());
          }
       });
    }
 
+   private void sendNotification(JMSNotificationType type, String message)
+   {
+      TypedProperties prop = new TypedProperties();
+      prop.putSimpleStringProperty(JMSNotificationType.MESSAGE, SimpleString.toSimpleString(message));
+      Notification notif = new Notification(null, type, prop);
+      try
+      {
+         server.getManagementService().sendNotification(notif);
+      }
+      catch (Exception e)
+      {
+         HornetQJMSServerLogger.LOGGER.warn("Failed to send notification : " + notif);
+      }
+   }
+
    public JMSStorageManager getJMSStorageManager()
    {
       return storage;
@@ -1446,6 +1511,11 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
          }
       });
 
+      if (valueReturn.get())
+      {
+         sendNotification(JMSNotificationType.CONNECTION_FACTORY_DESTROYED, name);
+      }
+
       return valueReturn.get();
    }
 
@@ -1457,10 +1527,6 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
    {
       checkInitialised();
       List<String> jndiBindings = connectionFactoryJNDI.get(name);
-      if (jndiBindings == null || jndiBindings.size() == 0)
-      {
-         return false;
-      }
 
       if (registry != null)
       {
@@ -1496,6 +1562,18 @@ public class JMSServerManagerImpl implements JMSServerManager, ActivateCallback
       return server.getHornetQServerControl().closeConnectionsForAddress(ipAddress);
    }
 
+   public boolean closeConsumerConnectionsForAddress(final String address) throws Exception
+   {
+      checkInitialised();
+      return server.getHornetQServerControl().closeConsumerConnectionsForAddress(address);
+   }
+
+   public boolean closeConnectionsForUser(final String userName) throws Exception
+   {
+      checkInitialised();
+      return server.getHornetQServerControl().closeConnectionsForUser(userName);
+   }
+
    public String[] listConnectionIDs() throws Exception
    {
       return server.getHornetQServerControl().listConnectionIDs();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/StandaloneNamingServer.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/StandaloneNamingServer.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/StandaloneNamingServer.java
index 5f2def5..ad4aa5a 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/StandaloneNamingServer.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/impl/StandaloneNamingServer.java
@@ -157,5 +157,11 @@ public class StandaloneNamingServer implements HornetQComponent
          }
          activated = false;
       }
+
+      @Override
+      public void activationComplete()
+      {
+
+      }
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/management/JMSNotificationType.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/management/JMSNotificationType.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/management/JMSNotificationType.java
new file mode 100644
index 0000000..0476265
--- /dev/null
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/management/JMSNotificationType.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.jms.server.management;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.NotificationType;
+
+public enum JMSNotificationType implements NotificationType
+{
+   QUEUE_CREATED(0),
+   QUEUE_DESTROYED(1),
+   TOPIC_CREATED(2),
+   TOPIC_DESTROYED(3),
+   CONNECTION_FACTORY_CREATED(4),
+   CONNECTION_FACTORY_DESTROYED(5);
+
+   public static final SimpleString MESSAGE = new SimpleString("message");
+
+   private int type;
+
+   private JMSNotificationType(int type)
+   {
+      this.type = type;
+   }
+
+   @Override
+   public int getType()
+   {
+      return type;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/AIOSequentialFileFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/AIOSequentialFileFactory.java b/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/AIOSequentialFileFactory.java
index 8c5851f..97948fb 100644
--- a/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/AIOSequentialFileFactory.java
+++ b/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/AIOSequentialFileFactory.java
@@ -226,9 +226,9 @@ public final class AIOSequentialFileFactory extends AbstractSequentialFileFactor
       private volatile long bufferReuseLastTime = System.currentTimeMillis();
 
       /**
-       * This queue is fed by {@link JournalImpl.ReuseBuffersController.LocalBufferCallback}} which is called directly by NIO or NIO.
-       * On the case of the AIO this is almost called by the native layer as soon as the buffer is not being used any more
-       * and ready to be reused or GCed
+       * This queue is fed by {@link org.hornetq.core.journal.impl.AIOSequentialFileFactory.ReuseBuffersController.LocalBufferCallback}
+       * which is called directly by NIO or NIO. On the case of the AIO this is almost called by the native layer as
+       * soon as the buffer is not being used any more and ready to be reused or GCed
        */
       private final ConcurrentLinkedQueue<ByteBuffer> reuseBuffersQueue = new ConcurrentLinkedQueue<ByteBuffer>();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/JournalFilesRepository.java
----------------------------------------------------------------------
diff --git a/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/JournalFilesRepository.java b/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/JournalFilesRepository.java
index dda3f25..7541417 100644
--- a/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/JournalFilesRepository.java
+++ b/hornetq-journal/src/main/java/org/hornetq/core/journal/impl/JournalFilesRepository.java
@@ -24,6 +24,7 @@ import java.util.concurrent.Executor;
 import java.util.concurrent.LinkedBlockingDeque;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
 
 import org.hornetq.core.journal.SequentialFile;
@@ -79,6 +80,8 @@ public class JournalFilesRepository
 
    private final int userVersion;
 
+   private final AtomicInteger freeFilesCount = new AtomicInteger(0);
+
    private Executor openFilesExecutor;
 
    private final Runnable pushOpenRunnable = new Runnable()
@@ -140,6 +143,8 @@ public class JournalFilesRepository
 
       freeFiles.clear();
 
+      freeFilesCount.set(0);
+
       for (JournalFile file : openedFiles)
       {
          try
@@ -207,8 +212,7 @@ public class JournalFilesRepository
 
    public void ensureMinFiles() throws Exception
    {
-      // FIXME - size() involves a scan
-      int filesToCreate = minFiles - (dataFiles.size() + freeFiles.size());
+      int filesToCreate = minFiles - (dataFiles.size() + freeFilesCount.get());
 
       if (filesToCreate > 0)
       {
@@ -216,6 +220,7 @@ public class JournalFilesRepository
          {
             // Keeping all files opened can be very costly (mainly on AIO)
             freeFiles.add(createFile(false, false, true, false, -1));
+            freeFilesCount.getAndIncrement();
          }
       }
 
@@ -368,7 +373,7 @@ public class JournalFilesRepository
 
    public int getFreeFilesCount()
    {
-      return freeFiles.size();
+      return freeFilesCount.get();
    }
 
    /**
@@ -405,8 +410,7 @@ public class JournalFilesRepository
          file.getFile().delete();
       }
       else
-         // FIXME - size() involves a scan!!!
-         if (!checkDelete || (freeFiles.size() + dataFiles.size() + 1 + openedFiles.size() < minFiles))
+         if (!checkDelete || (freeFilesCount.get() + dataFiles.size() + 1 + openedFiles.size() < minFiles))
          {
             // Re-initialise it
 
@@ -423,6 +427,7 @@ public class JournalFilesRepository
             }
 
             freeFiles.add(jf);
+            freeFilesCount.getAndIncrement();
          }
          else
          {
@@ -431,10 +436,10 @@ public class JournalFilesRepository
                HornetQJournalLogger.LOGGER.trace("DataFiles.size() = " + dataFiles.size());
                HornetQJournalLogger.LOGGER.trace("openedFiles.size() = " + openedFiles.size());
                HornetQJournalLogger.LOGGER.trace("minfiles = " + minFiles);
-               HornetQJournalLogger.LOGGER.trace("Free Files = " + freeFiles.size());
+               HornetQJournalLogger.LOGGER.trace("Free Files = " + freeFilesCount.get());
                HornetQJournalLogger.LOGGER.trace("File " + file +
                                                     " being deleted as freeFiles.size() + dataFiles.size() + 1 + openedFiles.size() (" +
-                                                    (freeFiles.size() + dataFiles.size() + 1 + openedFiles.size()) +
+                                                    (freeFilesCount.get() + dataFiles.size() + 1 + openedFiles.size()) +
                                                     ") < minFiles (" + minFiles + ")");
             }
             file.getFile().delete();
@@ -453,7 +458,9 @@ public class JournalFilesRepository
 
    public JournalFile getFreeFile()
    {
-      return freeFiles.remove();
+      JournalFile file = freeFiles.remove();
+      freeFilesCount.getAndDecrement();
+      return file;
    }
 
    // Opened files operations =======================================
@@ -544,6 +551,11 @@ public class JournalFilesRepository
 
       nextFile = freeFiles.poll();
 
+      if (nextFile != null)
+      {
+         freeFilesCount.getAndDecrement();
+      }
+
       if (nextFile == null)
       {
          nextFile = createFile(keepOpened, multiAIO, initFile, tmpCompactExtension, -1);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/pom.xml b/hornetq-protocols/hornetq-amqp-protocol/pom.xml
index 9c6fe46..b1079d3 100644
--- a/hornetq-protocols/hornetq-amqp-protocol/pom.xml
+++ b/hornetq-protocols/hornetq-amqp-protocol/pom.xml
@@ -14,6 +14,17 @@
    </properties>
 
    <dependencies>
+      <!-- JMS Client because of some Convertions that are done -->
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-jms-client</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-core-client</artifactId>
+         <version>${project.version}</version>
+      </dependency>
       <dependency>
          <groupId>org.jboss.logging</groupId>
          <artifactId>jboss-logging-processor</artifactId>
@@ -32,14 +43,34 @@
          <version>${project.version}</version>
       </dependency>
       <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-proton-plug</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
          <groupId>org.apache.qpid</groupId>
-         <artifactId>proton-api</artifactId>
+         <artifactId>proton-j</artifactId>
       </dependency>
       <dependency>
          <groupId>org.apache.qpid</groupId>
          <artifactId>proton-jms</artifactId>
       </dependency>
+
+
+
+      <dependency>
+         <groupId>org.jboss.spec.javax.jms</groupId>
+         <artifactId>jboss-jms-api_2.0_spec</artifactId>
+         <scope>provided</scope>
+      </dependency>
+      <dependency>
+         <groupId>junit</groupId>
+         <artifactId>junit</artifactId>
+         <scope>test</scope>
+      </dependency>
+
+
    </dependencies>
 
 
-</project>
\ No newline at end of file
+</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQAMQPProtocolMessageBundle.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQAMQPProtocolMessageBundle.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQAMQPProtocolMessageBundle.java
deleted file mode 100644
index ed020b7..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQAMQPProtocolMessageBundle.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.core.protocol.proton;
-
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPIllegalStateException;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPInternalErrorException;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPInvalidFieldException;
-import org.jboss.logging.annotations.Message;
-import org.jboss.logging.annotations.MessageBundle;
-import org.jboss.logging.Messages;
-
-/**
- * Logger Code 11
- * <p>
- * Each message id must be 6 digits long starting with 10, the 3rd digit should be 9. So the range
- * is from 219000 to 119999.
- * <p>
- * Once released, methods should not be deleted as they may be referenced by knowledge base
- * articles. Unused methods should be marked as deprecated.
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- */
-@MessageBundle(projectCode = "HQ")
-public interface HornetQAMQPProtocolMessageBundle
-{
-   HornetQAMQPProtocolMessageBundle BUNDLE = Messages.getBundle(HornetQAMQPProtocolMessageBundle.class);
-
-
-   @Message(id = 219000, value =  "target address not set", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPInvalidFieldException targetAddressNotSet();
-
-   @Message(id = 219001, value =  "error creating temporary queue, {0}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPInternalErrorException errorCreatingTemporaryQueue(String message);
-
-   @Message(id = 219002, value =  "target address does not exist", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPIllegalStateException addressDoesntExist();
-
-   @Message(id = 219003, value =  "error finding temporary queue, {0}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPInternalErrorException errorFindingTemporaryQueue(String message);
-
-   @Message(id = 219004, value =  "error creating HornetQ Session, {0}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPInternalErrorException errorCreatingHornetQSession(String message);
-
-   @Message(id = 219005, value =  "error creating HornetQ Consumer, {0}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPInternalErrorException errorCreatingHornetQConsumer(String message);
-
-   @Message(id = 219006, value =  "error starting HornetQ Consumer, {0}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPIllegalStateException errorStartingConsumer(String message);
-
-   @Message(id = 219007, value =  "error acknowledging message {0}, {1}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPIllegalStateException errorAcknowledgingMessage(long messageID, String message);
-
-   @Message(id = 219008, value =  "error cancelling message {0}, {1}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPIllegalStateException errorCancellingMessage(long messageID, String message);
-
-   @Message(id = 219009, value =  "error closing consumer {0}, {1}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPIllegalStateException errorClosingConsumer(long consumerID, String message);
-
-   @Message(id = 219010, value =  "source address does not exist", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPInvalidFieldException sourceAddressDoesntExist();
-
-   @Message(id = 219011, value =  "source address not set", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPInvalidFieldException sourceAddressNotSet();
-
-   @Message(id = 219012, value =  "error rolling back coordinator: {0}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPIllegalStateException errorRollingbackCoordinator(String message);
-
-   @Message(id = 219013, value =  "error committing coordinator: {0}", format = Message.Format.MESSAGE_FORMAT)
-   HornetQAMQPIllegalStateException errorCommittingCoordinator(String message);
-
-   @Message(id = 219015, value =  "error decoding AMQP frame", format = Message.Format.MESSAGE_FORMAT)
-   String decodeError();
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQProtonRemotingConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQProtonRemotingConnection.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQProtonRemotingConnection.java
new file mode 100644
index 0000000..8c6f778
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/HornetQProtonRemotingConnection.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton;
+
+import java.util.concurrent.Executor;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.core.client.HornetQClientLogger;
+import org.hornetq.spi.core.protocol.AbstractRemotingConnection;
+import org.hornetq.spi.core.remoting.Connection;
+import org.proton.plug.AMQPConnectionContext;
+
+/**
+ *
+ * This is a Server's Connection representation used by HornetQ.
+ * @author Clebert Suconic
+ */
+
+public class HornetQProtonRemotingConnection extends AbstractRemotingConnection
+{
+   private final AMQPConnectionContext amqpConnection;
+
+   private boolean destroyed = false;
+
+   private final ProtonProtocolManager manager;
+
+
+   public HornetQProtonRemotingConnection(ProtonProtocolManager manager, AMQPConnectionContext amqpConnection, Connection transportConnection, Executor executor)
+   {
+      super(transportConnection, executor);
+      this.manager = manager;
+      this.amqpConnection = amqpConnection;
+   }
+
+   public ProtonProtocolManager getManager()
+   {
+      return manager;
+   }
+
+   /*
+    * This can be called concurrently by more than one thread so needs to be locked
+    */
+   public void fail(final HornetQException me, String scaleDownTargetNodeID)
+   {
+      if (destroyed)
+      {
+         return;
+      }
+
+      destroyed = true;
+
+      HornetQClientLogger.LOGGER.connectionFailureDetected(me.getMessage(), me.getType());
+
+      // Then call the listeners
+      callFailureListeners(me, scaleDownTargetNodeID);
+
+      callClosingListeners();
+
+      internalClose();
+   }
+
+
+   @Override
+   public void destroy()
+   {
+      synchronized (this)
+      {
+         if (destroyed)
+         {
+            return;
+         }
+
+         destroyed = true;
+      }
+
+
+      callClosingListeners();
+
+      internalClose();
+
+   }
+
+   @Override
+   public boolean isClient()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean isDestroyed()
+   {
+      return destroyed;
+   }
+
+   @Override
+   public void disconnect(boolean criticalError)
+   {
+      getTransportConnection().close();
+   }
+
+   /**
+    * Disconnect the connection, closing all channels
+    */
+   @Override
+   public void disconnect(String scaleDownNodeID, boolean criticalError)
+   {
+      getTransportConnection().close();
+   }
+
+   @Override
+   public boolean checkDataReceived()
+   {
+      return amqpConnection.checkDataReceived();
+   }
+
+   @Override
+   public void flush()
+   {
+      amqpConnection.flush();
+   }
+
+   @Override
+   public void bufferReceived(Object connectionID, HornetQBuffer buffer)
+   {
+      amqpConnection.inputBuffer(buffer.byteBuf());
+      super.bufferReceived(connectionID, buffer);
+   }
+
+   private void internalClose()
+   {
+      // We close the underlying transport connection
+      getTransportConnection().close();
+   }
+}


[03/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityNotificationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityNotificationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityNotificationTest.java
index 9e3a60f..f0f9180 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityNotificationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityNotificationTest.java
@@ -16,8 +16,8 @@ import org.junit.After;
 
 import org.junit.Test;
 
-import static org.hornetq.api.core.management.NotificationType.SECURITY_AUTHENTICATION_VIOLATION;
-import static org.hornetq.api.core.management.NotificationType.SECURITY_PERMISSION_VIOLATION;
+import static org.hornetq.api.core.management.CoreNotificationType.SECURITY_AUTHENTICATION_VIOLATION;
+import static org.hornetq.api.core.management.CoreNotificationType.SECURITY_PERMISSION_VIOLATION;
 
 import java.util.HashSet;
 import java.util.Set;
@@ -148,11 +148,11 @@ public class SecurityNotificationTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(true);
-      // the notifications are independent of JMX
-      conf.setJMXManagementEnabled(false);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration conf = createBasicConfig()
+         .setSecurityEnabled(true)
+         // the notifications are independent of JMX
+         .setJMXManagementEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       server = HornetQServers.newHornetQServer(conf, false);
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicOpenWireTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicOpenWireTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicOpenWireTest.java
new file mode 100644
index 0000000..ae98d2e
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicOpenWireTest.java
@@ -0,0 +1,249 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.jms.Connection;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.ActiveMQConnection;
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.api.core.SimpleString;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+/**
+ *
+ * @author @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class BasicOpenWireTest extends OpenWireTestBase
+{
+   @Rule public TestName name = new TestName();
+
+   protected static final String urlString = "tcp://" + OWHOST + ":" + OWPORT + "?wireFormat.cacheEnabled=true";
+   protected ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(urlString);
+   protected ActiveMQConnection connection;
+   protected String topicName = "amqTestTopic1";
+   protected String queueName = "amqTestQueue1";
+   protected String topicName2 = "amqTestTopic2";
+   protected String queueName2 = "amqTestQueue2";
+   protected String durableQueueName = "durableQueueName";
+
+   protected String messageTextPrefix = "";
+   protected boolean topic = true;
+
+   protected Map<String, SimpleString> testQueues = new HashMap<String, SimpleString>();
+
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      super.setUp();
+      SimpleString coreQueue = new SimpleString("jms.queue." + queueName);
+      this.server.createQueue(coreQueue, coreQueue, null, false, false);
+      testQueues.put(queueName, coreQueue);
+
+      SimpleString coreQueue2 = new SimpleString("jms.queue." + queueName2);
+      this.server.createQueue(coreQueue2, coreQueue2, null, false, false);
+      testQueues.put(queueName2, coreQueue2);
+
+      SimpleString durableQueue = new SimpleString("jms.queue." + durableQueueName);
+      this.server.createQueue(durableQueue, durableQueue, null, true, false);
+      testQueues.put(durableQueueName, durableQueue);
+
+      if (!enableSecurity)
+      {
+         connection = (ActiveMQConnection) factory.createConnection();
+      }
+   }
+
+   @Override
+   @After
+   public void tearDown() throws Exception
+   {
+      System.out.println("tear down! " + connection);
+      try
+      {
+         if (connection != null)
+         {
+            System.out.println("closing connection");
+            connection.close();
+            System.out.println("connection closed.");
+         }
+
+         Iterator<SimpleString> iterQueues = testQueues.values().iterator();
+         while (iterQueues.hasNext())
+         {
+            SimpleString coreQ = iterQueues.next();
+            this.server.destroyQueue(coreQ);
+            System.out.println("Destroyed queue: " + coreQ);
+         }
+         testQueues.clear();
+      }
+      catch (Throwable e)
+      {
+         System.out.println("Exception !! " + e);
+         e.printStackTrace();
+      }
+      finally
+      {
+         super.tearDown();
+         System.out.println("Super done.");
+      }
+   }
+
+   public ActiveMQDestination createDestination(Session session, byte type, String name) throws Exception
+   {
+      if (name == null)
+      {
+         return createDestination(session, type);
+      }
+
+      switch (type)
+      {
+         case ActiveMQDestination.QUEUE_TYPE:
+            makeSureCoreQueueExist(name);
+            return (ActiveMQDestination) session.createQueue(name);
+         case ActiveMQDestination.TOPIC_TYPE:
+            return (ActiveMQDestination) session.createTopic(name);
+         case ActiveMQDestination.TEMP_QUEUE_TYPE:
+            return (ActiveMQDestination) session.createTemporaryQueue();
+         case ActiveMQDestination.TEMP_TOPIC_TYPE:
+            return (ActiveMQDestination) session.createTemporaryTopic();
+         default:
+            throw new IllegalArgumentException("type: " + type);
+      }
+   }
+
+   public void makeSureCoreQueueExist(String qname) throws Exception
+   {
+      SimpleString coreQ = testQueues.get(qname);
+      if (coreQ == null)
+      {
+         coreQ = new SimpleString("jms.queue." + qname);
+         this.server.createQueue(coreQ, coreQ, null, false, false);
+         testQueues.put(qname, coreQ);
+      }
+   }
+
+   public ActiveMQDestination createDestination(Session session, byte type) throws JMSException
+   {
+      switch (type)
+      {
+         case ActiveMQDestination.QUEUE_TYPE:
+            return (ActiveMQDestination) session.createQueue(queueName);
+         case ActiveMQDestination.TOPIC_TYPE:
+            return (ActiveMQDestination) session.createTopic(topicName);
+         case ActiveMQDestination.TEMP_QUEUE_TYPE:
+            return (ActiveMQDestination) session.createTemporaryQueue();
+         case ActiveMQDestination.TEMP_TOPIC_TYPE:
+            return (ActiveMQDestination) session.createTemporaryTopic();
+         default:
+            throw new IllegalArgumentException("type: " + type);
+      }
+   }
+
+   protected ActiveMQDestination createDestination2(Session session, byte type) throws JMSException
+   {
+      switch (type)
+      {
+         case ActiveMQDestination.QUEUE_TYPE:
+            return (ActiveMQDestination) session.createQueue(queueName2);
+         case ActiveMQDestination.TOPIC_TYPE:
+            return (ActiveMQDestination) session.createTopic(topicName2);
+         case ActiveMQDestination.TEMP_QUEUE_TYPE:
+            return (ActiveMQDestination) session.createTemporaryQueue();
+         case ActiveMQDestination.TEMP_TOPIC_TYPE:
+            return (ActiveMQDestination) session.createTemporaryTopic();
+         default:
+            throw new IllegalArgumentException("type: " + type);
+      }
+   }
+
+   protected void sendMessages(Session session, Destination destination, int count) throws JMSException
+   {
+      MessageProducer producer = session.createProducer(destination);
+      sendMessages(session, producer, count);
+      producer.close();
+   }
+
+   protected void sendMessages(Session session, MessageProducer producer, int count) throws JMSException
+   {
+      for (int i = 0; i < count; i++)
+      {
+         producer.send(session.createTextMessage(messageTextPrefix + i));
+      }
+   }
+
+   protected void sendMessages(Connection connection, Destination destination, int count) throws JMSException
+   {
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      sendMessages(session, destination, count);
+      session.close();
+   }
+
+   /**
+    * @param messsage
+    * @param firstSet
+    * @param secondSet
+    */
+   protected void assertTextMessagesEqual(String messsage, Message[] firstSet,
+         Message[] secondSet) throws JMSException
+   {
+      assertEquals("Message count does not match: " + messsage,
+            firstSet.length, secondSet.length);
+      for (int i = 0; i < secondSet.length; i++)
+      {
+         TextMessage m1 = (TextMessage) firstSet[i];
+         TextMessage m2 = (TextMessage) secondSet[i];
+         assertFalse("Message " + (i + 1) + " did not match : " + messsage
+               + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null
+               ^ m2 == null);
+         assertEquals("Message " + (i + 1) + " did not match: " + messsage
+               + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getText(),
+               m2.getText());
+      }
+   }
+
+   protected Connection createConnection() throws JMSException
+   {
+      return factory.createConnection();
+   }
+
+   protected void safeClose(Session s)
+   {
+      try
+      {
+         s.close();
+      }
+      catch (Throwable e)
+      {
+      }
+   }
+
+
+}
+
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicSecurityTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicSecurityTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicSecurityTest.java
new file mode 100644
index 0000000..e7b09d2
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/BasicSecurityTest.java
@@ -0,0 +1,256 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire;
+
+import javax.jms.Connection;
+import javax.jms.Destination;
+import javax.jms.JMSSecurityException;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TemporaryQueue;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.command.ActiveMQQueue;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+*
+* @author @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+*
+*/
+public class BasicSecurityTest extends BasicOpenWireTest
+{
+   @Before
+   public void setUp() throws Exception
+   {
+      this.enableSecurity = true;
+      super.setUp();
+   }
+
+   @Test
+   public void testConnectionWithCredentials() throws Exception
+   {
+      Connection newConn = null;
+
+      //correct
+      try
+      {
+         newConn = factory.createConnection("openwireSender", "SeNdEr");
+         newConn.start();
+         newConn.close();
+
+         newConn = factory.createConnection("openwireReceiver", "ReCeIvEr");
+         newConn.start();
+         newConn.close();
+
+         newConn = null;
+      }
+      finally
+      {
+         if (newConn != null)
+         {
+            newConn.close();
+         }
+      }
+
+      //wrong password
+      try
+      {
+         newConn = factory.createConnection("openwireSender", "WrongPasswD");
+         newConn.start();
+      }
+      catch (JMSSecurityException e)
+      {
+         //expected
+      }
+      finally
+      {
+         if (newConn != null)
+         {
+            newConn.close();
+         }
+      }
+
+      //wrong user
+      try
+      {
+         newConn = factory.createConnection("wronguser", "SeNdEr");
+         newConn.start();
+      }
+      catch (JMSSecurityException e)
+      {
+         //expected
+      }
+      finally
+      {
+         if (newConn != null)
+         {
+            newConn.close();
+         }
+      }
+
+      //both wrong
+      try
+      {
+         newConn = factory.createConnection("wronguser", "wrongpass");
+         newConn.start();
+      }
+      catch (JMSSecurityException e)
+      {
+         //expected
+      }
+      finally
+      {
+         if (newConn != null)
+         {
+            newConn.close();
+         }
+      }
+
+      //default user
+      try
+      {
+         newConn = factory.createConnection();
+         newConn.start();
+      }
+      catch (JMSSecurityException e)
+      {
+         //expected
+      }
+      finally
+      {
+         if (newConn != null)
+         {
+            newConn.close();
+         }
+      }
+   }
+
+   @Test
+   public void testSendnReceiveAuthorization() throws Exception
+   {
+      Connection sendingConn = null;
+      Connection receivingConn = null;
+
+      //Sender
+      try
+      {
+         Destination dest = new ActiveMQQueue(queueName);
+
+         receivingConn = factory.createConnection("openwireReceiver", "ReCeIvEr");
+         receivingConn.start();
+
+         sendingConn = factory.createConnection("openwireSender", "SeNdEr");
+         sendingConn.start();
+
+         Session sendingSession = sendingConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+         Session receivingSession = receivingConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+         TextMessage message = sendingSession.createTextMessage("Hello World");
+
+         MessageProducer producer = null;
+
+         producer = receivingSession.createProducer(dest);
+
+         try
+         {
+            producer.send(message);
+         }
+         catch (JMSSecurityException e)
+         {
+            //expected
+            producer.close();
+         }
+
+         producer = sendingSession.createProducer(dest);
+         producer.send(message);
+
+         MessageConsumer consumer = null;
+         try
+         {
+            consumer = sendingSession.createConsumer(dest);
+         }
+         catch (JMSSecurityException e)
+         {
+            //expected
+         }
+
+         consumer = receivingSession.createConsumer(dest);
+         TextMessage received = (TextMessage) consumer.receive();
+
+         assertNotNull(received);
+         assertEquals("Hello World", received.getText());
+      }
+      finally
+      {
+         if (sendingConn != null)
+         {
+            sendingConn.close();
+         }
+
+         if (receivingConn != null)
+         {
+            receivingConn.close();
+         }
+      }
+   }
+
+   @Test
+   public void testCreateTempDestinationAuthorization() throws Exception
+   {
+      Connection conn1 = null;
+      Connection conn2 = null;
+
+      //Sender
+      try
+      {
+         conn1 = factory.createConnection("openwireGuest", "GuEsT");
+         conn1.start();
+
+         conn2 = factory.createConnection("openwireDestinationManager", "DeStInAtIoN");
+         conn2.start();
+
+         Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+         try
+         {
+            session1.createTemporaryQueue();
+            fail("user shouldn't be able to create temp queue");
+         }
+         catch (JMSSecurityException e)
+         {
+            //expected
+         }
+
+         Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+         TemporaryQueue q = session2.createTemporaryQueue();
+         assertNotNull(q);
+      }
+      finally
+      {
+         if (conn1 != null)
+         {
+            conn1.close();
+         }
+
+         if (conn2 != null)
+         {
+            conn2.close();
+         }
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireTestBase.java
new file mode 100644
index 0000000..668095f
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireTestBase.java
@@ -0,0 +1,190 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.jms.ConnectionFactory;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.jms.management.JMSServerControl;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.remoting.impl.netty.TransportConstants;
+import org.hornetq.core.security.Role;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.jms.server.config.ConnectionFactoryConfiguration;
+import org.hornetq.jms.server.config.impl.ConnectionFactoryConfigurationImpl;
+import org.hornetq.jms.server.impl.JMSServerManagerImpl;
+import org.hornetq.tests.integration.management.ManagementControlHelper;
+import org.hornetq.tests.unit.util.InVMNamingContext;
+import org.hornetq.tests.util.ServiceTestBase;
+import org.junit.After;
+import org.junit.Before;
+
+public class OpenWireTestBase extends ServiceTestBase
+{
+   public static final String OWHOST = "localhost";
+   public static final int OWPORT = 61616;
+
+   protected HornetQServer server;
+
+   protected JMSServerManagerImpl jmsServer;
+   protected boolean realStore = false;
+   protected boolean enableSecurity = false;
+
+   protected ConnectionFactory coreCf;
+   protected InVMNamingContext namingContext;
+
+   protected MBeanServer mbeanServer;
+
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      super.setUp();
+      server = this.createServer(realStore, true);
+      HashMap<String, Object> params = new HashMap<String, Object>();
+      params.put(TransportConstants.PORT_PROP_NAME, "61616");
+      params.put(TransportConstants.PROTOCOLS_PROP_NAME, "OPENWIRE");
+      TransportConfiguration transportConfiguration = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params);
+
+      Configuration serverConfig = server.getConfiguration();
+
+      Map<String, AddressSettings> addressSettings = serverConfig.getAddressesSettings();
+      String match = "jms.queue.#";
+      AddressSettings dlaSettings = new AddressSettings();
+      SimpleString dla = new SimpleString("jms.queue.ActiveMQ.DLQ");
+      dlaSettings.setDeadLetterAddress(dla);
+      addressSettings.put(match, dlaSettings);
+
+      serverConfig.getAcceptorConfigurations().add(transportConfiguration);
+      serverConfig.setSecurityEnabled(enableSecurity);
+
+      extraServerConfig(serverConfig);
+
+      if (enableSecurity)
+      {
+         server.getSecurityManager().addRole("openwireSender", "sender");
+         server.getSecurityManager().addUser("openwireSender", "SeNdEr");
+         //sender cannot receive
+         Role senderRole = new Role("sender", true, false, false, false, true, true, false);
+
+         server.getSecurityManager().addRole("openwireReceiver", "receiver");
+         server.getSecurityManager().addUser("openwireReceiver", "ReCeIvEr");
+         //receiver cannot send
+         Role receiverRole = new Role("receiver", false, true, false, false, true, true, false);
+
+         server.getSecurityManager().addRole("openwireGuest", "guest");
+         server.getSecurityManager().addUser("openwireGuest", "GuEsT");
+
+         //guest cannot do anything
+         Role guestRole = new Role("guest", false, false, false, false, false, false, false);
+
+         server.getSecurityManager().addRole("openwireDestinationManager", "manager");
+         server.getSecurityManager().addUser("openwireDestinationManager", "DeStInAtIoN");
+
+         //guest cannot do anything
+         Role destRole = new Role("manager", false, false, false, false, true, true, false);
+
+         Map<String, Set<Role>> settings = server.getConfiguration().getSecurityRoles();
+         if (settings == null)
+         {
+            settings = new HashMap<String, Set<Role>>();
+            server.getConfiguration().setSecurityRoles(settings);
+         }
+         Set<Role> anySet = settings.get("#");
+         if (anySet == null)
+         {
+            anySet = new HashSet<Role>();
+            settings.put("#", anySet);
+         }
+         anySet.add(senderRole);
+         anySet.add(receiverRole);
+         anySet.add(guestRole);
+         anySet.add(destRole);
+      }
+      jmsServer = new JMSServerManagerImpl(server);
+      namingContext = new InVMNamingContext();
+      jmsServer.setContext(namingContext);
+      jmsServer.start();
+
+      registerConnectionFactory();
+
+      mbeanServer = MBeanServerFactory.createMBeanServer();
+      System.out.println("debug: server started");
+   }
+
+   //override this to add extra server configs
+   protected void extraServerConfig(Configuration serverConfig)
+   {
+   }
+
+   protected void registerConnectionFactory() throws Exception
+   {
+      List<TransportConfiguration> connectorConfigs = new ArrayList<TransportConfiguration>();
+      connectorConfigs.add(new TransportConfiguration(INVM_CONNECTOR_FACTORY));
+
+      createCF(connectorConfigs, "/cf");
+
+      coreCf = (ConnectionFactory) namingContext.lookup("/cf");
+   }
+
+   protected void createCF(final List<TransportConfiguration> connectorConfigs, final String... jndiBindings) throws Exception
+   {
+      final int retryInterval = 1000;
+      final double retryIntervalMultiplier = 1.0;
+      final int reconnectAttempts = -1;
+      final int callTimeout = 30000;
+      final boolean ha = false;
+      List<String> connectorNames = registerConnectors(server, connectorConfigs);
+
+      String cfName = name.getMethodName();
+      if (cfName == null)
+      {
+         cfName = "cfOpenWire";
+      }
+      ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl()
+         .setName(cfName)
+         .setConnectorNames(connectorNames)
+         .setRetryInterval(retryInterval)
+         .setRetryIntervalMultiplier(retryIntervalMultiplier)
+         .setCallTimeout(callTimeout)
+         .setReconnectAttempts(reconnectAttempts);
+      jmsServer.createConnectionFactory(false, configuration, jndiBindings);
+   }
+
+   protected JMSServerControl getJMSServerControl() throws Exception
+   {
+      return ManagementControlHelper.createJMSServerControl(mbeanServer);
+   }
+
+   @Override
+   @After
+   public void tearDown() throws Exception
+   {
+      MBeanServerFactory.releaseMBeanServer(mbeanServer);
+      mbeanServer = null;
+      server.stop();
+      super.tearDown();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireUtilTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireUtilTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireUtilTest.java
new file mode 100644
index 0000000..b17b8df
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/OpenWireUtilTest.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire;
+
+import static org.junit.Assert.assertEquals;
+
+import org.hornetq.core.protocol.openwire.OpenWireUtil;
+import org.junit.Test;
+
+public class OpenWireUtilTest
+{
+   @Test
+   public void testWildcardConversion() throws Exception
+   {
+      String amqTarget = "TEST.ONE.>";
+      String coreTarget = OpenWireUtil.convertWildcard(amqTarget);
+      assertEquals("TEST.ONE.#", coreTarget);
+
+      amqTarget = "TEST.*.ONE";
+      coreTarget = OpenWireUtil.convertWildcard(amqTarget);
+      assertEquals("TEST.*.ONE", coreTarget);
+
+      amqTarget = "a.*.>.>";
+      coreTarget = OpenWireUtil.convertWildcard(amqTarget);
+      assertEquals("a.*.#", coreTarget);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/SimpleOpenWireTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/SimpleOpenWireTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/SimpleOpenWireTest.java
new file mode 100644
index 0000000..faf6fe1
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/SimpleOpenWireTest.java
@@ -0,0 +1,280 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire;
+
+import javax.jms.Connection;
+import javax.jms.Destination;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TemporaryQueue;
+import javax.jms.TemporaryTopic;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.command.ActiveMQQueue;
+import org.apache.activemq.command.ActiveMQTopic;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ *
+ * @author @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class SimpleOpenWireTest extends BasicOpenWireTest
+{
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      this.realStore = true;
+      super.setUp();
+   }
+
+   @Test
+   public void testSimpleQueue() throws Exception
+   {
+      connection.start();
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+      System.out.println("creating queue: " + queueName);
+      Destination dest = new ActiveMQQueue(queueName);
+
+      System.out.println("creating producer...");
+      MessageProducer producer = session.createProducer(dest);
+
+      final int num = 1;
+      final String msgBase = "MfromAMQ-";
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = session.createTextMessage("MfromAMQ-" + i);
+         producer.send(msg);
+         System.out.println("sent: ");
+      }
+
+      //receive
+      MessageConsumer consumer = session.createConsumer(dest);
+
+      System.out.println("receiving messages...");
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = (TextMessage) consumer.receive(5000);
+         System.out.println("received: " + msg);
+         String content = msg.getText();
+         System.out.println("content: " + content);
+         assertEquals(msgBase + i, content);
+      }
+
+      assertNull(consumer.receive(1000));
+
+      session.close();
+   }
+
+   @Test
+   public void testSimpleTopic() throws Exception
+   {
+      connection.start();
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+      System.out.println("creating queue: " + topicName);
+      Destination dest = new ActiveMQTopic(topicName);
+
+      MessageConsumer consumer1 = session.createConsumer(dest);
+      MessageConsumer consumer2 = session.createConsumer(dest);
+
+      MessageProducer producer = session.createProducer(dest);
+
+      final int num = 1;
+      final String msgBase = "MfromAMQ-";
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = session.createTextMessage("MfromAMQ-" + i);
+         producer.send(msg);
+         System.out.println("Sent a message");
+      }
+
+      //receive
+      System.out.println("receiving messages...");
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = (TextMessage) consumer1.receive(5000);
+         System.out.println("received: " + msg);
+         String content = msg.getText();
+         assertEquals(msgBase + i, content);
+      }
+
+      assertNull(consumer1.receive(500));
+
+      System.out.println("receiving messages...");
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = (TextMessage) consumer2.receive(5000);
+         System.out.println("received: " + msg);
+         String content = msg.getText();
+         assertEquals(msgBase + i, content);
+      }
+
+      assertNull(consumer2.receive(500));
+      session.close();
+   }
+
+   @Test
+   public void testSimpleTempTopic() throws Exception
+   {
+      connection.start();
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+      System.out.println("creating temp topic");
+      TemporaryTopic tempTopic = session.createTemporaryTopic();
+
+      System.out.println("create consumer 1");
+      MessageConsumer consumer1 = session.createConsumer(tempTopic);
+      System.out.println("create consumer 2");
+      MessageConsumer consumer2 = session.createConsumer(tempTopic);
+
+      System.out.println("create producer");
+      MessageProducer producer = session.createProducer(tempTopic);
+
+      System.out.println("sending messages");
+      final int num = 1;
+      final String msgBase = "MfromAMQ-";
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = session.createTextMessage("MfromAMQ-" + i);
+         producer.send(msg);
+         System.out.println("Sent a message");
+      }
+
+      //receive
+      System.out.println("receiving messages...");
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = (TextMessage) consumer1.receive(5000);
+         System.out.println("received: " + msg);
+         String content = msg.getText();
+         assertEquals(msgBase + i, content);
+      }
+
+      assertNull(consumer1.receive(500));
+
+      System.out.println("receiving messages...");
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = (TextMessage) consumer2.receive(5000);
+         System.out.println("received: " + msg);
+         String content = msg.getText();
+         assertEquals(msgBase + i, content);
+      }
+
+      assertNull(consumer2.receive(500));
+      session.close();
+   }
+
+   @Test
+   public void testSimpleTempQueue() throws Exception
+   {
+      connection.start();
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+      System.out.println("creating temp queue");
+      TemporaryQueue tempQueue = session.createTemporaryQueue();
+
+      System.out.println("create consumer 1");
+      MessageConsumer consumer1 = session.createConsumer(tempQueue);
+
+      System.out.println("create producer");
+      MessageProducer producer = session.createProducer(tempQueue);
+
+      System.out.println("sending messages");
+      final int num = 1;
+      final String msgBase = "MfromAMQ-";
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = session.createTextMessage("MfromAMQ-" + i);
+         producer.send(msg);
+         System.out.println("Sent a message");
+      }
+
+      //receive
+      System.out.println("receiving messages...");
+      for (int i = 0; i < num; i++)
+      {
+         TextMessage msg = (TextMessage) consumer1.receive(5000);
+         System.out.println("received: " + msg);
+         String content = msg.getText();
+         assertEquals(msgBase + i, content);
+      }
+
+      assertNull(consumer1.receive(500));
+      session.close();
+   }
+
+   /**
+    * This is the example shipped with the distribution
+    * @throws Exception
+    */
+   @Test
+   public void testOpenWireExample() throws Exception
+   {
+      Connection exConn = null;
+
+      try
+      {
+         String urlString = "tcp://" + OWHOST + ":" + OWPORT + "?wireFormat.cacheEnabled=true";
+         ActiveMQConnectionFactory exFact = new ActiveMQConnectionFactory(urlString);
+
+         // Step 2. Perfom a lookup on the queue
+         Queue queue = new ActiveMQQueue(durableQueueName);
+
+         // Step 4.Create a JMS Connection
+         exConn = exFact.createConnection();
+
+         // Step 10. Start the Connection
+         exConn.start();
+
+         // Step 5. Create a JMS Session
+         Session session = exConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+         // Step 6. Create a JMS Message Producer
+         MessageProducer producer = session.createProducer(queue);
+
+         // Step 7. Create a Text Message
+         TextMessage message = session.createTextMessage("This is a text message");
+
+         //System.out.println("Sent message: " + message.getText());
+
+         // Step 8. Send the Message
+         producer.send(message);
+
+         // Step 9. Create a JMS Message Consumer
+         MessageConsumer messageConsumer = session.createConsumer(queue);
+
+         // Step 11. Receive the message
+         TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);
+
+         System.out.println("Received message: " + messageReceived);
+
+         assertEquals("This is a text message", messageReceived.getText());
+      }
+      finally
+      {
+         if (exConn != null)
+         {
+            exConn.close();
+         }
+      }
+
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer10Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer10Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer10Test.java
new file mode 100644
index 0000000..d6a9942
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer10Test.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQConnection;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer10Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public int ackMode;
+   public byte destinationType;
+
+   public JMSConsumer10Test(int deliveryMode, int ackMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.ackMode = ackMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testUnackedWithPrefetch1StayInQueue() throws Exception
+   {
+
+      // Set prefetch to 1
+      connection.getPrefetchPolicy().setAll(1);
+      connection.start();
+
+      // Use all the ack modes
+      Session session = connection.createSession(false, ackMode);
+      ActiveMQDestination destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+
+      // Only pick up the first 2 messages.
+      Message message = null;
+      for (int i = 0; i < 2; i++)
+      {
+         message = consumer.receive(1000);
+         assertNotNull(message);
+      }
+      message.acknowledge();
+
+      connection.close();
+      connection = (ActiveMQConnection) factory.createConnection();
+      connection.getPrefetchPolicy().setAll(1);
+      connection.start();
+
+      // Use all the ack modes
+      session = connection.createSession(false, ackMode);
+      consumer = session.createConsumer(destination);
+
+      // Pickup the rest of the messages.
+      for (int i = 0; i < 2; i++)
+      {
+         message = consumer.receive(1000);
+         assertNotNull(message);
+      }
+      message.acknowledge();
+      assertNull(consumer.receiveNoWait());
+
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer11Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer11Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer11Test.java
new file mode 100644
index 0000000..5376f88
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer11Test.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQConnection;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer11Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT},
+         {DeliveryMode.PERSISTENT}
+      });
+   }
+
+   public int deliveryMode;
+
+   public JMSConsumer11Test(int deliveryMode)
+   {
+      this.deliveryMode = deliveryMode;
+   }
+
+   @Test
+   public void testPrefetch1MessageNotDispatched() throws Exception
+   {
+      // Set prefetch to 1
+      connection.getPrefetchPolicy().setAll(1);
+      connection.start();
+
+      Session session = connection.createSession(true, 0);
+      ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send 2 messages to the destination.
+      sendMessages(session, destination, 2);
+      session.commit();
+
+      // The prefetch should fill up with 1 message.
+      // Since prefetch is still full, the 2nd message should get dispatched
+      // to another consumer.. lets create the 2nd consumer test that it does
+      // make sure it does.
+      ActiveMQConnection connection2 = (ActiveMQConnection) factory
+            .createConnection();
+      connection2.start();
+      Session session2 = connection2.createSession(true, 0);
+      MessageConsumer consumer2 = session2.createConsumer(destination);
+
+      System.out.println("consumer receiving ...");
+      // Pick up the first message.
+      Message message1 = consumer.receive(1000);
+      System.out.println("received1: " + message1);
+      assertNotNull(message1);
+
+      System.out.println("consumer 2 receiving...");
+      // Pick up the 2nd messages.
+      Message message2 = consumer2.receive(5000);
+      System.out.println("received2: " + message2);
+      assertNotNull(message2);
+
+      System.out.println("commitning sessions !! " + session.getClass().getName());
+      session.commit();
+      System.out.println("commited session, now 2");
+      session2.commit();
+
+      System.out.println("all commited");
+      Message m = consumer.receiveNoWait();
+      System.out.println("recieved 3: " + m);
+      assertNull(m);
+
+      try
+      {
+         connection2.close();
+      }
+      catch (Throwable e)
+      {
+         System.err.println("exception e: " + e);
+         e.printStackTrace();
+      }
+
+      System.out.println("Test finished!!");
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer12Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer12Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer12Test.java
new file mode 100644
index 0000000..633cd01
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer12Test.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.jms.DeliveryMode;
+import javax.jms.MessageConsumer;
+import javax.jms.Session;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer12Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public byte destinationType;
+
+   public JMSConsumer12Test(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testDontStart() throws Exception
+   {
+
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send the messages
+      sendMessages(session, destination, 1);
+
+      // Make sure no messages were delivered.
+      assertNull(consumer.receive(1000));
+   }
+
+   @Test
+   public void testStartAfterSend() throws Exception
+   {
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send the messages
+      sendMessages(session, destination, 1);
+
+      // Start the conncection after the message was sent.
+      connection.start();
+
+      // Make sure only 1 message was delivered.
+      assertNotNull(consumer.receive(1000));
+      assertNull(consumer.receiveNoWait());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer13Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer13Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer13Test.java
new file mode 100644
index 0000000..82d8326
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer13Test.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer13Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE},
+      });
+   }
+
+   public int deliveryMode;
+   public byte destinationType;
+
+   public JMSConsumer13Test(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testReceiveMessageWithConsumer() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send the messages
+      sendMessages(session, destination, 1);
+
+      // Make sure only 1 message was delivered.
+      Message m = consumer.receive(1000);
+      assertNotNull(m);
+      assertEquals("0", ((TextMessage) m).getText());
+      assertNull(consumer.receiveNoWait());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer1Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer1Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer1Test.java
new file mode 100644
index 0000000..622a55b
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer1Test.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQMessageConsumer;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer1Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}
+      });
+   }
+
+   public ActiveMQDestination destination;
+   public int deliveryMode;
+   public int prefetch;
+   public int ackMode;
+   public byte destinationType;
+   public boolean durableConsumer;
+
+   public JMSConsumer1Test(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testMessageListenerWithConsumerCanBeStopped() throws Exception
+   {
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch done1 = new CountDownLatch(1);
+      final CountDownLatch done2 = new CountDownLatch(1);
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      destination = createDestination(session, destinationType);
+      ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session
+            .createConsumer(destination);
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            counter.incrementAndGet();
+            if (counter.get() == 1)
+            {
+               done1.countDown();
+            }
+            if (counter.get() == 2)
+            {
+               done2.countDown();
+            }
+         }
+      });
+
+      // Send a first message to make sure that the consumer dispatcher is
+      // running
+      sendMessages(session, destination, 1);
+      assertTrue(done1.await(1, TimeUnit.SECONDS));
+      assertEquals(1, counter.get());
+
+      // Stop the consumer.
+      consumer.stop();
+
+      // Send a message, but should not get delivered.
+      sendMessages(session, destination, 1);
+      assertFalse(done2.await(1, TimeUnit.SECONDS));
+      assertEquals(1, counter.get());
+
+      // Start the consumer, and the message should now get delivered.
+      consumer.start();
+      assertTrue(done2.await(1, TimeUnit.SECONDS));
+      assertEquals(2, counter.get());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer2Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer2Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer2Test.java
new file mode 100644
index 0000000..cee9545
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer2Test.java
@@ -0,0 +1,240 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQMessageConsumer;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+public class JMSConsumer2Test extends BasicOpenWireTest
+{
+   @Test
+   public void testMessageListenerWithConsumerCanBeStoppedConcurently() throws Exception
+   {
+
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch closeDone = new CountDownLatch(1);
+
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.CLIENT_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            ActiveMQDestination.QUEUE_TYPE);
+
+      // preload the queue
+      sendMessages(session, destination, 2000);
+
+      final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session
+            .createConsumer(destination);
+
+      final Map<Thread, Throwable> exceptions = Collections
+            .synchronizedMap(new HashMap<Thread, Throwable>());
+      Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler()
+      {
+         @Override
+         public void uncaughtException(Thread t, Throwable e)
+         {
+            exceptions.put(t, e);
+         }
+      });
+
+      final class AckAndClose implements Runnable
+      {
+         private final Message message;
+
+         public AckAndClose(Message m)
+         {
+            this.message = m;
+         }
+
+         @Override
+         public void run()
+         {
+            try
+            {
+               int count = counter.incrementAndGet();
+               if (count == 590)
+               {
+                  // close in a separate thread is ok by jms
+                  consumer.close();
+                  closeDone.countDown();
+               }
+               if (count % 200 == 0)
+               {
+                  // ensure there are some outstanding messages
+                  // ack every 200
+                  message.acknowledge();
+               }
+            }
+            catch (Exception e)
+            {
+               exceptions.put(Thread.currentThread(), e);
+            }
+         }
+      }
+
+      final ExecutorService executor = Executors.newCachedThreadPool();
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            // ack and close eventually in separate thread
+            executor.execute(new AckAndClose(m));
+         }
+      });
+
+      assertTrue(closeDone.await(20, TimeUnit.SECONDS));
+      // await possible exceptions
+      Thread.sleep(1000);
+      assertTrue("no exceptions: " + exceptions, exceptions.isEmpty());
+   }
+
+   @Test
+   public void testDupsOkConsumer() throws Exception
+   {
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.DUPS_OK_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+
+      // Make sure only 4 message are delivered.
+      for (int i = 0; i < 4; i++)
+      {
+         Message m = consumer.receive(1000);
+         assertNotNull(m);
+      }
+      assertNull(consumer.receive(1000));
+
+      // Close out the consumer.. no other messages should be left on the queue.
+      consumer.close();
+
+      consumer = session.createConsumer(destination);
+      assertNull(consumer.receive(1000));
+   }
+
+   @Test
+   public void testRedispatchOfUncommittedTx() throws Exception
+   {
+      connection.start();
+      Session session = connection.createSession(true,
+            Session.SESSION_TRANSACTED);
+      ActiveMQDestination destination = createDestination(session,
+            ActiveMQDestination.QUEUE_TYPE);
+
+      sendMessages(connection, destination, 2);
+
+      MessageConsumer consumer = session.createConsumer(destination);
+      Message m = consumer.receive(1000);
+      System.out.println("m1 received: " + m);
+      assertNotNull(m);
+      m = consumer.receive(5000);
+      System.out.println("m2 received: " + m);
+      assertNotNull(m);
+
+      // install another consumer while message dispatch is unacked/uncommitted
+      Session redispatchSession = connection.createSession(true,
+            Session.SESSION_TRANSACTED);
+      MessageConsumer redispatchConsumer = redispatchSession
+            .createConsumer(destination);
+      System.out.println("redispatch consumer: " + redispatchConsumer);
+
+      // no commit so will auto rollback and get re-dispatched to
+      // redisptachConsumer
+      System.out.println("closing session: " + session);
+      session.close();
+
+      Message msg = redispatchConsumer.receive(3000);
+      assertNotNull(msg);
+
+      assertTrue("redelivered flag set", msg.getJMSRedelivered());
+      assertEquals(2, msg.getLongProperty("JMSXDeliveryCount"));
+
+      msg = redispatchConsumer.receive(1000);
+      assertNotNull(msg);
+      assertTrue(msg.getJMSRedelivered());
+      assertEquals(2, msg.getLongProperty("JMSXDeliveryCount"));
+      redispatchSession.commit();
+
+      assertNull(redispatchConsumer.receive(500));
+      System.out.println("closing dispatch session: " + redispatchSession);
+      redispatchSession.close();
+   }
+
+   @Test
+   public void testRedispatchOfRolledbackTx() throws Exception
+   {
+
+      connection.start();
+      Session session = connection.createSession(true,
+            Session.SESSION_TRANSACTED);
+      ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);
+
+      sendMessages(connection, destination, 2);
+
+      MessageConsumer consumer = session.createConsumer(destination);
+      assertNotNull(consumer.receive(1000));
+      assertNotNull(consumer.receive(1000));
+
+      // install another consumer while message dispatch is unacked/uncommitted
+      Session redispatchSession = connection.createSession(true,
+            Session.SESSION_TRANSACTED);
+      MessageConsumer redispatchConsumer = redispatchSession
+            .createConsumer(destination);
+
+      session.rollback();
+      session.close();
+
+      Message msg = redispatchConsumer.receive(1000);
+      assertNotNull(msg);
+      assertTrue(msg.getJMSRedelivered());
+      assertEquals(2, msg.getLongProperty("JMSXDeliveryCount"));
+      msg = redispatchConsumer.receive(1000);
+      assertNotNull(msg);
+      assertTrue(msg.getJMSRedelivered());
+      assertEquals(2, msg.getLongProperty("JMSXDeliveryCount"));
+      redispatchSession.commit();
+
+      assertNull(redispatchConsumer.receive(500));
+      redispatchSession.close();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer3Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer3Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer3Test.java
new file mode 100644
index 0000000..a444fff
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer3Test.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQConnection;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer3Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} ackMode={1} destinationType={2}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.DUPS_OK_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, Session.CLIENT_ACKNOWLEDGE, ActiveMQDestination.TEMP_TOPIC_TYPE}
+      });
+   }
+
+   public ActiveMQDestination destination;
+   public int deliveryMode;
+   public int prefetch;
+   public int ackMode;
+   public byte destinationType;
+   public boolean durableConsumer;
+
+   public JMSConsumer3Test(int deliveryMode, int ackMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.ackMode = ackMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testMutiReceiveWithPrefetch1() throws Exception
+   {
+      // Set prefetch to 1
+      ((ActiveMQConnection)connection).getPrefetchPolicy().setAll(1);
+      connection.start();
+
+      // Use all the ack modes
+      Session session = connection.createSession(false, ackMode);
+      destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+
+      System.out.println("messages are sent.");
+      // Make sure 4 messages were delivered.
+      Message message = null;
+      for (int i = 0; i < 4; i++)
+      {
+         message = consumer.receive(5000);
+         System.out.println("message received: " + message + " ack mode: " + ackMode);
+         assertNotNull(message);
+      }
+      assertNull(consumer.receiveNoWait());
+      message.acknowledge();
+   }
+
+}
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer4Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer4Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer4Test.java
new file mode 100644
index 0000000..d4fe157
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer4Test.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+import javax.jms.Topic;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer4Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public byte destinationType;
+
+   public JMSConsumer4Test(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testDurableConsumerSelectorChange() throws Exception
+   {
+      // Receive a message with the JMS API
+      connection.setClientID("test");
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageProducer producer = session.createProducer(destination);
+      producer.setDeliveryMode(deliveryMode);
+      MessageConsumer consumer = session.createDurableSubscriber(
+            (Topic) destination, "test", "color='red'", false);
+
+      // Send the messages
+      TextMessage message = session.createTextMessage("1st");
+      message.setStringProperty("color", "red");
+      producer.send(message);
+
+      Message m = consumer.receive(1000);
+      assertNotNull(m);
+      assertEquals("1st", ((TextMessage) m).getText());
+
+      // Change the subscription.
+      consumer.close();
+      consumer = session.createDurableSubscriber((Topic) destination, "test",
+            "color='blue'", false);
+
+      message = session.createTextMessage("2nd");
+      message.setStringProperty("color", "red");
+      producer.send(message);
+      message = session.createTextMessage("3rd");
+      message.setStringProperty("color", "blue");
+      producer.send(message);
+
+      // Selector should skip the 2nd message.
+      m = consumer.receive(1000);
+      assertNotNull(m);
+      assertEquals("3rd", ((TextMessage) m).getText());
+
+      assertNull(consumer.receiveNoWait());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer5Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer5Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer5Test.java
new file mode 100644
index 0000000..70d7c41
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer5Test.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.BytesMessage;
+import javax.jms.DeliveryMode;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer5Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "deliveryMode={0} destinationType={1}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.NON_PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TOPIC_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_QUEUE_TYPE},
+         {DeliveryMode.PERSISTENT, ActiveMQDestination.TEMP_TOPIC_TYPE}
+      });
+   }
+
+   public int deliveryMode;
+   public byte destinationType;
+
+   public JMSConsumer5Test(int deliveryMode, byte destinationType)
+   {
+      this.deliveryMode = deliveryMode;
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testSendReceiveBytesMessage() throws Exception
+   {
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+      MessageProducer producer = session.createProducer(destination);
+
+      BytesMessage message = session.createBytesMessage();
+      message.writeBoolean(true);
+      message.writeBoolean(false);
+      producer.send(message);
+
+      // Make sure only 1 message was delivered.
+      BytesMessage m = (BytesMessage) consumer.receive(1000);
+      assertNotNull(m);
+      assertTrue(m.readBoolean());
+      assertFalse(m.readBoolean());
+
+      assertNull(consumer.receiveNoWait());
+   }
+
+   @Test
+   public void testSetMessageListenerAfterStart() throws Exception
+   {
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch done = new CountDownLatch(1);
+
+      // Receive a message with the JMS API
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+      MessageConsumer consumer = session.createConsumer(destination);
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+
+      // See if the message get sent to the listener
+      consumer.setMessageListener(new MessageListener()
+      {
+         @Override
+         public void onMessage(Message m)
+         {
+            counter.incrementAndGet();
+            if (counter.get() == 4)
+            {
+               System.out.println("ok finished all 4, done sleep");
+               done.countDown();
+            }
+         }
+      });
+
+      assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
+      System.out.println("ok await ok");
+      Thread.sleep(200);
+
+      // Make sure only 4 messages were delivered.
+      assertEquals(4, counter.get());
+      System.out.println("test done ok " + counter.get());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer6Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer6Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer6Test.java
new file mode 100644
index 0000000..d17dd06
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/openwire/amq/JMSConsumer6Test.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.openwire.amq;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.ActiveMQMessageConsumer;
+import org.apache.activemq.ActiveMQSession;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.hornetq.tests.integration.openwire.BasicOpenWireTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * adapted from: org.apache.activemq.JMSConsumerTest
+ *
+ * @author <a href="mailto:hgao@redhat.com">Howard Gao</a>
+ *
+ */
+@RunWith(Parameterized.class)
+public class JMSConsumer6Test extends BasicOpenWireTest
+{
+   @Parameterized.Parameters(name = "destinationType={0}")
+   public static Collection<Object[]> getParams()
+   {
+      return Arrays.asList(new Object[][] {
+         {ActiveMQDestination.QUEUE_TYPE},
+         {ActiveMQDestination.TOPIC_TYPE}
+      });
+   }
+
+   public byte destinationType;
+
+   public JMSConsumer6Test(byte destinationType)
+   {
+      this.destinationType = destinationType;
+   }
+
+   @Test
+   public void testPassMessageListenerIntoCreateConsumer() throws Exception
+   {
+
+      final AtomicInteger counter = new AtomicInteger(0);
+      final CountDownLatch done = new CountDownLatch(1);
+
+      // Receive a message with the JMS API
+      connection.start();
+      ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session, destinationType);
+      MessageConsumer consumer = session.createConsumer(destination,
+         new MessageListener()
+         {
+            @Override
+            public void onMessage(Message m)
+            {
+               counter.incrementAndGet();
+               if (counter.get() == 4)
+               {
+                  done.countDown();
+               }
+            }
+         });
+      assertNotNull(consumer);
+
+      // Send the messages
+      sendMessages(session, destination, 4);
+
+      assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
+      Thread.sleep(200);
+
+      // Make sure only 4 messages were delivered.
+      assertEquals(4, counter.get());
+   }
+
+   @Test
+   public void testAckOfExpired() throws Exception
+   {
+      connection.start();
+      Session session = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      ActiveMQDestination destination = createDestination(session,
+            destinationType);
+
+      MessageConsumer consumer = session.createConsumer(destination);
+      connection.setStatsEnabled(true);
+
+      Session sendSession = connection.createSession(false,
+            Session.AUTO_ACKNOWLEDGE);
+      MessageProducer producer = sendSession.createProducer(destination);
+      producer.setTimeToLive(1000);
+      final int count = 4;
+      for (int i = 0; i < count; i++)
+      {
+         TextMessage message = sendSession.createTextMessage("" + i);
+         producer.send(message);
+      }
+
+      // let first bunch in queue expire
+      Thread.sleep(2000);
+
+      producer.setTimeToLive(0);
+      for (int i = 0; i < count; i++)
+      {
+         TextMessage message = sendSession.createTextMessage("no expiry" + i);
+         producer.send(message);
+      }
+
+      ActiveMQMessageConsumer amqConsumer = (ActiveMQMessageConsumer) consumer;
+
+      for (int i = 0; i < count; i++)
+      {
+         TextMessage msg = (TextMessage) amqConsumer.receive();
+         assertNotNull(msg);
+         assertTrue("message has \"no expiry\" text: " + msg.getText(), msg
+               .getText().contains("no expiry"));
+
+         // force an ack when there are expired messages
+         amqConsumer.acknowledge();
+      }
+      assertEquals("consumer has expiredMessages", count, amqConsumer
+            .getConsumerStats().getExpiredMessageCount().getCount());
+   }
+
+}


[16/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/resources/schema/hornetq-configuration.xsd
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/resources/schema/hornetq-configuration.xsd b/hornetq-server/src/main/resources/schema/hornetq-configuration.xsd
index f134057..3ae9384 100644
--- a/hornetq-server/src/main/resources/schema/hornetq-configuration.xsd
+++ b/hornetq-server/src/main/resources/schema/hornetq-configuration.xsd
@@ -1,5 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <xsd:schema xmlns="urn:hornetq" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:hq="urn:org.hornetq"
+            xmlns:csd="http://www.w3.org/2001/XMLSchema"
             attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="urn:hornetq"
             version="1.0">
 
@@ -224,7 +225,7 @@
             </xsd:annotation>
          </xsd:element>
 
-         <xsd:element name="jmx-domain" type="xsd:string" default="jboss.as" maxOccurs="1" minOccurs="0">
+         <xsd:element name="jmx-domain" type="xsd:string" default="org.hornetq" maxOccurs="1" minOccurs="0">
             <xsd:annotation hq:linkend="management.jmx.configuration" hq:field_name="DEFAULT_JMX_DOMAIN">
                <xsd:documentation>
                   the JMX domain used to registered HornetQ MBeans in the MBeanServer
@@ -1230,8 +1231,7 @@
             </xsd:annotation>
          </xsd:element>
 
-         <xsd:element name="use-duplicate-detection" type="xsd:boolean" default="true"
-                      maxOccurs="1" minOccurs="0">
+         <xsd:element name="use-duplicate-detection" type="xsd:boolean" default="true" maxOccurs="1" minOccurs="0">
             <xsd:annotation hq:field_name="DEFAULT_BRIDGE_DUPLICATE_DETECTION">
                <xsd:documentation>
                   should duplicate detection headers be inserted in forwarded messages?
@@ -1239,8 +1239,8 @@
             </xsd:annotation>
          </xsd:element>
 
-         <xsd:element name="confirmation-window-size" type="xsd:int" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:default="(bytes, 1024 * 1024)">
+         <xsd:element name="confirmation-window-size" type="xsd:int" maxOccurs="1" minOccurs="0" default="1048576">
+            <xsd:annotation hq:default="(bytes)" hq:field_name="DEFAULT_BRIDGE_CONFIRMATION_WINDOW_SIZE">
                <xsd:documentation>
                   Once the bridge has received this many bytes, it sends a confirmation
                </xsd:documentation>
@@ -1263,8 +1263,7 @@
             </xsd:annotation>
          </xsd:element>
 
-         <xsd:element name="reconnect-attempts-same-node" default="10" type="xsd:int"
-                      maxOccurs="1" minOccurs="0">
+         <xsd:element name="reconnect-attempts-same-node" default="10" type="xsd:int" maxOccurs="1" minOccurs="0">
             <xsd:annotation hq:default="(int, 10)" hq:field_name="DEFAULT_BRIDGE_CONNECT_SAME_NODE">
                <xsd:documentation>
                   Upon reconnection this configures the number of time the same node on the topology will be retried
@@ -1326,8 +1325,7 @@
          </xsd:element>
 
          <xsd:element name="check-period" type="xsd:long" default="30000" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="connection-ttl" hq:default="(ms)"
-                            hq:field_name="DEFAULT_CLUSTER_FAILURE_CHECK_PERIOD">
+            <xsd:annotation hq:linkend="connection-ttl" hq:default="(ms)" hq:field_name="DEFAULT_CLUSTER_FAILURE_CHECK_PERIOD">
                <xsd:documentation>
                   The period (in milliseconds) used to check if the cluster connection has failed to receive pings from
                   another server
@@ -1336,8 +1334,7 @@
          </xsd:element>
 
          <xsd:element name="connection-ttl" type="xsd:long" default="60000" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="connection-ttl" hq:default="(ms)"
-                            hq:field_name="DEFAULT_CLUSTER_CONNECTION_TTL">
+            <xsd:annotation hq:linkend="connection-ttl" hq:default="(ms)" hq:field_name="DEFAULT_CLUSTER_CONNECTION_TTL">
                <xsd:documentation>
                   how long to keep a connection alive in the absence of any data arriving from the client
                </xsd:documentation>
@@ -1353,7 +1350,7 @@
          </xsd:element>
 
          <xsd:element name="call-timeout" type="xsd:long" default="30000" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:default="(ms)">
+            <xsd:annotation hq:default="(ms)" hq:field_name="DEFAULT_CLUSTER_CALL_TIMEOUT">
                <xsd:documentation>
                   How long to wait for a reply
                </xsd:documentation>
@@ -1425,7 +1422,7 @@
          </xsd:element>
 
          <xsd:element name="confirmation-window-size" type="xsd:int" default="1048576" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="client-reconnection">
+            <xsd:annotation hq:field_name="DEFAULT_CLUSTER_CONFIRMATION_WINDOW_SIZE" hq:linkend="client-reconnection">
                <xsd:documentation>
                   The size (in bytes) of the window used for confirming data from the server connected to.
                </xsd:documentation>
@@ -1433,7 +1430,7 @@
          </xsd:element>
 
          <xsd:element name="call-failover-timeout" type="xsd:long" default="-1" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="clusters.cluster-connections" hq:default="(ms)">
+            <xsd:annotation hq:linkend="clusters.cluster-connections" hq:default="(ms)" hq:field_name="DEFAULT_CLUSTER_CALL_FAILOVER_TIMEOUT">
                <xsd:documentation>
                   How long to wait for a reply if in the middle of a fail-over. -1 means wait forever.
                </xsd:documentation>
@@ -1471,9 +1468,8 @@
                   <xsd:sequence>
                      <xsd:element name="connector-ref" type="xsd:string" maxOccurs="unbounded" minOccurs="0"/>
                   </xsd:sequence>
-                  <xsd:attribute name="allow-direct-connections-only" default="false" type="xsd:boolean"
-                                 use="optional">
-                     <xsd:annotation>
+                  <xsd:attribute name="allow-direct-connections-only" default="false" type="xsd:boolean" use="optional">
+                     <xsd:annotation hq:field_name="DEFAULT_CLUSTER_ALLOW_DIRECT_CONNECTIONS">
                         <xsd:documentation>
                            restricts cluster connections to the listed connector-ref's
                         </xsd:documentation>
@@ -1558,27 +1554,60 @@
       </xsd:attribute>
 
    </xsd:complexType>
-
    <xsd:complexType name="haPolicyType">
-      <xsd:all>
-         <xsd:element name="policy-type" minOccurs="0" maxOccurs="1" default="NONE">
+      <xsd:choice>
+         <xsd:element name="live-only" type="haLiveOnlyPolicyType" minOccurs="0" maxOccurs="1">
             <xsd:annotation>
                <xsd:documentation>
-                  what kind of HA Policy should we use
+                  A live only server with no HA capabilities apart from scale down.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="replication" type="haReplicationType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  Configuration for a replicated server, either master, slave or colocated.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="shared-store" type="haSharedStoreType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  Configuration for a shared store server, either master, slave or colocated.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+      </xsd:choice>
+   </xsd:complexType>
+
+   <xsd:complexType name="haReplicationType">
+      <xsd:choice>
+         <xsd:element name="master" type="replicatedPolicyType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  A live server configured to replicate.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="slave" type="replicaPolicyType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  A backup server configured to replicate.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="colocated" type="haColocationReplicationType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  a replicated lives server that will allow requests to create colocated replicated backup servers.
                </xsd:documentation>
             </xsd:annotation>
-            <xsd:simpleType>
-               <xsd:restriction base="xsd:string">
-                  <xsd:enumeration value="NONE"/>
-                  <xsd:enumeration value="REPLICATED"/>
-                  <xsd:enumeration value="SHARED_STORE"/>
-                  <xsd:enumeration value="BACKUP_REPLICATED"/>
-                  <xsd:enumeration value="BACKUP_SHARED_STORE"/>
-                  <xsd:enumeration value="COLOCATED_REPLICATED"/>
-                  <xsd:enumeration value="COLOCATED_SHARED_STORE"/>
-               </xsd:restriction>
-            </xsd:simpleType>
          </xsd:element>
+      </xsd:choice>
+   </xsd:complexType>
+
+   <xsd:complexType name="haColocationReplicationType">
+      <xsd:all>
          <xsd:element name="request-backup" type="xsd:boolean" minOccurs="0" maxOccurs="1" default="false">
             <xsd:annotation hq:field_name="DEFAULT_HAPOLICY_REQUEST_BACKUP">
                <xsd:documentation>
@@ -1614,24 +1643,11 @@
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="backup-strategy" minOccurs="0" maxOccurs="1">
-            <xsd:annotation>
-               <xsd:documentation>
-                  The backup strategy to use if we are a backup or for any colocated backups.
-               </xsd:documentation>
-            </xsd:annotation>
-            <xsd:simpleType>
-               <xsd:restriction base="xsd:string">
-                  <xsd:enumeration value="FULL"/>
-                  <xsd:enumeration value="SCALE_DOWN"/>
-               </xsd:restriction>
-            </xsd:simpleType>
-         </xsd:element>
-         <xsd:element name="scale-down-connectors" minOccurs="0" maxOccurs="1">
+         <xsd:element name="excludes" maxOccurs="1" minOccurs="0">
             <xsd:annotation>
                <xsd:documentation>
-                  A list of connectors to use for scaling down, if not supplied then the scale-down-discovery-group or
-                  first invm connector will be used
+                  the connectors that shouldn't have their ports offset, typically remote connectors or the
+                  connector used in the cluster connection if scalinmg down
                </xsd:documentation>
             </xsd:annotation>
             <xsd:complexType>
@@ -1640,41 +1656,132 @@
                </xsd:sequence>
             </xsd:complexType>
          </xsd:element>
-         <xsd:element name="scale-down-discovery-group" type="xsd:string" minOccurs="0" maxOccurs="1">
+         <xsd:element name="master" type="replicatedPolicyType" minOccurs="0" maxOccurs="1">
             <xsd:annotation>
                <xsd:documentation>
-                  The discovery group to use for scale down, if not supplied then the scale-down-connectors or first
-                  invm connector will be used
+                  The configuration for the live replicated server.
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="scale-down-group-name" type="xsd:string" minOccurs="0" maxOccurs="1">
+         <xsd:element name="slave" type="replicaPolicyType" minOccurs="0" maxOccurs="1">
             <xsd:annotation>
                <xsd:documentation>
-                  The scale down group to scale down to, a server will only scale down to a server within the same group
+                  The configuration for any slaves created.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+      </xsd:all>
+   </xsd:complexType>
+
+   <xsd:complexType name="haColocationSharedStoreType">
+      <xsd:all>
+         <xsd:element name="request-backup" type="xsd:boolean" minOccurs="0" maxOccurs="1" default="false">
+            <xsd:annotation>
+               <xsd:documentation>
+                  If true then the server will request a backup on another node
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="backup-request-retries" type="xsd:int" minOccurs="0" maxOccurs="1" default="-1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  How many times the live server will try to request a backup, -1 means for ever.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="backup-request-retry-interval" type="xsd:long" minOccurs="0" maxOccurs="1" default="5000">
+            <xsd:annotation>
+               <xsd:documentation>
+                  How long to wait for retries between attempts to request a backup server.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="max-backups" type="xsd:int" minOccurs="0" maxOccurs="1" default="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  Whether or not this live server will accept backup requests from other live servers.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="backup-port-offset" type="xsd:int" minOccurs="0" maxOccurs="1" default="100">
+            <xsd:annotation>
+               <xsd:documentation>
+                  The offset to use for the Connectors and Acceptors when creating a new backup server.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="master" type="sharedStoreMasterPolicyType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  The configuration for the live shared store server.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="slave" type="sharedStoreSlavePolicyType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  The configuration for any shared store backups created.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+      </xsd:all>
+   </xsd:complexType>
+
+   <xsd:complexType name="haSharedStoreType">
+      <xsd:choice>
+         <xsd:element name="master" type="sharedStoreMasterPolicyType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  A shared store live server configuration.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="slave" type="sharedStoreSlavePolicyType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  A shared store backup server configuration.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="colocated" type="haColocationSharedStoreType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  A shared store colocated configuration
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="backup-group-name" type="xsd:string" minOccurs="0" maxOccurs="1">
+      </xsd:choice>
+   </xsd:complexType>
+
+   <xsd:complexType name="haLiveOnlyPolicyType">
+      <xsd:all>
+         <xsd:element name="scale-down" type="scaleDownType" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  The scale down configuration of this live server.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+      </xsd:all>
+   </xsd:complexType>
+   <xsd:complexType name="replicatedPolicyType">
+      <xsd:all>
+         <xsd:element name="group-name" type="xsd:string" minOccurs="0" maxOccurs="1">
             <xsd:annotation>
                <xsd:documentation>
                   used for replication, if set, (remote) backup servers will only pair with live servers with matching
-                  backup-group-name
+                  group-name
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="remote-connectors" maxOccurs="1" minOccurs="0">
+         <xsd:element name="cluster-name" type="xsd:string" maxOccurs="1" minOccurs="0">
             <xsd:annotation>
                <xsd:documentation>
-                  the remote connectors that shouldn't have their ports offset, typically remote connectors or the
-                  connector used in the cluster connection if scalinmg down
+                  Name of the cluster configuration to use for replication. This setting is only necessary in case you
+                  configure multiple cluster connections. It is used by a replicating backups and by live servers that
+                  may attempt fail-back.
                </xsd:documentation>
             </xsd:annotation>
-            <xsd:complexType>
-               <xsd:sequence>
-                  <xsd:element name="connector-ref" type="xsd:string" maxOccurs="unbounded" minOccurs="1"/>
-               </xsd:sequence>
-            </xsd:complexType>
          </xsd:element>
          <xsd:element name="check-for-live-server" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
             <xsd:annotation hq:linkend="hq.check-for-live-server" hq:field_name="DEFAULT_CHECK_FOR_LIVE_SERVER">
@@ -1686,6 +1793,50 @@
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
+      </xsd:all>
+   </xsd:complexType>
+   <xsd:complexType name="replicaPolicyType">
+      <xsd:all>
+         <xsd:element name="group-name" type="xsd:string" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  used for replication, if set, (remote) backup servers will only pair with live servers with matching
+                  group-name
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="cluster-name" type="xsd:string" maxOccurs="1" minOccurs="0">
+            <xsd:annotation>
+               <xsd:documentation>
+                  Name of the cluster configuration to use for replication. This setting is only necessary in case you
+                  configure multiple cluster connections. It is used by a replicating backups and by live servers that
+                  may attempt fail-back.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="max-saved-replicated-journals-size" type="xsd:int" default="2" maxOccurs="1" minOccurs="0">
+            <xsd:annotation hq:field_name="DEFAULT_MAX_SAVED_REPLICATED_JOURNALS_SIZE">
+               <xsd:documentation>
+                  This specifies how many times a replicated backup server can restart after moving its files on start.
+                  Once there are this number of backup journal files the server will stop permanently after if fails
+                  back.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="scale-down" type="scaleDownType" maxOccurs="1" minOccurs="0">
+            <xsd:annotation>
+               <xsd:documentation>
+                  if provided then this backup will scale down rather than becoming live after fail over.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="restart-backup" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
+            <xsd:annotation hq:linkend="ha.restart-backup" hq:field_name="DEFAULT_RESTART_BACKUP">
+               <xsd:documentation>
+                  Will this server, if a backup, restart once it has been stopped because of failback or scaling down.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
          <xsd:element name="allow-failback" type="xsd:boolean" default="true" maxOccurs="1" minOccurs="0">
             <xsd:annotation hq:linkend="ha.allow-fail-back" hq:field_name="DEFAULT_ALLOW_AUTO_FAILBACK">
                <xsd:documentation>
@@ -1697,21 +1848,25 @@
             </xsd:annotation>
          </xsd:element>
          <xsd:element name="failback-delay" type="xsd:long" default="5000" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="ha.allow-fail-back" hq:default="(in milliseconds)"
-                            hq:field_name="DEFAULT_FAILBACK_DELAY">
+            <xsd:annotation hq:linkend="ha.allow-fail-back" hq:default="(in milliseconds)" hq:field_name="DEFAULT_FAILBACK_DELAY">
                <xsd:documentation>
-                  delay to wait before fail-back occurs on (live's) restart
+                  if we have to start as a replicated server this is the delay to wait before fail-back occurs
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="failover-on-shutdown" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="ha.allow-fail-back" hq:field_name="DEFAULT_FAILOVER_ON_SERVER_SHUTDOWN">
+      </xsd:all>
+   </xsd:complexType>
+   <xsd:complexType name="colocatedReplicaPolicyType">
+      <xsd:all>
+         <xsd:element name="group-name" type="xsd:string" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
                <xsd:documentation>
-                  Will this backup server come live on a normal server shutdown
+                  used for replication, if set, (remote) backup servers will only pair with live servers with matching
+                  group-name
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="replication-clustername" type="xsd:string" maxOccurs="1" minOccurs="0">
+         <xsd:element name="cluster-name" type="xsd:string" maxOccurs="1" minOccurs="0">
             <xsd:annotation>
                <xsd:documentation>
                   Name of the cluster configuration to use for replication. This setting is only necessary in case you
@@ -1720,57 +1875,173 @@
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="scale-down-clustername" type="xsd:string" maxOccurs="1" minOccurs="0">
+         <xsd:element name="max-saved-replicated-journals-size" type="xsd:int" default="2" maxOccurs="1" minOccurs="0">
             <xsd:annotation>
                <xsd:documentation>
-                  Name of the cluster configuration to use for scaling down. This setting is only necessary in case you
-                  configure multiple cluster connections.
+                  This specifies how many times a replicated backup server can restart after moving its files on start.
+                  Once there are this number of backup journal files the server will stop permanently after if fails
+                  back.
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="max-saved-replicated-journals-size" type="xsd:int" default="2" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:field_name="DEFAULT_MAX_SAVED_REPLICATED_JOURNALS_SIZE">
+         <xsd:element name="scale-down" type="scaleDownType" maxOccurs="1" minOccurs="0">
+            <xsd:annotation>
                <xsd:documentation>
-                  This specifies how many times a replicated backup server can restart after moving its files on start.
-                  Once there are this number of backup journal files the server will stop permanently after if fails
-                  back.
+                  if provided then this backup will scale down rather than becoming live after fail over.
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
-         <xsd:element name="scale-down" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="ha.scale-down" hq:field_name="DEFAULT_SCALE_DOWN">
+         <xsd:element name="restart-backup" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
+            <xsd:annotation hq:linkend="ha.restart-backup">
+               <xsd:documentation>
+                  Will this server, if a backup, restart once it has been stopped because of failback or scaling down.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+      </xsd:all>
+   </xsd:complexType>
+   <xsd:complexType name="sharedStoreMasterPolicyType">
+      <xsd:all>
+         <xsd:element name="failback-delay" type="xsd:long" default="5000" maxOccurs="1" minOccurs="0">
+            <xsd:annotation>
+               <xsd:documentation>
+                  delay to wait before fail-back occurs on (live's) restart
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="failover-on-shutdown" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
+            <xsd:annotation hq:linkend="ha.allow-fail-back" hq:field_name="DEFAULT_FAILOVER_ON_SERVER_SHUTDOWN">
                <xsd:documentation>
-                  Will this server send its messages to another live server in the cluster when shut-down cleanly.
+                  Will this backup server come live on a normal server shutdown
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+      </xsd:all>
+   </xsd:complexType>
+   <xsd:complexType name="sharedStoreSlavePolicyType">
+      <xsd:all>
+         <xsd:element name="allow-failback" type="xsd:boolean" default="true" maxOccurs="1" minOccurs="0">
+            <xsd:annotation hq:linkend="ha.allow-fail-back">
+               <xsd:documentation>
+                  Whether a server will automatically stop when a another places a request to take over
+                  its place. The use case is when a regular server stops and its backup takes over its
+                  duties, later the main server restarts and requests the server (the former backup) to
+                  stop operating.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="failback-delay" type="xsd:long" default="5000" maxOccurs="1" minOccurs="0">
+            <xsd:annotation>
+               <xsd:documentation>
+                  delay to wait before fail-back occurs on (live's) restart
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="failover-on-shutdown" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
+            <xsd:annotation>
+               <xsd:documentation>
+                  Will this backup server come live on a normal server shutdown
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="scale-down" type="scaleDownType" maxOccurs="1" minOccurs="0">
+            <xsd:annotation>
+               <xsd:documentation>
+                  if provided then this backup will scale down rather than becoming live after fail over.
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
          <xsd:element name="restart-backup" type="xsd:boolean" default="false" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:linkend="ha.restart-backup" hq:field_name="DEFAULT_RESTART_BACKUP">
+            <xsd:annotation hq:linkend="ha.restart-backup">
                <xsd:documentation>
                   Will this server, if a backup, restart once it has been stopped because of failback or scaling down.
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
       </xsd:all>
-      <xsd:attribute name="template" use="optional">
-         <xsd:annotation>
-            <xsd:documentation>
-               if true then the backup will use the same configuration as the live server.
-            </xsd:documentation>
-         </xsd:annotation>
-         <xsd:simpleType>
-            <xsd:restriction base="xsd:string">
-               <xsd:enumeration value="NONE"/>
-               <xsd:enumeration value="REPLICATED"/>
-               <xsd:enumeration value="SHARED_STORE"/>
-               <xsd:enumeration value="BACKUP_REPLICATED"/>
-               <xsd:enumeration value="BACKUP_SHARED_STORE"/>
-               <xsd:enumeration value="COLOCATED_REPLICATED"/>
-               <xsd:enumeration value="COLOCATED_SHARED_STORE"/>
-            </xsd:restriction>
-         </xsd:simpleType>
-      </xsd:attribute>
    </xsd:complexType>
+   <xsd:complexType name="colocatedPolicyType">
+      <xsd:all>
+         <xsd:element name="request-backup" type="xsd:boolean" minOccurs="0" maxOccurs="1" default="false">
+            <xsd:annotation>
+               <xsd:documentation>
+                  If true then the server will request a backup on another node
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="backup-request-retries" type="xsd:int" minOccurs="0" maxOccurs="1" default="-1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  How many times the live server will try to request a backup, -1 means for ever.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="backup-request-retry-interval" type="xsd:long" minOccurs="0" maxOccurs="1" default="5000">
+            <xsd:annotation>
+               <xsd:documentation>
+                  How long to wait for retries between attempts to request a backup server.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="max-backups" type="xsd:int" minOccurs="0" maxOccurs="1" default="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  Whether or not this live server will accept backup requests from other live servers.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="backup-port-offset" type="xsd:int" minOccurs="0" maxOccurs="1" default="100">
+            <xsd:annotation>
+               <xsd:documentation>
+                  The offset to use for the Connectors and Acceptors when creating a new backup server.
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+      </xsd:all>
+   </xsd:complexType>
+   <xsd:complexType name="scaleDownType">
+      <xsd:sequence>
+         <xsd:element name="enabled" type="xsd:boolean" default="true" maxOccurs="1" minOccurs="0">
+            <xsd:annotation hq:linkend="ha.scale-down" hq:field_name="DEFAULT_SCALE_DOWN_ENABLED">
+               <xsd:documentation>
+                  its possible that you only want a server to partake in scale down as a receiver, via a group.
+                  In this case set scale-down to false
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="group-name" type="xsd:string" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  The scale down group to scale down to, a server will only scale down to a server within the same group
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:choice>
+         <xsd:element name="discovery-group" type="xsd:string" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  The discovery group to use for scale down, if not supplied then the scale-down-connectors or first
+                  invm connector will be used
+               </xsd:documentation>
+            </xsd:annotation>
+         </xsd:element>
+         <xsd:element name="connectors" minOccurs="0" maxOccurs="1">
+            <xsd:annotation>
+               <xsd:documentation>
+                  A list of connectors to use for scaling down, if not supplied then the scale-down-discovery-group or
+                  first invm connector will be used
+               </xsd:documentation>
+            </xsd:annotation>
+            <xsd:complexType>
+               <xsd:sequence>
+                  <xsd:element name="connector-ref" type="xsd:string" maxOccurs="unbounded" minOccurs="1"/>
+               </xsd:sequence>
+            </xsd:complexType>
+         </xsd:element>
+         </xsd:choice>
+      </xsd:sequence>
+   </xsd:complexType>
+
    <xsd:complexType name="groupingHandlerType">
       <xsd:all>
          <xsd:element name="type" maxOccurs="1" minOccurs="1">
@@ -1795,14 +2066,14 @@
             </xsd:annotation>
          </xsd:element>
          <xsd:element name="timeout" type="xsd:int" default="5000" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:default="(ms)">
+            <xsd:annotation hq:default="(ms)" hq:field_name="DEFAULT_GROUPING_HANDLER_TIMEOUT">
                <xsd:documentation>
                   How long to wait for a decision
                </xsd:documentation>
             </xsd:annotation>
          </xsd:element>
          <xsd:element name="group-timeout" type="xsd:int" default="-1" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:default="(ms)">
+            <xsd:annotation hq:default="(ms)" hq:field_name="DEFAULT_GROUPING_HANDLER_GROUP_TIMEOUT">
                <xsd:documentation>
                   How long a group binding will be used, -1 means for ever. Bindings are removed after this wait
                   elapses. On the remote node this is used to determine how often you should re-query the main
@@ -1811,7 +2082,7 @@
             </xsd:annotation>
          </xsd:element>
          <xsd:element name="reaper-period" type="xsd:long" default="30000" maxOccurs="1" minOccurs="0">
-            <xsd:annotation hq:default="(ms)">
+            <xsd:annotation hq:default="(ms)" hq:field_name="DEFAULT_GROUPING_HANDLER_REAPER_PERIOD">
                <xsd:documentation>
                   How often the reaper will be run to check for timed out group bindings. Only valid for LOCAL handlers
                </xsd:documentation>
@@ -1966,6 +2237,37 @@
                   </xsd:documentation>
                </xsd:annotation>
             </xsd:element>
+
+            <xsd:element name="slow-consumer-threshold" type="xsd:long" maxOccurs="1" minOccurs="0">
+               <xsd:annotation hq:default="-1">
+                  <xsd:documentation>
+                     The minimum rate of message consumption allowed before a consumer is considered "slow." Measured
+                     in messages-per-second.
+                  </xsd:documentation>
+               </xsd:annotation>
+            </xsd:element>
+
+            <xsd:element name="slow-consumer-policy" default="NOTIFY" maxOccurs="1" minOccurs="0">
+               <xsd:annotation>
+                  <xsd:documentation>
+                     what happens when a slow consumer is identified
+                  </xsd:documentation>
+               </xsd:annotation>
+               <xsd:simpleType>
+                  <xsd:restriction base="xsd:string">
+                     <xsd:enumeration value="KILL"/>
+                     <xsd:enumeration value="NOTIFY"/>
+                  </xsd:restriction>
+               </xsd:simpleType>
+            </xsd:element>
+
+            <xsd:element name="slow-consumer-check-period" type="xsd:long" maxOccurs="1" minOccurs="0">
+               <xsd:annotation hq:default="5">
+                  <xsd:documentation>
+                     How often to check for slow consumers on a particular queue. Measured in minutes.
+                  </xsd:documentation>
+               </xsd:annotation>
+            </xsd:element>
          </xsd:all>
 
          <xsd:attribute name="match" type="xsd:string" use="required">

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/config/impl/ConfigurationImplTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/config/impl/ConfigurationImplTest.java b/hornetq-server/src/test/java/org/hornetq/core/config/impl/ConfigurationImplTest.java
index aa396c3..1718125 100644
--- a/hornetq-server/src/test/java/org/hornetq/core/config/impl/ConfigurationImplTest.java
+++ b/hornetq-server/src/test/java/org/hornetq/core/config/impl/ConfigurationImplTest.java
@@ -11,7 +11,7 @@
  * permissions and limitations under the License.
  */
 package org.hornetq.core.config.impl;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
 import org.junit.Before;
 
 import org.junit.Test;
@@ -45,7 +45,6 @@ public class ConfigurationImplTest extends UnitTestCase
    @Test
    public void testDefaults()
    {
-      Assert.assertEquals(HornetQDefaultConfiguration.isDefaultSharedStore(), conf.getHAPolicy().isSharedStore());
       Assert.assertEquals(HornetQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(),
                           conf.getScheduledThreadPoolMaxSize());
       Assert.assertEquals(HornetQDefaultConfiguration.getDefaultSecurityInvalidationInterval(),
@@ -110,10 +109,6 @@ public class ConfigurationImplTest extends UnitTestCase
    {
       for (int j = 0; j < 100; j++)
       {
-         HAPolicy.POLICY_TYPE p = HAPolicy.POLICY_TYPE.SHARED_STORE;
-         conf.getHAPolicy().setPolicyType(p);
-         Assert.assertEquals(p, conf.getHAPolicy().getPolicyType());
-
          int i = RandomUtil.randomInt();
          conf.setScheduledThreadPoolMaxSize(i);
          Assert.assertEquals(i, conf.getScheduledThreadPoolMaxSize());
@@ -324,7 +319,7 @@ public class ConfigurationImplTest extends UnitTestCase
    {
       boolean b = RandomUtil.randomBoolean();
 
-      conf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
+      conf.setHAPolicyConfiguration(new LiveOnlyPolicyConfiguration());
 
       int i = RandomUtil.randomInt();
       conf.setScheduledThreadPoolMaxSize(i);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/config/impl/DefaultsFileConfigurationTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/config/impl/DefaultsFileConfigurationTest.java b/hornetq-server/src/test/java/org/hornetq/core/config/impl/DefaultsFileConfigurationTest.java
index 359b3f8..15e9f72 100644
--- a/hornetq-server/src/test/java/org/hornetq/core/config/impl/DefaultsFileConfigurationTest.java
+++ b/hornetq-server/src/test/java/org/hornetq/core/config/impl/DefaultsFileConfigurationTest.java
@@ -12,11 +12,9 @@
  */
 package org.hornetq.core.config.impl;
 
-import org.hornetq.core.config.BackupStrategy;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
 import org.junit.Test;
 
-import java.util.ArrayList;
 import java.util.Collections;
 
 import org.junit.Assert;
@@ -39,9 +37,6 @@ public class DefaultsFileConfigurationTest extends ConfigurationImplTest
    @Test
    public void testDefaults()
    {
-      Assert.assertEquals(HornetQDefaultConfiguration.isDefaultBackup(), conf.getHAPolicy().isBackup());
-
-      Assert.assertEquals(HornetQDefaultConfiguration.isDefaultSharedStore(), conf.getHAPolicy().isSharedStore());
 
       Assert.assertEquals(HornetQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(),
                           conf.getScheduledThreadPoolMaxSize());
@@ -142,28 +137,8 @@ public class DefaultsFileConfigurationTest extends ConfigurationImplTest
 
       Assert.assertEquals(HornetQDefaultConfiguration.getDefaultMessageExpiryThreadPriority(),
                           conf.getMessageExpiryThreadPriority());
-      Assert.assertEquals("replication cluster name", null, conf.getHAPolicy().getReplicationClustername());
-      Assert.assertEquals("scale-down cluster name", null, conf.getHAPolicy().getScaleDownClustername());
-      Assert.assertEquals("ha-policy type", HAPolicy.POLICY_TYPE.valueOf(HornetQDefaultConfiguration.getDefaultHapolicyType()), conf.getHAPolicy().getPolicyType());
-      Assert.assertEquals("check-for-live-server", HornetQDefaultConfiguration.isDefaultCheckForLiveServer(), conf.getHAPolicy().isCheckForLiveServer());
-      Assert.assertEquals("scale-down", HornetQDefaultConfiguration.isDefaultScaleDown(), conf.getHAPolicy().isScaleDown());
-      Assert.assertEquals("max-saved-replicated-journals-size", HornetQDefaultConfiguration.getDefaultMaxSavedReplicatedJournalsSize(), conf.getHAPolicy().getMaxSavedReplicatedJournalsSize());
-      Assert.assertEquals("failover-on-shutdown", HornetQDefaultConfiguration.isDefaultFailoverOnServerShutdown(), conf.getHAPolicy().isFailoverOnServerShutdown());
-      Assert.assertEquals("backup-group-name", null, conf.getHAPolicy().getBackupGroupName());
-      Assert.assertEquals("backup-port-offset", HornetQDefaultConfiguration.getDefaultHapolicyBackupPortOffset(), conf.getHAPolicy().getBackupPortOffset());
-      Assert.assertEquals("backup-request-retries", HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetries(), conf.getHAPolicy().getBackupRequestRetries());
-      Assert.assertEquals("backup-request-retry-interval", HornetQDefaultConfiguration.getDefaultHapolicyBackupRequestRetryInterval(), conf.getHAPolicy().getBackupRequestRetryInterval());
-      Assert.assertEquals("backup-strategy", BackupStrategy.valueOf(HornetQDefaultConfiguration.getDefaultHapolicyBackupStrategy()), conf.getHAPolicy().getBackupStrategy());
-      Assert.assertEquals("failback-delay", HornetQDefaultConfiguration.getDefaultFailbackDelay(), conf.getHAPolicy().getFailbackDelay());
-      Assert.assertEquals("max-backups", HornetQDefaultConfiguration.getDefaultHapolicyMaxBackups(), conf.getHAPolicy().getMaxBackups());
-      Assert.assertEquals("remote-connectors for ha-policy", new ArrayList<>(), conf.getHAPolicy().getRemoteConnectors());
-      Assert.assertEquals("scale-down-connectors for ha-policy", new ArrayList<>(), conf.getHAPolicy().getScaleDownConnectors());
-      Assert.assertEquals("scale-down-discovery-group", null, conf.getHAPolicy().getScaleDownDiscoveryGroup());
-      Assert.assertEquals("scale-down-group-name", null, conf.getHAPolicy().getScaleDownGroupName());
-      Assert.assertEquals("allow-failback", HornetQDefaultConfiguration.isDefaultAllowAutoFailback(), conf.getHAPolicy().isAllowAutoFailBack());
-      Assert.assertEquals("backup", false, conf.getHAPolicy().isBackup());
-      Assert.assertEquals("request-backup", HornetQDefaultConfiguration.isDefaultHapolicyRequestBackup(), conf.getHAPolicy().isRequestBackup());
-      Assert.assertEquals("shared-store", false, conf.getHAPolicy().isSharedStore());
+
+      Assert.assertTrue(conf.getHAPolicyConfiguration() instanceof LiveOnlyPolicyConfiguration);
    }
 
    // Protected ---------------------------------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationParserTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationParserTest.java b/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationParserTest.java
index ccafbad..a88a79c 100644
--- a/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationParserTest.java
+++ b/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationParserTest.java
@@ -124,8 +124,6 @@ public class FileConfigurationParserTest extends UnitTestCase
       config = parser.parseMainConfig(new ByteArrayInputStream(configStr.getBytes(StandardCharsets.UTF_8)));
 
       assertEquals("newpassword", config.getClusterPassword());
-
-      assertEquals("abackupgroupname", config.getHAPolicy().getBackupGroupName());
    }
 
    private static String firstPart =

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationTest.java b/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationTest.java
index 381c08d..fc60af0 100644
--- a/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationTest.java
+++ b/hornetq-server/src/test/java/org/hornetq/core/config/impl/FileConfigurationTest.java
@@ -13,21 +13,21 @@
 package org.hornetq.core.config.impl;
 
 import java.util.Collections;
-import java.util.List;
 
 import org.hornetq.api.core.BroadcastGroupConfiguration;
 import org.hornetq.api.core.DiscoveryGroupConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.UDPBroadcastGroupConfiguration;
-import org.hornetq.core.config.BackupStrategy;
 import org.hornetq.core.config.BridgeConfiguration;
 import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.DivertConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ha.LiveOnlyPolicyConfiguration;
 import org.hornetq.core.security.Role;
 import org.hornetq.core.server.JournalType;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.settings.impl.SlowConsumerPolicy;
 import org.junit.Assert;
 import org.junit.Test;
 
@@ -68,8 +68,6 @@ public class FileConfigurationTest extends ConfigurationImplTest
       Assert.assertEquals(8, conf.getMessageExpiryThreadPriority());
       Assert.assertEquals(127, conf.getIDCacheSize());
       Assert.assertEquals(true, conf.isPersistIDCache());
-      Assert.assertEquals(false, conf.getHAPolicy().isBackup());
-      Assert.assertEquals(false, conf.getHAPolicy().isSharedStore());
       Assert.assertEquals(true, conf.isPersistDeliveryCountBeforeDelivery());
       Assert.assertEquals("pagingdir", conf.getPagingDirectory());
       Assert.assertEquals("somedir", conf.getBindingsDirectory());
@@ -234,32 +232,13 @@ public class FileConfigurationTest extends ConfigurationImplTest
 
       Assert.assertEquals(2, conf.getClusterConfigurations().size());
 
-      HAPolicy haPolicy = conf.getHAPolicy();
-      assertEquals(HAPolicy.POLICY_TYPE.COLOCATED_REPLICATED, haPolicy.getPolicyType());
-      assertEquals(true, haPolicy.isRequestBackup());
-      assertEquals(33, haPolicy.getBackupRequestRetries());
-      assertEquals(1234, haPolicy.getBackupRequestRetryInterval());
-      assertEquals(12, haPolicy.getMaxBackups());
-      assertEquals(1002, haPolicy.getBackupPortOffset());
-      assertEquals(BackupStrategy.SCALE_DOWN, haPolicy.getBackupStrategy());
-      assertEquals("wahey!", haPolicy.getScaleDownDiscoveryGroup());
-      assertEquals("boo!", haPolicy.getScaleDownGroupName());
-      List<String> scaleDownConnectors = haPolicy.getScaleDownConnectors();
-      assertEquals(2, scaleDownConnectors.size());
-      assertEquals("sd-connector1", scaleDownConnectors.get(0));
-      assertEquals("sd-connector2", scaleDownConnectors.get(1));
-      List<String> remoteConnectors = haPolicy.getRemoteConnectors();
-      assertEquals(2, remoteConnectors.size());
-      assertEquals("remote-connector1", remoteConnectors.get(0));
-      assertEquals("remote-connector2", remoteConnectors.get(1));
-      assertEquals(true, haPolicy.isCheckForLiveServer());
-      assertEquals(false, haPolicy.isAllowAutoFailBack());
-      assertEquals(10000, haPolicy.getFailbackDelay());
-      assertEquals(true, haPolicy.isFailoverOnServerShutdown());
-      assertEquals("replicationClustername", haPolicy.getReplicationClustername());
-      assertEquals("scaleDownClustername", haPolicy.getScaleDownClustername());
-      assertEquals(3, haPolicy.getMaxSavedReplicatedJournalsSize());
-      assertEquals(true, haPolicy.isScaleDown());
+      HAPolicyConfiguration pc = conf.getHAPolicyConfiguration();
+      assertNotNull(pc);
+      assertTrue(pc instanceof LiveOnlyPolicyConfiguration);
+      LiveOnlyPolicyConfiguration lopc = (LiveOnlyPolicyConfiguration) pc;
+      assertNotNull(lopc.getScaleDownConfiguration());
+      assertEquals(lopc.getScaleDownConfiguration().getGroupName(), "boo!");
+      assertEquals(lopc.getScaleDownConfiguration().getDiscoveryGroup(), "wahey");
 
       for (ClusterConnectionConfiguration ccc : conf.getClusterConfigurations())
       {
@@ -311,6 +290,9 @@ public class FileConfigurationTest extends ConfigurationImplTest
       assertEquals(81738173872337L, conf.getAddressesSettings().get("a1").getPageSizeBytes());
       assertEquals(10, conf.getAddressesSettings().get("a1").getPageCacheMaxSize());
       assertEquals(4, conf.getAddressesSettings().get("a1").getMessageCounterHistoryDayLimit());
+      assertEquals(10, conf.getAddressesSettings().get("a1").getSlowConsumerThreshold());
+      assertEquals(5, conf.getAddressesSettings().get("a1").getSlowConsumerCheckPeriod());
+      assertEquals(SlowConsumerPolicy.NOTIFY, conf.getAddressesSettings().get("a1").getSlowConsumerPolicy());
 
       assertEquals("a2.1", conf.getAddressesSettings().get("a2").getDeadLetterAddress().toString());
       assertEquals("a2.2", conf.getAddressesSettings().get("a2").getExpiryAddress().toString());
@@ -319,6 +301,9 @@ public class FileConfigurationTest extends ConfigurationImplTest
       assertEquals(7126716262626L, conf.getAddressesSettings().get("a2").getPageSizeBytes());
       assertEquals(20, conf.getAddressesSettings().get("a2").getPageCacheMaxSize());
       assertEquals(8, conf.getAddressesSettings().get("a2").getMessageCounterHistoryDayLimit());
+      assertEquals(20, conf.getAddressesSettings().get("a2").getSlowConsumerThreshold());
+      assertEquals(15, conf.getAddressesSettings().get("a2").getSlowConsumerCheckPeriod());
+      assertEquals(SlowConsumerPolicy.KILL, conf.getAddressesSettings().get("a2").getSlowConsumerPolicy());
 
 
       assertEquals(2, conf.getQueueConfigurations().size());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/config/impl/HAPolicyConfigurationTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/config/impl/HAPolicyConfigurationTest.java b/hornetq-server/src/test/java/org/hornetq/core/config/impl/HAPolicyConfigurationTest.java
new file mode 100644
index 0000000..f0dde3a
--- /dev/null
+++ b/hornetq-server/src/test/java/org/hornetq/core/config/impl/HAPolicyConfigurationTest.java
@@ -0,0 +1,434 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.config.impl;
+
+import org.hornetq.core.server.cluster.ha.ColocatedPolicy;
+import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.server.cluster.ha.LiveOnlyPolicy;
+import org.hornetq.core.server.cluster.ha.ReplicaPolicy;
+import org.hornetq.core.server.cluster.ha.ReplicatedPolicy;
+import org.hornetq.core.server.cluster.ha.ScaleDownPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreMasterPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreSlavePolicy;
+import org.hornetq.core.server.impl.ColocatedActivation;
+import org.hornetq.core.server.impl.LiveOnlyActivation;
+import org.hornetq.core.server.impl.SharedNothingBackupActivation;
+import org.hornetq.core.server.impl.SharedNothingLiveActivation;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.server.impl.Activation;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.SharedStoreBackupActivation;
+import org.hornetq.core.server.impl.SharedStoreLiveActivation;
+import org.hornetq.tests.util.UnitTestCase;
+import org.junit.Test;
+
+import java.util.List;
+
+public class HAPolicyConfigurationTest extends UnitTestCase
+{
+   @Test
+   public void liveOnlyTest() throws Exception
+   {
+      Configuration configuration = createConfiguration("live-only-hapolicy-config.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof LiveOnlyActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof LiveOnlyPolicy);
+         LiveOnlyPolicy liveOnlyPolicy = (LiveOnlyPolicy) haPolicy;
+         ScaleDownPolicy scaleDownPolicy = liveOnlyPolicy.getScaleDownPolicy();
+         assertNotNull(scaleDownPolicy);
+         assertEquals(scaleDownPolicy.getGroupName(), "boo!");
+         assertEquals(scaleDownPolicy.getDiscoveryGroup(), "wahey");
+         List<String> connectors = scaleDownPolicy.getConnectors();
+         assertNotNull(connectors);
+         assertEquals(connectors.size(), 0);
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void liveOnlyTest2() throws Exception
+   {
+      Configuration configuration = createConfiguration("live-only-hapolicy-config2.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof LiveOnlyActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof LiveOnlyPolicy);
+         LiveOnlyPolicy liveOnlyPolicy = (LiveOnlyPolicy) haPolicy;
+         ScaleDownPolicy scaleDownPolicy = liveOnlyPolicy.getScaleDownPolicy();
+         assertNotNull(scaleDownPolicy);
+         assertFalse(scaleDownPolicy.isEnabled());
+         assertEquals(scaleDownPolicy.getGroupName(), "boo!");
+         assertEquals(scaleDownPolicy.getDiscoveryGroup(), null);
+         List<String> connectors = scaleDownPolicy.getConnectors();
+         assertNotNull(connectors);
+         assertEquals(connectors.size(), 2);
+         assertTrue(connectors.contains("sd-connector1"));
+         assertTrue(connectors.contains("sd-connector2"));
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void liveOnlyTest3() throws Exception
+   {
+      liveOnlyTest("live-only-hapolicy-config3.xml");
+   }
+
+   @Test
+   public void liveOnlyTest4() throws Exception
+   {
+      liveOnlyTest("live-only-hapolicy-config4.xml");
+   }
+   @Test
+   public void liveOnlyTest5() throws Exception
+   {
+      liveOnlyTest("live-only-hapolicy-config5.xml");
+   }
+
+   @Test
+   public void ReplicatedTest() throws Exception
+   {
+      Configuration configuration = createConfiguration("replicated-hapolicy-config.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedNothingLiveActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof ReplicatedPolicy);
+         ReplicatedPolicy replicatedPolicy = (ReplicatedPolicy) haPolicy;
+         assertEquals(replicatedPolicy.getGroupName(), "purple");
+         assertTrue(replicatedPolicy.isCheckForLiveServer());
+         assertEquals(replicatedPolicy.getClusterName(), "abcdefg");
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void ReplicaTest() throws Exception
+   {
+      Configuration configuration = createConfiguration("replica-hapolicy-config.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedNothingBackupActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof ReplicaPolicy);
+         ReplicaPolicy replicaPolicy = (ReplicaPolicy) haPolicy;
+         assertEquals(replicaPolicy.getGroupName(), "tiddles");
+         assertEquals(replicaPolicy.getMaxSavedReplicatedJournalsSize(), 22);
+         assertEquals(replicaPolicy.getClusterName(), "33rrrrr");
+         assertFalse(replicaPolicy.isRestartBackup());
+         ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy();
+         assertNotNull(scaleDownPolicy);
+         assertEquals(scaleDownPolicy.getGroupName(), "boo!");
+         assertEquals(scaleDownPolicy.getDiscoveryGroup(), "wahey");
+         List<String> connectors = scaleDownPolicy.getConnectors();
+         assertNotNull(connectors);
+         assertEquals(connectors.size(), 0);
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void ReplicaTest2() throws Exception
+   {
+      Configuration configuration = createConfiguration("replica-hapolicy-config2.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedNothingBackupActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof ReplicaPolicy);
+         ReplicaPolicy replicaPolicy = (ReplicaPolicy) haPolicy;
+         assertEquals(replicaPolicy.getGroupName(), "tiddles");
+         assertEquals(replicaPolicy.getMaxSavedReplicatedJournalsSize(), 22);
+         assertEquals(replicaPolicy.getClusterName(), "33rrrrr");
+         assertFalse(replicaPolicy.isRestartBackup());
+         ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy();
+         assertNotNull(scaleDownPolicy);
+         assertEquals(scaleDownPolicy.getGroupName(), "boo!");
+         assertEquals(scaleDownPolicy.getDiscoveryGroup(), null);
+         List<String> connectors = scaleDownPolicy.getConnectors();
+         assertNotNull(connectors);
+         assertEquals(connectors.size(), 2);
+         assertTrue(connectors.contains("sd-connector1"));
+         assertTrue(connectors.contains("sd-connector2"));
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void ReplicaTest3() throws Exception
+   {
+      Configuration configuration = createConfiguration("replica-hapolicy-config3.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedNothingBackupActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof ReplicaPolicy);
+         ReplicaPolicy replicaPolicy = (ReplicaPolicy) haPolicy;
+         assertEquals(replicaPolicy.getGroupName(), "tiddles");
+         assertEquals(replicaPolicy.getMaxSavedReplicatedJournalsSize(), 22);
+         assertEquals(replicaPolicy.getClusterName(), "33rrrrr");
+         assertFalse(replicaPolicy.isRestartBackup());
+         ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy();
+         assertNull(scaleDownPolicy);
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void SharedStoreMasterTest() throws Exception
+   {
+      Configuration configuration = createConfiguration("shared-store-master-hapolicy-config.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedStoreLiveActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof SharedStoreMasterPolicy);
+         SharedStoreMasterPolicy masterPolicy = (SharedStoreMasterPolicy) haPolicy;
+         assertEquals(masterPolicy.getFailbackDelay(), 3456);
+         assertFalse(masterPolicy.isFailoverOnServerShutdown());
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void SharedStoreSlaveTest() throws Exception
+   {
+      Configuration configuration = createConfiguration("shared-store-slave-hapolicy-config.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedStoreBackupActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof SharedStoreSlavePolicy);
+         SharedStoreSlavePolicy replicaPolicy = (SharedStoreSlavePolicy) haPolicy;
+         assertEquals(replicaPolicy.getFailbackDelay(), 9876);
+         assertFalse(replicaPolicy.isFailoverOnServerShutdown());
+         assertFalse(replicaPolicy.isRestartBackup());
+         ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy();
+         assertNotNull(scaleDownPolicy);
+         assertEquals(scaleDownPolicy.getGroupName(), "boo!");
+         assertEquals(scaleDownPolicy.getDiscoveryGroup(), "wahey");
+         List<String> connectors = scaleDownPolicy.getConnectors();
+         assertNotNull(connectors);
+         assertEquals(connectors.size(), 0);
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void SharedStoreSlaveTest2() throws Exception
+   {
+      Configuration configuration = createConfiguration("shared-store-slave-hapolicy-config2.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedStoreBackupActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof SharedStoreSlavePolicy);
+         SharedStoreSlavePolicy replicaPolicy = (SharedStoreSlavePolicy) haPolicy;
+         assertEquals(replicaPolicy.getFailbackDelay(), 5678);
+         assertTrue(replicaPolicy.isFailoverOnServerShutdown());
+         assertTrue(replicaPolicy.isRestartBackup());
+         ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy();
+         assertNotNull(scaleDownPolicy);
+         assertEquals(scaleDownPolicy.getGroupName(), "boo!");
+         assertEquals(scaleDownPolicy.getDiscoveryGroup(), null);
+         List<String> connectors = scaleDownPolicy.getConnectors();
+         assertNotNull(connectors);
+         assertEquals(connectors.size(), 2);
+         assertTrue(connectors.contains("sd-connector1"));
+         assertTrue(connectors.contains("sd-connector2"));
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void SharedStoreSlaveTest3() throws Exception
+   {
+      Configuration configuration = createConfiguration("shared-store-slave-hapolicy-config3.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof SharedStoreBackupActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof SharedStoreSlavePolicy);
+         SharedStoreSlavePolicy replicaPolicy = (SharedStoreSlavePolicy) haPolicy;
+         assertEquals(replicaPolicy.getFailbackDelay(), 5678);
+         assertTrue(replicaPolicy.isFailoverOnServerShutdown());
+         assertTrue(replicaPolicy.isRestartBackup());
+         ScaleDownPolicy scaleDownPolicy = replicaPolicy.getScaleDownPolicy();
+         assertNull(scaleDownPolicy);
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   @Test
+   public void colocatedTest() throws Exception
+   {
+      Configuration configuration = createConfiguration("colocated-hapolicy-config.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof ColocatedActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof ColocatedPolicy);
+         ColocatedPolicy colocatedPolicy = (ColocatedPolicy) haPolicy;
+         ReplicatedPolicy livePolicy = (ReplicatedPolicy) colocatedPolicy.getLivePolicy();
+         assertNotNull(livePolicy);
+
+         assertEquals(livePolicy.getGroupName(), "purple");
+         assertTrue(livePolicy.isCheckForLiveServer());
+         assertEquals(livePolicy.getClusterName(), "abcdefg");
+         ReplicaPolicy backupPolicy = (ReplicaPolicy) colocatedPolicy.getBackupPolicy();
+         assertNotNull(backupPolicy);
+         assertEquals(backupPolicy.getGroupName(), "tiddles");
+         assertEquals(backupPolicy.getMaxSavedReplicatedJournalsSize(), 22);
+         assertEquals(backupPolicy.getClusterName(), "33rrrrr");
+         assertFalse(backupPolicy.isRestartBackup());
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+
+   @Test
+   public void colocatedTest2() throws Exception
+   {
+      Configuration configuration = createConfiguration("colocated-hapolicy-config2.xml");
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof ColocatedActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof ColocatedPolicy);
+         ColocatedPolicy colocatedPolicy = (ColocatedPolicy) haPolicy;
+         SharedStoreMasterPolicy livePolicy = (SharedStoreMasterPolicy) colocatedPolicy.getLivePolicy();
+         assertNotNull(livePolicy);
+
+         assertFalse(livePolicy.isFailoverOnServerShutdown());
+         assertEquals(livePolicy.getFailbackDelay(), 1234);
+         SharedStoreSlavePolicy backupPolicy = (SharedStoreSlavePolicy) colocatedPolicy.getBackupPolicy();
+         assertNotNull(backupPolicy);
+         assertEquals(backupPolicy.getFailbackDelay(), 44);
+         assertFalse(backupPolicy.isFailoverOnServerShutdown());
+         assertFalse(backupPolicy.isRestartBackup());
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+   private void liveOnlyTest(String file) throws Exception
+   {
+      Configuration configuration = createConfiguration(file);
+      HornetQServerImpl server = new HornetQServerImpl(configuration);
+      try
+      {
+         server.start();
+         Activation activation = server.getActivation();
+         assertTrue(activation instanceof LiveOnlyActivation);
+         HAPolicy haPolicy = server.getHAPolicy();
+         assertTrue(haPolicy instanceof LiveOnlyPolicy);
+         LiveOnlyPolicy liveOnlyPolicy = (LiveOnlyPolicy) haPolicy;
+         ScaleDownPolicy scaleDownPolicy = liveOnlyPolicy.getScaleDownPolicy();
+         assertNull(scaleDownPolicy);
+      }
+      finally
+      {
+         server.stop();
+      }
+   }
+
+
+   protected Configuration createConfiguration(String fileName) throws Exception
+   {
+      FileConfiguration fc = new FileConfiguration(fileName);
+
+      fc.start();
+
+      // we need this otherwise the data folder will be located under hornetq-server and not on the temporary directory
+      fc.setPagingDirectory(getTestDir() + "/" + fc.getPagingDirectory());
+      fc.setLargeMessagesDirectory(getTestDir() + "/" + fc.getLargeMessagesDirectory());
+      fc.setJournalDirectory(getTestDir() + "/" + fc.getJournalDirectory());
+      fc.setBindingsDirectory(getTestDir() + "/" + fc.getBindingsDirectory());
+
+      return fc;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/server/group/impl/ClusteredResetMockTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/server/group/impl/ClusteredResetMockTest.java b/hornetq-server/src/test/java/org/hornetq/core/server/group/impl/ClusteredResetMockTest.java
index ecd998d..e98c86b 100644
--- a/hornetq-server/src/test/java/org/hornetq/core/server/group/impl/ClusteredResetMockTest.java
+++ b/hornetq-server/src/test/java/org/hornetq/core/server/group/impl/ClusteredResetMockTest.java
@@ -20,8 +20,6 @@ import java.util.Set;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
-import junit.framework.Assert;
-
 import org.hornetq.api.core.BroadcastGroupConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
@@ -56,6 +54,7 @@ import org.hornetq.spi.core.remoting.Acceptor;
 import org.hornetq.tests.util.UnitTestCase;
 import org.hornetq.utils.ConcurrentHashSet;
 import org.hornetq.utils.ReusableLatch;
+import org.junit.Assert;
 import org.junit.Test;
 
 /**

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/server/impl/EmbeddedServerTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/server/impl/EmbeddedServerTest.java b/hornetq-server/src/test/java/org/hornetq/core/server/impl/EmbeddedServerTest.java
index cf8bb86..78ac525 100644
--- a/hornetq-server/src/test/java/org/hornetq/core/server/impl/EmbeddedServerTest.java
+++ b/hornetq-server/src/test/java/org/hornetq/core/server/impl/EmbeddedServerTest.java
@@ -38,11 +38,11 @@ public class EmbeddedServerTest
    @Before
    public void setup()
    {
-      configuration = new ConfigurationImpl();
-      configuration.setJournalDirectory(SERVER_JOURNAL_DIR);
-      configuration.setPersistenceEnabled(false);
-      configuration.setSecurityEnabled(false);
-      configuration.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      configuration = new ConfigurationImpl()
+         .setJournalDirectory(SERVER_JOURNAL_DIR)
+         .setPersistenceEnabled(false)
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
 
       server = HornetQServers.newHornetQServer(configuration);
       try

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/server/impl/ScheduledDeliveryHandlerTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/server/impl/ScheduledDeliveryHandlerTest.java b/hornetq-server/src/test/java/org/hornetq/core/server/impl/ScheduledDeliveryHandlerTest.java
index f2613a4..efca9bf 100644
--- a/hornetq-server/src/test/java/org/hornetq/core/server/impl/ScheduledDeliveryHandlerTest.java
+++ b/hornetq-server/src/test/java/org/hornetq/core/server/impl/ScheduledDeliveryHandlerTest.java
@@ -329,8 +329,9 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public void setMessageID(long id)
+      public FakeMessage setMessageID(long id)
       {
+         return this;
       }
 
       @Override
@@ -574,9 +575,9 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public void setUserID(UUID userID)
+      public FakeMessage setUserID(UUID userID)
       {
-
+         return this;
       }
 
       @Override
@@ -604,9 +605,9 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public void setDurable(boolean durable)
+      public FakeMessage setDurable(boolean durable)
       {
-
+         return this;
       }
 
       @Override
@@ -622,9 +623,9 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public void setExpiration(long expiration)
+      public FakeMessage setExpiration(long expiration)
       {
-
+         return this;
       }
 
       @Override
@@ -634,9 +635,9 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public void setTimestamp(long timestamp)
+      public FakeMessage setTimestamp(long timestamp)
       {
-
+         return this;
       }
 
       @Override
@@ -646,9 +647,9 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public void setPriority(byte priority)
+      public FakeMessage setPriority(byte priority)
       {
-
+         return this;
       }
 
       @Override
@@ -974,6 +975,18 @@ public class ScheduledDeliveryHandlerTest extends Assert
       {
          return null;
       }
+
+      @Override
+      public FakeMessage writeBodyBufferBytes(byte[] bytes)
+      {
+         return this;
+      }
+
+      @Override
+      public FakeMessage writeBodyBufferString(String string)
+      {
+         return this;
+      }
    }
 
 
@@ -1178,18 +1191,6 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public long getMessageCount(long timeout)
-      {
-         return 0;
-      }
-
-      @Override
-      public long getInstantMessageCount()
-      {
-         return 0;
-      }
-
-      @Override
       public int getDeliveringCount()
       {
          return 0;
@@ -1226,13 +1227,7 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
-      public long getMessagesAdded(long timeout)
-      {
-         return 0;
-      }
-
-      @Override
-      public long getInstantMessagesAdded()
+      public long getMessagesAcknowledged()
       {
          return 0;
       }
@@ -1472,6 +1467,12 @@ public class ScheduledDeliveryHandlerTest extends Assert
       }
 
       @Override
+      public void resetMessagesAcknowledged()
+      {
+
+      }
+
+      @Override
       public void incrementMesssagesAdded()
       {
 
@@ -1494,5 +1495,17 @@ public class ScheduledDeliveryHandlerTest extends Assert
       {
 
       }
+
+      @Override
+      public void postAcknowledge(MessageReference ref)
+      {
+
+      }
+
+      @Override
+      public float getRate()
+      {
+         return 0.0f;
+      }
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/test/java/org/hornetq/core/settings/AddressSettingsTest.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/test/java/org/hornetq/core/settings/AddressSettingsTest.java b/hornetq-server/src/test/java/org/hornetq/core/settings/AddressSettingsTest.java
new file mode 100644
index 0000000..32c7a3a
--- /dev/null
+++ b/hornetq-server/src/test/java/org/hornetq/core/settings/AddressSettingsTest.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.settings;
+
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
+import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.tests.util.UnitTestCase;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * @author <a href="ataylor@redhat.com">Andy Taylor</a>
+ */
+public class AddressSettingsTest extends UnitTestCase
+{
+   @Test
+   public void testDefaults()
+   {
+      AddressSettings addressSettings = new AddressSettings();
+      Assert.assertEquals(null, addressSettings.getDeadLetterAddress());
+      Assert.assertEquals(null, addressSettings.getExpiryAddress());
+      Assert.assertEquals(AddressSettings.DEFAULT_MAX_DELIVERY_ATTEMPTS, addressSettings.getMaxDeliveryAttempts());
+      Assert.assertEquals(addressSettings.getMaxSizeBytes(), AddressSettings.DEFAULT_MAX_SIZE_BYTES);
+      Assert.assertEquals(AddressSettings.DEFAULT_PAGE_SIZE, addressSettings.getPageSizeBytes());
+      Assert.assertEquals(AddressSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT,
+                          addressSettings.getMessageCounterHistoryDayLimit());
+      Assert.assertEquals(AddressSettings.DEFAULT_REDELIVER_DELAY, addressSettings.getRedeliveryDelay());
+      Assert.assertEquals(AddressSettings.DEFAULT_REDELIVER_MULTIPLIER,
+                          addressSettings.getRedeliveryMultiplier(),
+                          0.000001);
+      Assert.assertEquals(AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD, addressSettings.getSlowConsumerThreshold());
+      Assert.assertEquals(AddressSettings.DEFAULT_SLOW_CONSUMER_CHECK_PERIOD, addressSettings.getSlowConsumerCheckPeriod());
+      Assert.assertEquals(AddressSettings.DEFAULT_SLOW_CONSUMER_POLICY, addressSettings.getSlowConsumerPolicy());
+
+   }
+
+   @Test
+   public void testSingleMerge()
+   {
+      AddressSettings addressSettings = new AddressSettings();
+      AddressSettings addressSettingsToMerge = new AddressSettings();
+      SimpleString DLQ = new SimpleString("testDLQ");
+      SimpleString exp = new SimpleString("testExpiryQueue");
+      addressSettingsToMerge.setDeadLetterAddress(DLQ);
+      addressSettingsToMerge.setExpiryAddress(exp);
+      addressSettingsToMerge.setMaxDeliveryAttempts(1000);
+      addressSettingsToMerge.setAddressFullMessagePolicy(AddressFullMessagePolicy.DROP);
+      addressSettingsToMerge.setMaxSizeBytes(1001);
+      addressSettingsToMerge.setMessageCounterHistoryDayLimit(1002);
+      addressSettingsToMerge.setRedeliveryDelay(1003);
+      addressSettingsToMerge.setPageSizeBytes(1004);
+      addressSettings.merge(addressSettingsToMerge);
+      Assert.assertEquals(addressSettings.getDeadLetterAddress(), DLQ);
+      Assert.assertEquals(addressSettings.getExpiryAddress(), exp);
+      Assert.assertEquals(addressSettings.getMaxDeliveryAttempts(), 1000);
+      Assert.assertEquals(addressSettings.getMaxSizeBytes(), 1001);
+      Assert.assertEquals(addressSettings.getMessageCounterHistoryDayLimit(), 1002);
+      Assert.assertEquals(addressSettings.getRedeliveryDelay(), 1003);
+      Assert.assertEquals(addressSettings.getPageSizeBytes(), 1004);
+      Assert.assertEquals(AddressFullMessagePolicy.DROP, addressSettings.getAddressFullMessagePolicy());
+   }
+
+   @Test
+   public void testMultipleMerge()
+   {
+      AddressSettings addressSettings = new AddressSettings();
+      AddressSettings addressSettingsToMerge = new AddressSettings();
+      SimpleString DLQ = new SimpleString("testDLQ");
+      SimpleString exp = new SimpleString("testExpiryQueue");
+      addressSettingsToMerge.setDeadLetterAddress(DLQ);
+      addressSettingsToMerge.setExpiryAddress(exp);
+      addressSettingsToMerge.setMaxDeliveryAttempts(1000);
+      addressSettingsToMerge.setMaxSizeBytes(1001);
+      addressSettingsToMerge.setMessageCounterHistoryDayLimit(1002);
+      addressSettingsToMerge.setAddressFullMessagePolicy(AddressFullMessagePolicy.DROP);
+      addressSettings.merge(addressSettingsToMerge);
+
+      AddressSettings addressSettingsToMerge2 = new AddressSettings();
+      SimpleString exp2 = new SimpleString("testExpiryQueue2");
+      addressSettingsToMerge2.setExpiryAddress(exp2);
+      addressSettingsToMerge2.setMaxSizeBytes(2001);
+      addressSettingsToMerge2.setRedeliveryDelay(2003);
+      addressSettingsToMerge2.setRedeliveryMultiplier(2.5);
+      addressSettings.merge(addressSettingsToMerge2);
+
+      Assert.assertEquals(addressSettings.getDeadLetterAddress(), DLQ);
+      Assert.assertEquals(addressSettings.getExpiryAddress(), exp);
+      Assert.assertEquals(addressSettings.getMaxDeliveryAttempts(), 1000);
+      Assert.assertEquals(addressSettings.getMaxSizeBytes(), 1001);
+      Assert.assertEquals(addressSettings.getMessageCounterHistoryDayLimit(), 1002);
+      Assert.assertEquals(addressSettings.getRedeliveryDelay(), 2003);
+      Assert.assertEquals(addressSettings.getRedeliveryMultiplier(), 2.5, 0.000001);
+      Assert.assertEquals(AddressFullMessagePolicy.DROP, addressSettings.getAddressFullMessagePolicy());
+   }
+
+   @Test
+   public void testMultipleMergeAll()
+   {
+      AddressSettings addressSettings = new AddressSettings();
+      AddressSettings addressSettingsToMerge = new AddressSettings();
+      SimpleString DLQ = new SimpleString("testDLQ");
+      SimpleString exp = new SimpleString("testExpiryQueue");
+      addressSettingsToMerge.setDeadLetterAddress(DLQ);
+      addressSettingsToMerge.setExpiryAddress(exp);
+      addressSettingsToMerge.setMaxSizeBytes(1001);
+      addressSettingsToMerge.setRedeliveryDelay(1003);
+      addressSettingsToMerge.setRedeliveryMultiplier(1.0);
+      addressSettingsToMerge.setAddressFullMessagePolicy(AddressFullMessagePolicy.DROP);
+      addressSettings.merge(addressSettingsToMerge);
+
+      AddressSettings addressSettingsToMerge2 = new AddressSettings();
+      SimpleString exp2 = new SimpleString("testExpiryQueue2");
+      SimpleString DLQ2 = new SimpleString("testDlq2");
+      addressSettingsToMerge2.setExpiryAddress(exp2);
+      addressSettingsToMerge2.setDeadLetterAddress(DLQ2);
+      addressSettingsToMerge2.setMaxDeliveryAttempts(2000);
+      addressSettingsToMerge2.setMaxSizeBytes(2001);
+      addressSettingsToMerge2.setMessageCounterHistoryDayLimit(2002);
+      addressSettingsToMerge2.setRedeliveryDelay(2003);
+      addressSettingsToMerge2.setRedeliveryMultiplier(2.0);
+      addressSettingsToMerge2.setMaxRedeliveryDelay(5000);
+      addressSettingsToMerge.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE);
+      addressSettings.merge(addressSettingsToMerge2);
+
+      Assert.assertEquals(addressSettings.getDeadLetterAddress(), DLQ);
+      Assert.assertEquals(addressSettings.getExpiryAddress(), exp);
+      Assert.assertEquals(addressSettings.getMaxDeliveryAttempts(), 2000);
+      Assert.assertEquals(addressSettings.getMaxSizeBytes(), 1001);
+      Assert.assertEquals(addressSettings.getMessageCounterHistoryDayLimit(), 2002);
+      Assert.assertEquals(addressSettings.getRedeliveryDelay(), 1003);
+      Assert.assertEquals(addressSettings.getRedeliveryMultiplier(), 1.0, 0.000001);
+      Assert.assertEquals(addressSettings.getMaxRedeliveryDelay(), 5000);
+      Assert.assertEquals(AddressFullMessagePolicy.DROP, addressSettings.getAddressFullMessagePolicy());
+   }
+}


[27/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-selector/src/main/java/org/hornetq/selector/filter/BinaryExpression.java
----------------------------------------------------------------------
diff --git a/hornetq-selector/src/main/java/org/hornetq/selector/filter/BinaryExpression.java b/hornetq-selector/src/main/java/org/hornetq/selector/filter/BinaryExpression.java
index 8e700a4..476090e 100755
--- a/hornetq-selector/src/main/java/org/hornetq/selector/filter/BinaryExpression.java
+++ b/hornetq-selector/src/main/java/org/hornetq/selector/filter/BinaryExpression.java
@@ -53,29 +53,49 @@ public abstract class BinaryExpression implements Expression
    }
 
    /**
-    * TODO: more efficient hashCode()
-    *
     * @see java.lang.Object#hashCode()
     */
    public int hashCode()
    {
-      return toString().hashCode();
+      int result = left.hashCode();
+      result = 31 * result + right.hashCode();
+      result = 31 * result + getExpressionSymbol().hashCode();
+      return result;
    }
 
    /**
-    * TODO: more efficient hashCode()
-    *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object o)
    {
+      if (this == o)
+      {
+         return true;
+      }
+
+      if (o == null || getClass() != o.getClass())
+      {
+         return false;
+      }
+
+      final BinaryExpression that = (BinaryExpression)o;
+
+      if (!this.getExpressionSymbol().equals(that.getExpressionSymbol()))
+      {
+         return false;
+      }
+
+      if (left != null && !left.equals(that.left))
+      {
+         return false;
+      }
 
-      if (o == null || !this.getClass().equals(o.getClass()))
+      if (right != null && !right.equals(that.right))
       {
          return false;
       }
-      return toString().equals(o.toString());
 
+      return true;
    }
 
    /**

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-selector/src/main/java/org/hornetq/selector/filter/ConstantExpression.java
----------------------------------------------------------------------
diff --git a/hornetq-selector/src/main/java/org/hornetq/selector/filter/ConstantExpression.java b/hornetq-selector/src/main/java/org/hornetq/selector/filter/ConstantExpression.java
index 2f4f878..4e50967 100755
--- a/hornetq-selector/src/main/java/org/hornetq/selector/filter/ConstantExpression.java
+++ b/hornetq-selector/src/main/java/org/hornetq/selector/filter/ConstantExpression.java
@@ -139,36 +139,39 @@ public class ConstantExpression implements Expression
    }
 
    /**
-    * TODO: more efficient hashCode()
-    *
     * @see java.lang.Object#hashCode()
     */
    public int hashCode()
    {
-      return toString().hashCode();
+      return value != null ? value.hashCode() : 0;
    }
 
    /**
-    * TODO: more efficient hashCode()
-    *
-    * @see java.lang.Object#equals(java.lang.Object)
+    * @see java.lang.Object#equals(Object)
     */
-   public boolean equals(Object o)
+   public boolean equals(final Object o)
    {
-
-      if (o == null || !this.getClass().equals(o.getClass()))
+      if (this == o)
+      {
+         return true;
+      }
+      if (o == null || getClass() != o.getClass())
       {
          return false;
       }
-      return toString().equals(o.toString());
-
+      final ConstantExpression that = (ConstantExpression)o;
+      if (value != null && !value.equals(that.value))
+      {
+         return false;
+      }
+      return true;
    }
 
    /**
     * Encodes the value of string so that it looks like it would look like when
     * it was provided in a selector.
     *
-    * @param string
+    * @param s
     * @return
     */
    public static String encodeString(String s)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-selector/src/main/java/org/hornetq/selector/filter/UnaryExpression.java
----------------------------------------------------------------------
diff --git a/hornetq-selector/src/main/java/org/hornetq/selector/filter/UnaryExpression.java b/hornetq-selector/src/main/java/org/hornetq/selector/filter/UnaryExpression.java
index ca55b64..ee77595 100755
--- a/hornetq-selector/src/main/java/org/hornetq/selector/filter/UnaryExpression.java
+++ b/hornetq-selector/src/main/java/org/hornetq/selector/filter/UnaryExpression.java
@@ -284,29 +284,43 @@ public abstract class UnaryExpression implements Expression
    }
 
    /**
-    * TODO: more efficient hashCode()
-    *
     * @see java.lang.Object#hashCode()
     */
    public int hashCode()
    {
-      return toString().hashCode();
+      int result = right.hashCode();
+      result = 31 * result + getExpressionSymbol().hashCode();
+      return result;
    }
 
    /**
-    * TODO: more efficient hashCode()
-    *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object o)
    {
+      if (this == o)
+      {
+         return true;
+      }
+
+      if (o == null || getClass() != o.getClass())
+      {
+         return false;
+      }
+
+      final BinaryExpression that = (BinaryExpression)o;
+
+      if (!this.getExpressionSymbol().equals(that.getExpressionSymbol()))
+      {
+         return false;
+      }
 
-      if (o == null || !this.getClass().equals(o.getClass()))
+      if (right != null && !right.equals(that.right))
       {
          return false;
       }
-      return toString().equals(o.toString());
 
+      return true;
    }
 
    /**

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-selector/src/test/java/org/hornetq/selector/SelectorParserTest.java
----------------------------------------------------------------------
diff --git a/hornetq-selector/src/test/java/org/hornetq/selector/SelectorParserTest.java b/hornetq-selector/src/test/java/org/hornetq/selector/SelectorParserTest.java
index f42a2cc..1dda085 100755
--- a/hornetq-selector/src/test/java/org/hornetq/selector/SelectorParserTest.java
+++ b/hornetq-selector/src/test/java/org/hornetq/selector/SelectorParserTest.java
@@ -16,19 +16,19 @@
  */
 package org.hornetq.selector;
 
-import junit.framework.TestCase;
-
 import org.hornetq.selector.filter.BooleanExpression;
 import org.hornetq.selector.filter.ComparisonExpression;
 import org.hornetq.selector.filter.Expression;
 import org.hornetq.selector.filter.LogicExpression;
 import org.hornetq.selector.filter.PropertyExpression;
 import org.hornetq.selector.filter.XPathExpression;
+import org.junit.Assert;
+import org.junit.Test;
 
 /**
  * @version $Revision: 1.2 $
  */
-public class SelectorParserTest extends TestCase
+public class SelectorParserTest
 {
 
    public void info(String msg)
@@ -36,13 +36,15 @@ public class SelectorParserTest extends TestCase
       System.out.println(msg);
    }
 
+   @Test
    public void testParseXPath() throws Exception
    {
       BooleanExpression filter = parse("XPATH '//title[@lang=''eng'']'");
-      assertTrue("Created XPath expression", filter instanceof XPathExpression);
+      Assert.assertTrue("Created XPath expression", filter instanceof XPathExpression);
       info("Expression: " + filter);
    }
 
+   @Test
    public void testParseWithParensAround() throws Exception
    {
       String[] values = {"x = 1 and y = 2", "(x = 1) and (y = 2)", "((x = 1) and (y = 2))"};
@@ -53,13 +55,13 @@ public class SelectorParserTest extends TestCase
          info("Parsing: " + value);
 
          BooleanExpression andExpression = parse(value);
-         assertTrue("Created LogicExpression expression", andExpression instanceof LogicExpression);
+         Assert.assertTrue("Created LogicExpression expression", andExpression instanceof LogicExpression);
          LogicExpression logicExpression = (LogicExpression) andExpression;
          Expression left = logicExpression.getLeft();
          Expression right = logicExpression.getRight();
 
-         assertTrue("Left is a binary filter", left instanceof ComparisonExpression);
-         assertTrue("Right is a binary filter", right instanceof ComparisonExpression);
+         Assert.assertTrue("Left is a binary filter", left instanceof ComparisonExpression);
+         Assert.assertTrue("Right is a binary filter", right instanceof ComparisonExpression);
          ComparisonExpression leftCompare = (ComparisonExpression) left;
          ComparisonExpression rightCompare = (ComparisonExpression) right;
          assertPropertyExpression("left", leftCompare.getLeft(), "x");
@@ -69,9 +71,9 @@ public class SelectorParserTest extends TestCase
 
    protected void assertPropertyExpression(String message, Expression expression, String expected)
    {
-      assertTrue(message + ". Must be PropertyExpression", expression instanceof PropertyExpression);
+      Assert.assertTrue(message + ". Must be PropertyExpression", expression instanceof PropertyExpression);
       PropertyExpression propExp = (PropertyExpression) expression;
-      assertEquals(message + ". Property name", expected, propExp.getName());
+      Assert.assertEquals(message + ". Property name", expected, propExp.getName());
    }
 
    protected BooleanExpression parse(String text) throws Exception

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-selector/src/test/java/org/hornetq/selector/SelectorTest.java
----------------------------------------------------------------------
diff --git a/hornetq-selector/src/test/java/org/hornetq/selector/SelectorTest.java b/hornetq-selector/src/test/java/org/hornetq/selector/SelectorTest.java
index 91df373..67c59e6 100755
--- a/hornetq-selector/src/test/java/org/hornetq/selector/SelectorTest.java
+++ b/hornetq-selector/src/test/java/org/hornetq/selector/SelectorTest.java
@@ -18,17 +18,17 @@ package org.hornetq.selector;
 
 import java.util.HashMap;
 
-import junit.framework.TestCase;
-
 import org.hornetq.selector.filter.BooleanExpression;
 import org.hornetq.selector.filter.FilterException;
 import org.hornetq.selector.filter.Filterable;
+import org.junit.Assert;
+import org.junit.Test;
 
 /**
  * @version $Revision: 1.7 $
  */
 @SuppressWarnings("unchecked")
-public class SelectorTest extends TestCase
+public class SelectorTest
 {
 
    class MockMessage implements Filterable
@@ -142,6 +142,7 @@ public class SelectorTest extends TestCase
    }
 
 
+   @Test
    public void testBooleanSelector() throws Exception
    {
       MockMessage message = createMessage();
@@ -151,6 +152,7 @@ public class SelectorTest extends TestCase
 
    }
 
+   @Test
    public void testXPathSelectors() throws Exception
    {
       MockMessage message = new MockMessage();
@@ -194,6 +196,7 @@ public class SelectorTest extends TestCase
 
    }
 
+   @Test
    public void testJMSPropertySelectors() throws Exception
    {
       MockMessage message = createMessage();
@@ -214,6 +217,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "JMSType = 'crap'", false);
    }
 
+   @Test
    public void testBasicSelectors() throws Exception
    {
       MockMessage message = createMessage();
@@ -225,6 +229,7 @@ public class SelectorTest extends TestCase
 
    }
 
+   @Test
    public void testPropertyTypes() throws Exception
    {
       MockMessage message = createMessage();
@@ -252,6 +257,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "doubleProp = 10", false);
    }
 
+   @Test
    public void testAndSelectors() throws Exception
    {
       MockMessage message = createMessage();
@@ -262,6 +268,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "unknown = 'Foo' and anotherUnknown < 200", false);
    }
 
+   @Test
    public void testOrSelectors() throws Exception
    {
       MockMessage message = createMessage();
@@ -273,6 +280,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "unknown = 'Foo' or anotherUnknown < 200", false);
    }
 
+   @Test
    public void testPlus() throws Exception
    {
       MockMessage message = createMessage();
@@ -285,6 +293,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "name + '!' = 'James!'", true);
    }
 
+   @Test
    public void testMinus() throws Exception
    {
       MockMessage message = createMessage();
@@ -294,6 +303,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "rank - 2 > 122", false);
    }
 
+   @Test
    public void testMultiply() throws Exception
    {
       MockMessage message = createMessage();
@@ -303,6 +313,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "rank * 2 < 130", false);
    }
 
+   @Test
    public void testDivide() throws Exception
    {
       MockMessage message = createMessage();
@@ -314,6 +325,7 @@ public class SelectorTest extends TestCase
 
    }
 
+   @Test
    public void testBetween() throws Exception
    {
       MockMessage message = createMessage();
@@ -322,6 +334,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "rank between 10 and 120", false);
    }
 
+   @Test
    public void testIn() throws Exception
    {
       MockMessage message = createMessage();
@@ -334,6 +347,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "name not in ('Gromit', 'Bob', 'Cheddar')", true);
    }
 
+   @Test
    public void testIsNull() throws Exception
    {
       MockMessage message = createMessage();
@@ -344,6 +358,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "name is null", false);
    }
 
+   @Test
    public void testLike() throws Exception
    {
       MockMessage message = createMessage();
@@ -372,6 +387,7 @@ public class SelectorTest extends TestCase
    /**
     * Test cases from Mats Henricson
     */
+   @Test
    public void testMatsHenricsonUseCases() throws Exception
    {
       MockMessage message = createMessage();
@@ -394,6 +410,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "Command NOT IN ('MirrorLobbyRequest', 'MirrorLobbyReply')", false);
    }
 
+   @Test
    public void testFloatComparisons() throws Exception
    {
       MockMessage message = createMessage();
@@ -444,12 +461,14 @@ public class SelectorTest extends TestCase
       assertSelector(message, "4E-10 < 5E-10", true);
    }
 
+   @Test
    public void testStringQuoteParsing() throws Exception
    {
       MockMessage message = createMessage();
       assertSelector(message, "quote = '''In God We Trust'''", true);
    }
 
+   @Test
    public void testLikeComparisons() throws Exception
    {
       MockMessage message = createMessage();
@@ -472,6 +491,7 @@ public class SelectorTest extends TestCase
       assertSelector(message, "punctuation LIKE '!#$&()*+,-./:;<=>?@[\\]^`{|}~'", true);
    }
 
+   @Test
    public void testInvalidSelector() throws Exception
    {
       MockMessage message = createMessage();
@@ -511,7 +531,7 @@ public class SelectorTest extends TestCase
       try
       {
          SelectorParser.parse(text);
-         fail("Created a valid selector");
+         Assert.fail("Created a valid selector");
       }
       catch (FilterException e)
       {
@@ -521,9 +541,9 @@ public class SelectorTest extends TestCase
    protected void assertSelector(MockMessage message, String text, boolean expected) throws FilterException
    {
       BooleanExpression selector = SelectorParser.parse(text);
-      assertTrue("Created a valid selector", selector != null);
+      Assert.assertTrue("Created a valid selector", selector != null);
       boolean value = selector.matches(message);
-      assertEquals("Selector for: " + text, expected, value);
+      Assert.assertEquals("Selector for: " + text, expected, value);
    }
 
    protected MockMessage createMessage(String subject)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-server/pom.xml b/hornetq-server/pom.xml
index 94adc63..7695bde 100644
--- a/hornetq-server/pom.xml
+++ b/hornetq-server/pom.xml
@@ -35,11 +35,6 @@
         <scope>test</scope>
       </dependency>
       <dependency>
-         <groupId>org.jboss.logmanager</groupId>
-         <artifactId>jboss-logmanager</artifactId>
-         <scope>test</scope>
-      </dependency>
-      <dependency>
          <groupId>org.hornetq</groupId>
          <artifactId>hornetq-commons</artifactId>
          <version>${project.version}</version>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/BridgeConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/BridgeConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/BridgeConfiguration.java
index 6d56039..70a18b3 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/BridgeConfiguration.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/BridgeConfiguration.java
@@ -15,6 +15,7 @@ package org.hornetq.core.config;
 import java.io.Serializable;
 import java.util.List;
 
+import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.client.HornetQClient;
 
 /**
@@ -25,17 +26,17 @@ public final class BridgeConfiguration implements Serializable
 {
    private static final long serialVersionUID = -1057244274380572226L;
 
-   private String name;
+   private String name = null;
 
-   private String queueName;
+   private String queueName = null;
 
-   private String forwardingAddress;
+   private String forwardingAddress = null;
 
-   private String filterString;
+   private String filterString = null;
 
-   private List<String> staticConnectors;
+   private List<String> staticConnectors = null;
 
-   private String discoveryGroupName;
+   private String discoveryGroupName = null;
 
    private boolean ha = false;
 
@@ -43,23 +44,23 @@ public final class BridgeConfiguration implements Serializable
 
    private long retryInterval = HornetQClient.DEFAULT_RETRY_INTERVAL;
 
-   private double retryIntervalMultiplier = HornetQClient.DEFAULT_RETRY_INTERVAL;
+   private double retryIntervalMultiplier = HornetQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER;
 
-   private int initialConnectAttempts = -1;
+   private int initialConnectAttempts = HornetQDefaultConfiguration.getDefaultBridgeInitialConnectAttempts();
 
-   private int reconnectAttempts = -1;
+   private int reconnectAttempts = HornetQDefaultConfiguration.getDefaultBridgeReconnectAttempts();
 
-   private int reconnectAttemptsOnSameNode = 10;
+   private int reconnectAttemptsOnSameNode = HornetQDefaultConfiguration.getDefaultBridgeConnectSameNode();
 
-   private boolean useDuplicateDetection = true;
+   private boolean useDuplicateDetection = HornetQDefaultConfiguration.isDefaultBridgeDuplicateDetection();
 
    private int confirmationWindowSize = HornetQClient.DEFAULT_CONFIRMATION_WINDOW_SIZE;
 
    private long clientFailureCheckPeriod = HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD;
 
-   private String user;
+   private String user = HornetQDefaultConfiguration.getDefaultClusterUser();
 
-   private String password;
+   private String password = HornetQDefaultConfiguration.getDefaultClusterPassword();
 
    private long connectionTTL = HornetQClient.DEFAULT_CONNECTION_TTL;
 
@@ -72,101 +73,10 @@ public final class BridgeConfiguration implements Serializable
    private long callTimeout = HornetQClient.DEFAULT_CALL_TIMEOUT;
 
 
-   /**
-    * A default constructor for embedded users or testcases to setup defaults
-    */
    public BridgeConfiguration()
    {
    }
 
-   public BridgeConfiguration(final String name,
-                              final String queueName,
-                              final String forwardingAddress,
-                              final String filterString,
-                              final String transformerClassName,
-                              final int minLargeMessageSize,
-                              final long clientFailureCheckPeriod,
-                              final long connectionTTL,
-                              final long retryInterval,
-                              final long maxRetryInterval,
-                              final double retryIntervalMultiplier,
-                              final int initialConnectAttempts,
-                              final int reconnectAttempts,
-                              final int reconnectAttemptsOnSameNode,
-                              final boolean useDuplicateDetection,
-                              final int confirmationWindowSize,
-                              final List<String> staticConnectors,
-                              final boolean ha,
-                              final String user,
-                              final String password)
-   {
-      this.name = name;
-      this.queueName = queueName;
-      this.forwardingAddress = forwardingAddress;
-      this.minLargeMessageSize = minLargeMessageSize;
-      this.filterString = filterString;
-      this.transformerClassName = transformerClassName;
-      this.retryInterval = retryInterval;
-      this.retryIntervalMultiplier = retryIntervalMultiplier;
-      this.initialConnectAttempts = initialConnectAttempts;
-      this.reconnectAttempts = reconnectAttempts;
-      this.reconnectAttemptsOnSameNode = reconnectAttemptsOnSameNode;
-      this.useDuplicateDetection = useDuplicateDetection;
-      this.confirmationWindowSize = confirmationWindowSize;
-      this.clientFailureCheckPeriod = clientFailureCheckPeriod;
-      this.staticConnectors = staticConnectors;
-      this.user = user;
-      this.password = password;
-      this.connectionTTL = connectionTTL;
-      this.maxRetryInterval = maxRetryInterval;
-      this.ha = ha;
-      discoveryGroupName = null;
-   }
-
-   public BridgeConfiguration(final String name,
-                              final String queueName,
-                              final String forwardingAddress,
-                              final String filterString,
-                              final String transformerClassName,
-                              final int minLargeMessageSize,
-                              final long clientFailureCheckPeriod,
-                              final long connectionTTL,
-                              final long retryInterval,
-                              final long maxRetryInterval,
-                              final double retryIntervalMultiplier,
-                              final int initialConnectAttempts,
-                              final int reconnectAttempts,
-                              final int reconnectAttemptsOnSameNode,
-                              final boolean useDuplicateDetection,
-                              final int confirmationWindowSize,
-                              final String discoveryGroupName,
-                              final boolean ha,
-                              final String user,
-                              final String password)
-   {
-      this.name = name;
-      this.queueName = queueName;
-      this.forwardingAddress = forwardingAddress;
-      this.filterString = filterString;
-      this.transformerClassName = transformerClassName;
-      this.minLargeMessageSize = minLargeMessageSize;
-      this.retryInterval = retryInterval;
-      this.retryIntervalMultiplier = retryIntervalMultiplier;
-      this.initialConnectAttempts = initialConnectAttempts;
-      this.reconnectAttempts = reconnectAttempts;
-      this.reconnectAttemptsOnSameNode = reconnectAttemptsOnSameNode;
-      this.useDuplicateDetection = useDuplicateDetection;
-      this.confirmationWindowSize = confirmationWindowSize;
-      this.clientFailureCheckPeriod = clientFailureCheckPeriod;
-      this.staticConnectors = null;
-      this.discoveryGroupName = discoveryGroupName;
-      this.ha = ha;
-      this.user = user;
-      this.password = password;
-      this.connectionTTL = connectionTTL;
-      this.maxRetryInterval = maxRetryInterval;
-   }
-
    public String getName()
    {
       return name;
@@ -175,9 +85,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param name the name to set
     */
-   public void setName(final String name)
+   public BridgeConfiguration setName(final String name)
    {
       this.name = name;
+      return this;
    }
 
    public String getQueueName()
@@ -188,9 +99,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param queueName the queueName to set
     */
-   public void setQueueName(final String queueName)
+   public BridgeConfiguration setQueueName(final String queueName)
    {
       this.queueName = queueName;
+      return this;
    }
 
    /**
@@ -201,9 +113,10 @@ public final class BridgeConfiguration implements Serializable
       return connectionTTL;
    }
 
-   public void setConnectionTTL(long connectionTTL)
+   public BridgeConfiguration setConnectionTTL(long connectionTTL)
    {
       this.connectionTTL = connectionTTL;
+      return this;
    }
 
    /**
@@ -214,9 +127,10 @@ public final class BridgeConfiguration implements Serializable
       return maxRetryInterval;
    }
 
-   public void setMaxRetryInterval(long maxRetryInterval)
+   public BridgeConfiguration setMaxRetryInterval(long maxRetryInterval)
    {
       this.maxRetryInterval = maxRetryInterval;
+      return this;
    }
 
    public String getForwardingAddress()
@@ -227,9 +141,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param forwardingAddress the forwardingAddress to set
     */
-   public void setForwardingAddress(final String forwardingAddress)
+   public BridgeConfiguration setForwardingAddress(final String forwardingAddress)
    {
       this.forwardingAddress = forwardingAddress;
+      return this;
    }
 
    public String getFilterString()
@@ -240,9 +155,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param filterString the filterString to set
     */
-   public void setFilterString(final String filterString)
+   public BridgeConfiguration setFilterString(final String filterString)
    {
       this.filterString = filterString;
+      return this;
    }
 
    public String getTransformerClassName()
@@ -253,9 +169,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param transformerClassName the transformerClassName to set
     */
-   public void setTransformerClassName(final String transformerClassName)
+   public BridgeConfiguration setTransformerClassName(final String transformerClassName)
    {
       this.transformerClassName = transformerClassName;
+      return this;
    }
 
    public List<String> getStaticConnectors()
@@ -266,9 +183,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param staticConnectors the staticConnectors to set
     */
-   public void setStaticConnectors(final List<String> staticConnectors)
+   public BridgeConfiguration setStaticConnectors(final List<String> staticConnectors)
    {
       this.staticConnectors = staticConnectors;
+      return this;
    }
 
    public String getDiscoveryGroupName()
@@ -279,9 +197,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param discoveryGroupName the discoveryGroupName to set
     */
-   public void setDiscoveryGroupName(final String discoveryGroupName)
+   public BridgeConfiguration setDiscoveryGroupName(final String discoveryGroupName)
    {
       this.discoveryGroupName = discoveryGroupName;
+      return this;
    }
 
    public boolean isHA()
@@ -293,9 +212,10 @@ public final class BridgeConfiguration implements Serializable
     *
     * @param ha is the bridge supporting HA?
     */
-   public void setHA(final boolean ha)
+   public BridgeConfiguration setHA(final boolean ha)
    {
       this.ha = ha;
+      return this;
    }
 
    public long getRetryInterval()
@@ -306,9 +226,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param retryInterval the retryInterval to set
     */
-   public void setRetryInterval(final long retryInterval)
+   public BridgeConfiguration setRetryInterval(final long retryInterval)
    {
       this.retryInterval = retryInterval;
+      return this;
    }
 
    public double getRetryIntervalMultiplier()
@@ -319,9 +240,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param retryIntervalMultiplier the retryIntervalMultiplier to set
     */
-   public void setRetryIntervalMultiplier(final double retryIntervalMultiplier)
+   public BridgeConfiguration setRetryIntervalMultiplier(final double retryIntervalMultiplier)
    {
       this.retryIntervalMultiplier = retryIntervalMultiplier;
+      return this;
    }
 
    public int getInitialConnectAttempts()
@@ -332,9 +254,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param initialConnectAttempts the initialConnectAttempts to set
     */
-   public void setInitialConnectAttempts(final int initialConnectAttempts)
+   public BridgeConfiguration setInitialConnectAttempts(final int initialConnectAttempts)
    {
       this.initialConnectAttempts = initialConnectAttempts;
+      return this;
    }
 
    public int getReconnectAttempts()
@@ -345,9 +268,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param reconnectAttempts the reconnectAttempts to set
     */
-   public void setReconnectAttempts(final int reconnectAttempts)
+   public BridgeConfiguration setReconnectAttempts(final int reconnectAttempts)
    {
       this.reconnectAttempts = reconnectAttempts;
+      return this;
    }
 
    public boolean isUseDuplicateDetection()
@@ -358,9 +282,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param useDuplicateDetection the useDuplicateDetection to set
     */
-   public void setUseDuplicateDetection(final boolean useDuplicateDetection)
+   public BridgeConfiguration setUseDuplicateDetection(final boolean useDuplicateDetection)
    {
       this.useDuplicateDetection = useDuplicateDetection;
+      return this;
    }
 
    public int getConfirmationWindowSize()
@@ -371,9 +296,10 @@ public final class BridgeConfiguration implements Serializable
    /**
     * @param confirmationWindowSize the confirmationWindowSize to set
     */
-   public void setConfirmationWindowSize(final int confirmationWindowSize)
+   public BridgeConfiguration setConfirmationWindowSize(final int confirmationWindowSize)
    {
       this.confirmationWindowSize = confirmationWindowSize;
+      return this;
    }
 
    public long getClientFailureCheckPeriod()
@@ -381,9 +307,10 @@ public final class BridgeConfiguration implements Serializable
       return clientFailureCheckPeriod;
    }
 
-   public void setClientFailureCheckPeriod(long clientFailureCheckPeriod)
+   public BridgeConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod)
    {
       this.clientFailureCheckPeriod = clientFailureCheckPeriod;
+      return this;
    }
 
    /**
@@ -394,9 +321,10 @@ public final class BridgeConfiguration implements Serializable
       return minLargeMessageSize;
    }
 
-   public void setMinLargeMessageSize(int minLargeMessageSize)
+   public BridgeConfiguration setMinLargeMessageSize(int minLargeMessageSize)
    {
       this.minLargeMessageSize = minLargeMessageSize;
+      return this;
    }
 
    public String getUser()
@@ -404,9 +332,10 @@ public final class BridgeConfiguration implements Serializable
       return user;
    }
 
-   public void setUser(String user)
+   public BridgeConfiguration setUser(String user)
    {
       this.user = user;
+      return this;
    }
 
    public String getPassword()
@@ -414,9 +343,10 @@ public final class BridgeConfiguration implements Serializable
       return password;
    }
 
-   public void setPassword(String password)
+   public BridgeConfiguration setPassword(String password)
    {
       this.password = password;
+      return this;
    }
 
    /**
@@ -432,9 +362,10 @@ public final class BridgeConfiguration implements Serializable
       return reconnectAttemptsOnSameNode;
    }
 
-   public void setReconnectAttemptsOnSameNode(int reconnectAttemptsOnSameNode)
+   public BridgeConfiguration setReconnectAttemptsOnSameNode(int reconnectAttemptsOnSameNode)
    {
       this.reconnectAttemptsOnSameNode = reconnectAttemptsOnSameNode;
+      return this;
    }
 
    /**
@@ -443,9 +374,10 @@ public final class BridgeConfiguration implements Serializable
     * The bridge shouldn't be sending blocking anyways
     * @param callTimeout the callTimeout to set
     */
-   public void setCallTimeout(long callTimeout)
+   public BridgeConfiguration setCallTimeout(long callTimeout)
    {
       this.callTimeout = callTimeout;
+      return this;
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/ClusterConnectionConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/ClusterConnectionConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/config/ClusterConnectionConfiguration.java
index 8cdeab8..e3ea8ee 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/ClusterConnectionConfiguration.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/ClusterConnectionConfiguration.java
@@ -18,7 +18,6 @@ import java.util.List;
 
 import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.core.server.HornetQMessageBundle;
 
 /**
  * A ClusterConnectionConfiguration
@@ -29,231 +28,74 @@ public final class ClusterConnectionConfiguration implements Serializable
 {
    private static final long serialVersionUID = 8948303813427795935L;
 
-   private final String name;
+   private String name;
 
-   private final String address;
+   private String address;
 
-   private final String connectorName;
+   private String connectorName;
 
-   private long clientFailureCheckPeriod;
+   private long clientFailureCheckPeriod = HornetQDefaultConfiguration.getDefaultClusterFailureCheckPeriod();
 
-   private long connectionTTL;
+   private long connectionTTL = HornetQDefaultConfiguration.getDefaultClusterConnectionTtl();
 
-   private long retryInterval;
+   private long retryInterval = HornetQDefaultConfiguration.getDefaultClusterRetryInterval();
 
-   private double retryIntervalMultiplier;
+   private double retryIntervalMultiplier = HornetQDefaultConfiguration.getDefaultClusterRetryIntervalMultiplier();
 
-   private long maxRetryInterval;
+   private long maxRetryInterval = HornetQDefaultConfiguration.getDefaultClusterMaxRetryInterval();
 
-   private int initialConnectAttempts;
+   private int initialConnectAttempts = HornetQDefaultConfiguration.getDefaultClusterInitialConnectAttempts();
 
-   private int reconnectAttempts;
+   private int reconnectAttempts = HornetQDefaultConfiguration.getDefaultClusterReconnectAttempts();
 
-   private long callTimeout;
+   private long callTimeout = HornetQDefaultConfiguration.getDefaultClusterCallTimeout();
 
-   private long callFailoverTimeout;
+   private long callFailoverTimeout = HornetQDefaultConfiguration.getDefaultClusterCallFailoverTimeout();
 
-   private boolean duplicateDetection;
+   private boolean duplicateDetection = HornetQDefaultConfiguration.isDefaultClusterDuplicateDetection();
 
-   private boolean forwardWhenNoConsumers;
+   private boolean forwardWhenNoConsumers = HornetQDefaultConfiguration.isDefaultClusterForwardWhenNoConsumers();
 
-   private final List<String> staticConnectors;
+   private List<String> staticConnectors = Collections.emptyList();
 
-   private final String discoveryGroupName;
+   private String discoveryGroupName = null;
 
-   private final int maxHops;
+   private int maxHops = HornetQDefaultConfiguration.getDefaultClusterMaxHops();
 
-   private final int confirmationWindowSize;
+   private int confirmationWindowSize = HornetQDefaultConfiguration.getDefaultClusterConfirmationWindowSize();
 
-   private final boolean allowDirectConnectionsOnly;
+   private boolean allowDirectConnectionsOnly = false;
 
-   private int minLargeMessageSize;
+   private int minLargeMessageSize = HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
 
-   private final long clusterNotificationInterval;
+   private long clusterNotificationInterval = HornetQDefaultConfiguration.getDefaultClusterNotificationInterval();
 
-   private final int clusterNotificationAttempts;
+   private int clusterNotificationAttempts = HornetQDefaultConfiguration.getDefaultClusterNotificationAttempts();
 
-   public ClusterConnectionConfiguration(final String name,
-                                         final String address,
-                                         final String connectorName,
-                                         final long retryInterval,
-                                         final boolean duplicateDetection,
-                                         final boolean forwardWhenNoConsumers,
-                                         final int maxHops,
-                                         final int confirmationWindowSize,
-                                         final List<String> staticConnectors,
-                                         final boolean allowDirectConnectionsOnly)
+   public ClusterConnectionConfiguration()
    {
-      this(name,
-         address,
-         connectorName,
-         HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-         HornetQDefaultConfiguration.getDefaultClusterFailureCheckPeriod(),
-         HornetQDefaultConfiguration.getDefaultClusterConnectionTtl(),
-         retryInterval,
-         HornetQDefaultConfiguration.getDefaultClusterRetryIntervalMultiplier(),
-         HornetQDefaultConfiguration.getDefaultClusterMaxRetryInterval(),
-         HornetQDefaultConfiguration.getDefaultClusterInitialConnectAttempts(),
-         HornetQDefaultConfiguration.getDefaultClusterReconnectAttempts(),
-         HornetQClient.DEFAULT_CALL_TIMEOUT,
-         HornetQClient.DEFAULT_CALL_FAILOVER_TIMEOUT,
-         duplicateDetection,
-         forwardWhenNoConsumers,
-         maxHops,
-         confirmationWindowSize,
-         staticConnectors,
-         allowDirectConnectionsOnly,
-         HornetQDefaultConfiguration.getDefaultClusterNotificationInterval(),
-         HornetQDefaultConfiguration.getDefaultClusterNotificationAttempts(),
-         null);
    }
 
-
-   public ClusterConnectionConfiguration(final String name,
-                                         final String address,
-                                         final String connectorName,
-                                         final int minLargeMessageSize,
-                                         final long clientFailureCheckPeriod,
-                                         final long connectionTTL,
-                                         final long retryInterval,
-                                         final double retryIntervalMultiplier,
-                                         final long maxRetryInterval,
-                                         final int initialConnectAttempts,
-                                         final int reconnectAttempts,
-                                         final long callTimeout,
-                                         final long callFailoverTimeout,
-                                         final boolean duplicateDetection,
-                                         final boolean forwardWhenNoConsumers,
-                                         final int maxHops,
-                                         final int confirmationWindowSize,
-                                         final List<String> staticConnectors,
-                                         final boolean allowDirectConnectionsOnly,
-                                         final long clusterNotificationInterval,
-                                         final int clusterNotificationAttempts,
-                                         final String scaleDownConnector)
+   public String getName()
    {
-      this.name = name;
-      this.address = address;
-      this.connectorName = connectorName;
-      this.clientFailureCheckPeriod = clientFailureCheckPeriod;
-      this.connectionTTL = connectionTTL;
-      if (retryInterval <= 0)
-         throw HornetQMessageBundle.BUNDLE.invalidRetryInterval(retryInterval);
-      this.retryInterval = retryInterval;
-      this.retryIntervalMultiplier = retryIntervalMultiplier;
-      this.maxRetryInterval = maxRetryInterval;
-      this.initialConnectAttempts = initialConnectAttempts;
-      this.reconnectAttempts = reconnectAttempts;
-      if (staticConnectors != null)
-      {
-         this.staticConnectors = staticConnectors;
-      }
-      else
-      {
-         this.staticConnectors = Collections.emptyList();
-      }
-      this.duplicateDetection = duplicateDetection;
-      this.callTimeout = callTimeout;
-      this.callFailoverTimeout = callFailoverTimeout;
-      this.forwardWhenNoConsumers = forwardWhenNoConsumers;
-      discoveryGroupName = null;
-      this.maxHops = maxHops;
-      this.confirmationWindowSize = confirmationWindowSize;
-      this.allowDirectConnectionsOnly = allowDirectConnectionsOnly;
-      this.minLargeMessageSize = minLargeMessageSize;
-      this.clusterNotificationInterval = clusterNotificationInterval;
-      this.clusterNotificationAttempts = clusterNotificationAttempts;
+      return name;
    }
 
-
-   public ClusterConnectionConfiguration(final String name,
-                                         final String address,
-                                         final String connectorName,
-                                         final long retryInterval,
-                                         final boolean duplicateDetection,
-                                         final boolean forwardWhenNoConsumers,
-                                         final int maxHops,
-                                         final int confirmationWindowSize,
-                                         final String discoveryGroupName)
-   {
-      this(name,
-         address,
-         connectorName,
-         HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-         HornetQDefaultConfiguration.getDefaultClusterFailureCheckPeriod(),
-         HornetQDefaultConfiguration.getDefaultClusterConnectionTtl(),
-         retryInterval,
-         HornetQDefaultConfiguration.getDefaultClusterRetryIntervalMultiplier(),
-         HornetQDefaultConfiguration.getDefaultClusterMaxRetryInterval(),
-         HornetQDefaultConfiguration.getDefaultClusterInitialConnectAttempts(),
-         HornetQDefaultConfiguration.getDefaultClusterReconnectAttempts(),
-         HornetQClient.DEFAULT_CALL_TIMEOUT,
-         HornetQClient.DEFAULT_CALL_FAILOVER_TIMEOUT,
-         duplicateDetection,
-         forwardWhenNoConsumers,
-         maxHops,
-         confirmationWindowSize,
-         discoveryGroupName,
-         HornetQDefaultConfiguration.getDefaultClusterNotificationInterval(),
-         HornetQDefaultConfiguration.getDefaultClusterNotificationAttempts(),
-         null);
-   }
-
-
-   public ClusterConnectionConfiguration(final String name,
-                                         final String address,
-                                         final String connectorName,
-                                         final int minLargeMessageSize,
-                                         final long clientFailureCheckPeriod,
-                                         final long connectionTTL,
-                                         final long retryInterval,
-                                         final double retryIntervalMultiplier,
-                                         final long maxRetryInterval,
-                                         final int initialConnectAttempts,
-                                         final int reconnectAttempts,
-                                         final long callTimeout,
-                                         final long callFailoverTimeout,
-                                         final boolean duplicateDetection,
-                                         final boolean forwardWhenNoConsumers,
-                                         final int maxHops,
-                                         final int confirmationWindowSize,
-                                         final String discoveryGroupName,
-                                         final long clusterNotificationInterval,
-                                         final int clusterNotificationAttempts,
-                                         final String scaleDownConnector)
+   public ClusterConnectionConfiguration setName(String name)
    {
       this.name = name;
-      this.address = address;
-      this.connectorName = connectorName;
-      this.clientFailureCheckPeriod = clientFailureCheckPeriod;
-      this.connectionTTL = connectionTTL;
-      this.retryInterval = retryInterval;
-      this.retryIntervalMultiplier = retryIntervalMultiplier;
-      this.maxRetryInterval = maxRetryInterval;
-      this.initialConnectAttempts = initialConnectAttempts;
-      this.reconnectAttempts = reconnectAttempts;
-      this.callTimeout = callTimeout;
-      this.callFailoverTimeout = callFailoverTimeout;
-      this.duplicateDetection = duplicateDetection;
-      this.forwardWhenNoConsumers = forwardWhenNoConsumers;
-      this.discoveryGroupName = discoveryGroupName;
-      this.clusterNotificationInterval = clusterNotificationInterval;
-      this.clusterNotificationAttempts = clusterNotificationAttempts;
-      this.staticConnectors = Collections.emptyList();
-      this.maxHops = maxHops;
-      this.confirmationWindowSize = confirmationWindowSize;
-      this.minLargeMessageSize = minLargeMessageSize;
-      allowDirectConnectionsOnly = false;
+      return this;
    }
 
-   public String getName()
+   public String getAddress()
    {
-      return name;
+      return address;
    }
 
-   public String getAddress()
+   public ClusterConnectionConfiguration setAddress(String address)
    {
-      return address;
+      this.address = address;
+      return this;
    }
 
    /**
@@ -319,6 +161,12 @@ public final class ClusterConnectionConfiguration implements Serializable
       return connectorName;
    }
 
+   public ClusterConnectionConfiguration setConnectorName(String connectorName)
+   {
+      this.connectorName = connectorName;
+      return this;
+   }
+
    public boolean isDuplicateDetection()
    {
       return duplicateDetection;
@@ -334,21 +182,45 @@ public final class ClusterConnectionConfiguration implements Serializable
       return maxHops;
    }
 
+   public ClusterConnectionConfiguration setMaxHops(int maxHops)
+   {
+      this.maxHops = maxHops;
+      return this;
+   }
+
    public int getConfirmationWindowSize()
    {
       return confirmationWindowSize;
    }
 
+   public ClusterConnectionConfiguration setConfirmationWindowSize(int confirmationWindowSize)
+   {
+      this.confirmationWindowSize = confirmationWindowSize;
+      return this;
+   }
+
    public List<String> getStaticConnectors()
    {
       return staticConnectors;
    }
 
+   public ClusterConnectionConfiguration setStaticConnectors(List<String> staticConnectors)
+   {
+      this.staticConnectors = staticConnectors;
+      return this;
+   }
+
    public String getDiscoveryGroupName()
    {
       return discoveryGroupName;
    }
 
+   public ClusterConnectionConfiguration setDiscoveryGroupName(String discoveryGroupName)
+   {
+      this.discoveryGroupName = discoveryGroupName;
+      return this;
+   }
+
    public long getRetryInterval()
    {
       return retryInterval;
@@ -359,6 +231,12 @@ public final class ClusterConnectionConfiguration implements Serializable
       return allowDirectConnectionsOnly;
    }
 
+   public ClusterConnectionConfiguration setAllowDirectConnectionsOnly(boolean allowDirectConnectionsOnly)
+   {
+      this.allowDirectConnectionsOnly = allowDirectConnectionsOnly;
+      return this;
+   }
+
 
    /**
     * @return the minLargeMessageSize
@@ -371,97 +249,109 @@ public final class ClusterConnectionConfiguration implements Serializable
    /**
     * @param minLargeMessageSize the minLargeMessageSize to set
     */
-   public void setMinLargeMessageSize(final int minLargeMessageSize)
+   public ClusterConnectionConfiguration setMinLargeMessageSize(final int minLargeMessageSize)
    {
       this.minLargeMessageSize = minLargeMessageSize;
+      return this;
    }
 
    /**
     * @param clientFailureCheckPeriod the clientFailureCheckPeriod to set
     */
-   public void setClientFailureCheckPeriod(long clientFailureCheckPeriod)
+   public ClusterConnectionConfiguration setClientFailureCheckPeriod(long clientFailureCheckPeriod)
    {
       this.clientFailureCheckPeriod = clientFailureCheckPeriod;
+      return this;
    }
 
    /**
     * @param connectionTTL the connectionTTL to set
     */
-   public void setConnectionTTL(long connectionTTL)
+   public ClusterConnectionConfiguration setConnectionTTL(long connectionTTL)
    {
       this.connectionTTL = connectionTTL;
+      return this;
    }
 
    /**
     * @param retryInterval the retryInterval to set
     */
-   public void setRetryInterval(long retryInterval)
+   public ClusterConnectionConfiguration setRetryInterval(long retryInterval)
    {
       this.retryInterval = retryInterval;
+      return this;
    }
 
    /**
     * @param retryIntervalMultiplier the retryIntervalMultiplier to set
     */
-   public void setRetryIntervalMultiplier(double retryIntervalMultiplier)
+   public ClusterConnectionConfiguration setRetryIntervalMultiplier(double retryIntervalMultiplier)
    {
       this.retryIntervalMultiplier = retryIntervalMultiplier;
+      return this;
    }
 
    /**
     * @param maxRetryInterval the maxRetryInterval to set
     */
-   public void setMaxRetryInterval(long maxRetryInterval)
+   public ClusterConnectionConfiguration setMaxRetryInterval(long maxRetryInterval)
    {
       this.maxRetryInterval = maxRetryInterval;
+      return this;
    }
 
    /**
     * @param initialConnectAttempts the reconnectAttempts to set
     */
-   public void setInitialConnectAttempts(int initialConnectAttempts)
+   public ClusterConnectionConfiguration setInitialConnectAttempts(int initialConnectAttempts)
    {
       this.initialConnectAttempts = initialConnectAttempts;
+      return this;
    }
 
    /**
     * @param reconnectAttempts the reconnectAttempts to set
     */
-   public void setReconnectAttempts(int reconnectAttempts)
+   public ClusterConnectionConfiguration setReconnectAttempts(int reconnectAttempts)
    {
       this.reconnectAttempts = reconnectAttempts;
+      return this;
    }
 
    /**
     * @param callTimeout the callTimeout to set
     */
-   public void setCallTimeout(long callTimeout)
+   public ClusterConnectionConfiguration setCallTimeout(long callTimeout)
    {
       this.callTimeout = callTimeout;
+      return this;
    }
 
    /**
     * @param callFailoverTimeout the callTimeout to set
     */
-   public void setCallFailoverTimeout(long callFailoverTimeout)
+   public ClusterConnectionConfiguration setCallFailoverTimeout(long callFailoverTimeout)
    {
       this.callFailoverTimeout = callFailoverTimeout;
+      return this;
    }
 
    /**
     * @param duplicateDetection the duplicateDetection to set
     */
-   public void setDuplicateDetection(boolean duplicateDetection)
+   public ClusterConnectionConfiguration setDuplicateDetection(boolean duplicateDetection)
    {
       this.duplicateDetection = duplicateDetection;
+      return this;
    }
 
    /**
     * @param forwardWhenNoConsumers the forwardWhenNoConsumers to set
     */
-   public void setForwardWhenNoConsumers(boolean forwardWhenNoConsumers)
+   public ClusterConnectionConfiguration setForwardWhenNoConsumers(boolean forwardWhenNoConsumers)
    {
       this.forwardWhenNoConsumers = forwardWhenNoConsumers;
+      return this;
    }
 
    /*
@@ -472,11 +362,23 @@ public final class ClusterConnectionConfiguration implements Serializable
       return clusterNotificationInterval;
    }
 
+   public ClusterConnectionConfiguration setClusterNotificationInterval(long clusterNotificationInterval)
+   {
+      this.clusterNotificationInterval = clusterNotificationInterval;
+      return this;
+   }
+
    public int getClusterNotificationAttempts()
    {
       return clusterNotificationAttempts;
    }
 
+   public ClusterConnectionConfiguration setClusterNotificationAttempts(int clusterNotificationAttempts)
+   {
+      this.clusterNotificationAttempts = clusterNotificationAttempts;
+      return this;
+   }
+
    @Override
    public int hashCode()
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/Configuration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/Configuration.java b/hornetq-server/src/main/java/org/hornetq/core/config/Configuration.java
index ebf06f2..084a7e2 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/Configuration.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/Configuration.java
@@ -23,7 +23,6 @@ import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.security.Role;
 import org.hornetq.core.server.JournalType;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.group.impl.GroupingHandlerConfiguration;
 import org.hornetq.core.settings.impl.AddressSettings;
 
@@ -42,7 +41,7 @@ public interface Configuration extends Serializable
    /**
     * To be used on dependency management on the application server
     */
-   void setName(String name);
+   Configuration setName(String name);
 
    /**
     * returns the name used to group of live/backup servers
@@ -59,10 +58,10 @@ public interface Configuration extends Serializable
     *
     * @param nodeGroupName the node group name
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setBackupGroupName(String)}
+    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
-   void setBackupGroupName(String nodeGroupName);
+   Configuration setBackupGroupName(String nodeGroupName);
 
    /**
     * Returns whether this server is clustered. <br>
@@ -76,20 +75,10 @@ public interface Configuration extends Serializable
     *
     * @return {@code true} if the backup will stop when the live server restarts
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#isAllowAutoFailBack()}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
-   boolean isAllowAutoFailBack();
-
-   /**
-    * whether a backup will automatically stop when a live server is restarting (i.e. failing back).
-    *
-    * @param allowAutoFailBack true if allowed
-    *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setAllowAutoFailBack(boolean)}
-    */
-   @Deprecated
-   void setAllowAutoFailBack(boolean allowAutoFailBack);
+   boolean isAllowFailBack();
 
    /**
     * Returns whether delivery count is persisted before messages are delivered to the consumers. <br>
@@ -101,7 +90,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether delivery count is persisted before messages are delivered to consumers.
     */
-   void setPersistDeliveryCountBeforeDelivery(boolean persistDeliveryCountBeforeDelivery);
+   Configuration setPersistDeliveryCountBeforeDelivery(boolean persistDeliveryCountBeforeDelivery);
 
    /**
     * Returns {@code true} if this server is a backup, {@code false} if it is a live server. <br>
@@ -116,10 +105,10 @@ public interface Configuration extends Serializable
    /**
     * Formerly set whether this server is a backup or not.
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setPolicyType(org.hornetq.core.server.cluster.ha.HAPolicy.POLICY_TYPE)}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
-   void setBackup(boolean backup);
+   Configuration setBackup(boolean backup);
 
    /**
     * Returns whether this server shares its data store with a corresponding live or backup server. <br>
@@ -133,10 +122,10 @@ public interface Configuration extends Serializable
    /**
     * Formerly set whether this server shares its data store with a backup or live server.
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setPolicyType(org.hornetq.core.server.cluster.ha.HAPolicy.POLICY_TYPE)}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
-   void setSharedStore(boolean sharedStore);
+   Configuration setSharedStore(boolean sharedStore);
 
    /**
     * Returns whether this server will use files to configure and deploy its resources. <br>
@@ -147,7 +136,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether this server will use files to configure and deploy its resources.
     */
-   void setFileDeploymentEnabled(boolean enable);
+   Configuration setFileDeploymentEnabled(boolean enable);
 
    /**
     * Returns whether this server is using persistence and store data. <br>
@@ -158,7 +147,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether this server is using persistence and store data.
     */
-   void setPersistenceEnabled(boolean enable);
+   Configuration setPersistenceEnabled(boolean enable);
 
    /**
     * Returns the period (in milliseconds) to scan configuration files used by deployment. <br>
@@ -169,7 +158,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the period  to scan configuration files used by deployment.
     */
-   void setFileDeployerScanPeriod(long period);
+   Configuration setFileDeployerScanPeriod(long period);
 
    /**
     * Returns the maximum number of threads in the thread pool of this server. <br>
@@ -180,7 +169,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the maximum number of threads in the thread pool of this server.
     */
-   void setThreadPoolMaxSize(int maxSize);
+   Configuration setThreadPoolMaxSize(int maxSize);
 
    /**
     * Returns the maximum number of threads in the <em>scheduled</em> thread pool of this server. <br>
@@ -191,7 +180,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the maximum number of threads in the <em>scheduled</em> thread pool of this server.
     */
-   void setScheduledThreadPoolMaxSize(int maxSize);
+   Configuration setScheduledThreadPoolMaxSize(int maxSize);
 
    /**
     * Returns the interval time (in milliseconds) to invalidate security credentials. <br>
@@ -202,7 +191,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the interval time (in milliseconds) to invalidate security credentials.
     */
-   void setSecurityInvalidationInterval(long interval);
+   Configuration setSecurityInvalidationInterval(long interval);
 
    /**
     * Returns whether security is enabled for this server. <br>
@@ -213,7 +202,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether security is enabled for this server.
     */
-   void setSecurityEnabled(boolean enabled);
+   Configuration setSecurityEnabled(boolean enabled);
 
    /**
     * Returns whether this server is manageable using JMX or not. <br>
@@ -222,9 +211,10 @@ public interface Configuration extends Serializable
    boolean isJMXManagementEnabled();
 
    /**
-    * Sets whether this server is manageable using JMX or not.
+    * Sets whether this server is manageable using JMX or not. <br>
+    * Default value is {@value org.hornetq.api.config.HornetQDefaultConfiguration#DEFAULT_JMX_MANAGEMENT_ENABLED}.
     */
-   void setJMXManagementEnabled(boolean enabled);
+   Configuration setJMXManagementEnabled(boolean enabled);
 
    /**
     * Returns the domain used by JMX MBeans (provided JMX management is enabled). <br>
@@ -238,7 +228,7 @@ public interface Configuration extends Serializable
     * Changing this JMX domain is required if multiple HornetQ servers are run inside
     * the same JVM and all servers are using the same MBeanServer.
     */
-   void setJMXDomain(String domain);
+   Configuration setJMXDomain(String domain);
 
    /**
     * Returns the list of interceptors classes used by this server for incoming messages (i.e. those being delivered to
@@ -276,7 +266,7 @@ public interface Configuration extends Serializable
     * {@link #setOutgoingInterceptorClassNames(List)}
     */
    @Deprecated
-   void setInterceptorClassNames(List<String> interceptors);
+   Configuration setInterceptorClassNames(List<String> interceptors);
 
    /**
     * Sets the list of interceptors classes used by this server for incoming messages (i.e. those being delivered to
@@ -284,7 +274,7 @@ public interface Configuration extends Serializable
     * <br />
     * Classes must implement {@link org.hornetq.api.core.Interceptor}.
     */
-   void setIncomingInterceptorClassNames(List<String> interceptors);
+   Configuration setIncomingInterceptorClassNames(List<String> interceptors);
 
    /**
     * Sets the list of interceptors classes used by this server for outgoing messages (i.e. those being delivered to
@@ -292,7 +282,7 @@ public interface Configuration extends Serializable
     * <br />
     * Classes must implement {@link org.hornetq.api.core.Interceptor}.
     */
-   void setOutgoingInterceptorClassNames(List<String> interceptors);
+   Configuration setOutgoingInterceptorClassNames(List<String> interceptors);
 
    /**
     * Returns the connection time to live. <br>
@@ -304,7 +294,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the connection time to live.
     */
-   void setConnectionTTLOverride(long ttl);
+   Configuration setConnectionTTLOverride(long ttl);
 
    /**
     * Returns whether code coming from connection is executed asynchronously or not. <br>
@@ -316,7 +306,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether code coming from connection is executed asynchronously or not.
     */
-   void setEnabledAsyncConnectionExecution(boolean enabled);
+   Configuration setEnabledAsyncConnectionExecution(boolean enabled);
 
    /**
     * Returns the acceptors configured for this server.
@@ -326,7 +316,11 @@ public interface Configuration extends Serializable
    /**
     * Sets the acceptors configured for this server.
     */
-   void setAcceptorConfigurations(Set<TransportConfiguration> infos);
+   Configuration setAcceptorConfigurations(Set<TransportConfiguration> infos);
+
+   Configuration addAcceptorConfiguration(final TransportConfiguration infos);
+
+   Configuration clearAcceptorConfigurations();
 
    /**
     * Returns the connectors configured for this server.
@@ -336,7 +330,9 @@ public interface Configuration extends Serializable
    /**
     * Sets the connectors configured for this server.
     */
-   void setConnectorConfigurations(Map<String, TransportConfiguration> infos);
+   Configuration setConnectorConfigurations(Map<String, TransportConfiguration> infos);
+
+   Configuration addConnectorConfiguration(final String key, final TransportConfiguration info);
 
    /**
     * Returns the broadcast groups configured for this server.
@@ -346,7 +342,9 @@ public interface Configuration extends Serializable
    /**
     * Sets the broadcast groups configured for this server.
     */
-   void setBroadcastGroupConfigurations(List<BroadcastGroupConfiguration> configs);
+   Configuration setBroadcastGroupConfigurations(List<BroadcastGroupConfiguration> configs);
+
+   Configuration addBroadcastGroupConfiguration(final BroadcastGroupConfiguration config);
 
    /**
     * Returns the discovery groups configured for this server.
@@ -356,7 +354,9 @@ public interface Configuration extends Serializable
    /**
     * Sets the discovery groups configured for this server.
     */
-   void setDiscoveryGroupConfigurations(Map<String, DiscoveryGroupConfiguration> configs);
+   Configuration setDiscoveryGroupConfigurations(Map<String, DiscoveryGroupConfiguration> configs);
+
+   Configuration addDiscoveryGroupConfiguration(final String key, DiscoveryGroupConfiguration discoveryGroupConfiguration);
 
    /**
     * Returns the grouping handler configured for this server.
@@ -366,7 +366,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the grouping handler configured for this server.
     */
-   void setGroupingHandlerConfiguration(GroupingHandlerConfiguration groupingHandlerConfiguration);
+   Configuration setGroupingHandlerConfiguration(GroupingHandlerConfiguration groupingHandlerConfiguration);
 
    /**
     * Returns the bridges configured for this server.
@@ -376,7 +376,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the bridges configured for this server.
     */
-   void setBridgeConfigurations(final List<BridgeConfiguration> configs);
+   Configuration setBridgeConfigurations(final List<BridgeConfiguration> configs);
 
    /**
     * Returns the diverts configured for this server.
@@ -386,7 +386,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the diverts configured for this server.
     */
-   void setDivertConfigurations(final List<DivertConfiguration> configs);
+   Configuration setDivertConfigurations(final List<DivertConfiguration> configs);
 
    /**
     * Returns the cluster connections configured for this server.
@@ -399,7 +399,11 @@ public interface Configuration extends Serializable
    /**
     * Sets the cluster connections configured for this server.
     */
-   void setClusterConfigurations(final List<ClusterConnectionConfiguration> configs);
+   Configuration setClusterConfigurations(final List<ClusterConnectionConfiguration> configs);
+
+   Configuration addClusterConfiguration(final ClusterConnectionConfiguration config);
+
+   Configuration clearClusterConfigurations();
 
    /**
     * Returns the queues configured for this server.
@@ -409,32 +413,34 @@ public interface Configuration extends Serializable
    /**
     * Sets the queues configured for this server.
     */
-   void setQueueConfigurations(final List<CoreQueueConfiguration> configs);
+   Configuration setQueueConfigurations(final List<CoreQueueConfiguration> configs);
+
+   Configuration addQueueConfiguration(final CoreQueueConfiguration config);
 
    /**
     * Returns the management address of this server. <br>
     * Clients can send management messages to this address to manage this server. <br>
-    * Default value is {@value org.hornetq.api.config.HornetQDefaultConfiguration#DEFAULT_MANAGEMENT_ADDRESS}.
+    * Default value is {@link org.hornetq.api.config.HornetQDefaultConfiguration#DEFAULT_MANAGEMENT_ADDRESS}.
     */
    SimpleString getManagementAddress();
 
    /**
     * Sets the management address of this server.
     */
-   void setManagementAddress(SimpleString address);
+   Configuration setManagementAddress(SimpleString address);
 
    /**
     * Returns the management notification address of this server. <br>
     * Clients can bind queues to this address to receive management notifications emitted by this
     * server. <br>
-    * Default value is {@value org.hornetq.api.config.HornetQDefaultConfiguration#DEFAULT_MANAGEMENT_NOTIFICATION_ADDRESS}.
+    * Default value is {@link org.hornetq.api.config.HornetQDefaultConfiguration#DEFAULT_MANAGEMENT_NOTIFICATION_ADDRESS}.
     */
    SimpleString getManagementNotificationAddress();
 
    /**
     * Sets the management notification address of this server.
     */
-   void setManagementNotificationAddress(SimpleString address);
+   Configuration setManagementNotificationAddress(SimpleString address);
 
    /**
     * Returns the cluster user for this server. <br>
@@ -445,7 +451,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the cluster user for this server.
     */
-   void setClusterUser(String user);
+   Configuration setClusterUser(String user);
 
    /**
     * Returns the cluster password for this server. <br>
@@ -459,7 +465,7 @@ public interface Configuration extends Serializable
     * @return true if clients should failover
     * @see #setFailoverOnServerShutdown(boolean)
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#isFailoverOnServerShutdown()}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
    boolean isFailoverOnServerShutdown();
@@ -472,15 +478,15 @@ public interface Configuration extends Serializable
     * case {@code failoverOnServerShutdown} is ignored, and the server will behave as if it was set
     * to {@code true}.
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setFailoverOnServerShutdown(boolean)}
+    * @deprecated you should replace by using the correct {@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
-   void setFailoverOnServerShutdown(boolean failoverOnServerShutdown);
+   Configuration setFailoverOnServerShutdown(boolean failoverOnServerShutdown);
 
    /**
     * Sets the cluster password for this server.
     */
-   void setClusterPassword(String password);
+   Configuration setClusterPassword(String password);
 
    /**
     * Returns the size of the cache for pre-creating message IDs. <br>
@@ -491,7 +497,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the size of the cache for pre-creating message IDs.
     */
-   void setIDCacheSize(int idCacheSize);
+   Configuration setIDCacheSize(int idCacheSize);
 
    /**
     * Returns whether message ID cache is persisted. <br>
@@ -502,7 +508,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether message ID cache is persisted.
     */
-   void setPersistIDCache(boolean persist);
+   Configuration setPersistIDCache(boolean persist);
 
    // Journal related attributes ------------------------------------------------------------
 
@@ -515,7 +521,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the file system directory used to store bindings.
     */
-   void setBindingsDirectory(String dir);
+   Configuration setBindingsDirectory(String dir);
 
    /**
     * The max number of concurrent reads allowed on paging.
@@ -529,7 +535,7 @@ public interface Configuration extends Serializable
     * <p/>
     * Default = 5
     */
-   void setPageMaxConcurrentIO(int maxIO);
+   Configuration setPageMaxConcurrentIO(int maxIO);
 
    /**
     * Returns the file system directory used to store journal log. <br>
@@ -540,7 +546,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the file system directory used to store journal log.
     */
-   void setJournalDirectory(String dir);
+   Configuration setJournalDirectory(String dir);
 
    /**
     * Returns the type of journal used by this server (either {@code NIO} or {@code ASYNCIO}).
@@ -552,7 +558,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the type of journal used by this server (either {@code NIO} or {@code ASYNCIO}).
     */
-   void setJournalType(JournalType type);
+   Configuration setJournalType(JournalType type);
 
    /**
     * Returns whether the journal is synchronized when receiving transactional data. <br>
@@ -563,7 +569,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether the journal is synchronized when receiving transactional data.
     */
-   void setJournalSyncTransactional(boolean sync);
+   Configuration setJournalSyncTransactional(boolean sync);
 
    /**
     * Returns whether the journal is synchronized when receiving non-transactional data. <br>
@@ -574,7 +580,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether the journal is synchronized when receiving non-transactional data.
     */
-   void setJournalSyncNonTransactional(boolean sync);
+   Configuration setJournalSyncNonTransactional(boolean sync);
 
    /**
     * Returns the size (in bytes) of each journal files. <br>
@@ -585,7 +591,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the size (in bytes) of each journal files.
     */
-   void setJournalFileSize(int size);
+   Configuration setJournalFileSize(int size);
 
    /**
     * Returns the minimal number of journal files before compacting. <br>
@@ -596,7 +602,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the minimal number of journal files before compacting.
     */
-   void setJournalCompactMinFiles(int minFiles);
+   Configuration setJournalCompactMinFiles(int minFiles);
 
    /**
     * Returns the percentage of live data before compacting the journal. <br>
@@ -607,7 +613,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the percentage of live data before compacting the journal.
     */
-   void setJournalCompactPercentage(int percentage);
+   Configuration setJournalCompactPercentage(int percentage);
 
    /**
     * Returns the number of journal files to pre-create. <br>
@@ -618,7 +624,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the number of journal files to pre-create.
     */
-   void setJournalMinFiles(int files);
+   Configuration setJournalMinFiles(int files);
 
    // AIO and NIO need different values for these params
 
@@ -631,7 +637,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the maximum number of write requests that can be in the AIO queue at any given time.
     */
-   void setJournalMaxIO_AIO(int journalMaxIO);
+   Configuration setJournalMaxIO_AIO(int journalMaxIO);
 
    /**
     * Returns the timeout (in nanoseconds) used to flush buffers in the AIO queue.
@@ -643,7 +649,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the timeout (in nanoseconds) used to flush buffers in the AIO queue.
     */
-   void setJournalBufferTimeout_AIO(int journalBufferTimeout);
+   Configuration setJournalBufferTimeout_AIO(int journalBufferTimeout);
 
    /**
     * Returns the buffer size (in bytes) for AIO.
@@ -655,7 +661,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the buffer size (in bytes) for AIO.
     */
-   void setJournalBufferSize_AIO(int journalBufferSize);
+   Configuration setJournalBufferSize_AIO(int journalBufferSize);
 
    /**
     * Returns the maximum number of write requests for NIO journal. <br>
@@ -666,7 +672,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the maximum number of write requests for NIO journal.
     */
-   void setJournalMaxIO_NIO(int journalMaxIO);
+   Configuration setJournalMaxIO_NIO(int journalMaxIO);
 
    /**
     * Returns the timeout (in nanoseconds) used to flush buffers in the NIO.
@@ -678,7 +684,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the timeout (in nanoseconds) used to flush buffers in the NIO.
     */
-   void setJournalBufferTimeout_NIO(int journalBufferTimeout);
+   Configuration setJournalBufferTimeout_NIO(int journalBufferTimeout);
 
    /**
     * Returns the buffer size (in bytes) for NIO.
@@ -690,7 +696,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the buffer size (in bytes) for NIO.
     */
-   void setJournalBufferSize_NIO(int journalBufferSize);
+   Configuration setJournalBufferSize_NIO(int journalBufferSize);
 
    /**
     * Returns whether the bindings directory is created on this server startup. <br>
@@ -701,7 +707,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether the bindings directory is created on this server startup.
     */
-   void setCreateBindingsDir(boolean create);
+   Configuration setCreateBindingsDir(boolean create);
 
    /**
     * Returns whether the journal directory is created on this server startup. <br>
@@ -712,33 +718,33 @@ public interface Configuration extends Serializable
    /**
     * Sets whether the journal directory is created on this server startup.
     */
-   void setCreateJournalDir(boolean create);
+   Configuration setCreateJournalDir(boolean create);
 
    // Undocumented attributes
 
    boolean isLogJournalWriteRate();
 
-   void setLogJournalWriteRate(boolean rate);
+   Configuration setLogJournalWriteRate(boolean rate);
 
    int getJournalPerfBlastPages();
 
-   void setJournalPerfBlastPages(int pages);
+   Configuration setJournalPerfBlastPages(int pages);
 
    long getServerDumpInterval();
 
-   void setServerDumpInterval(long interval);
+   Configuration setServerDumpInterval(long interval);
 
    int getMemoryWarningThreshold();
 
-   void setMemoryWarningThreshold(int memoryWarningThreshold);
+   Configuration setMemoryWarningThreshold(int memoryWarningThreshold);
 
    long getMemoryMeasureInterval();
 
-   void setMemoryMeasureInterval(long memoryMeasureInterval);
+   Configuration setMemoryMeasureInterval(long memoryMeasureInterval);
 
    boolean isRunSyncSpeedTest();
 
-   void setRunSyncSpeedTest(boolean run);
+   Configuration setRunSyncSpeedTest(boolean run);
 
    // Paging Properties --------------------------------------------------------------------
 
@@ -751,7 +757,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the file system directory used to store paging files.
     */
-   void setPagingDirectory(String dir);
+   Configuration setPagingDirectory(String dir);
 
    // Large Messages Properties ------------------------------------------------------------
 
@@ -764,7 +770,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the file system directory used to store large messages.
     */
-   void setLargeMessagesDirectory(String directory);
+   Configuration setLargeMessagesDirectory(String directory);
 
    // Other Properties ---------------------------------------------------------------------
 
@@ -777,7 +783,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether wildcard routing is supported by this server.
     */
-   void setWildcardRoutingEnabled(boolean enabled);
+   Configuration setWildcardRoutingEnabled(boolean enabled);
 
    /**
     * Returns the timeout (in milliseconds) after which transactions is removed from the resource
@@ -790,7 +796,7 @@ public interface Configuration extends Serializable
     * Sets the timeout (in milliseconds) after which transactions is removed
     * from the resource manager after it was created.
     */
-   void setTransactionTimeout(long timeout);
+   Configuration setTransactionTimeout(long timeout);
 
    /**
     * Returns whether message counter is enabled for this server. <br>
@@ -801,7 +807,7 @@ public interface Configuration extends Serializable
    /**
     * Sets whether message counter is enabled for this server.
     */
-   void setMessageCounterEnabled(boolean enabled);
+   Configuration setMessageCounterEnabled(boolean enabled);
 
    /**
     * Returns the sample period (in milliseconds) to take message counter snapshot. <br>
@@ -814,7 +820,7 @@ public interface Configuration extends Serializable
     *
     * @param period value must be greater than 1000ms
     */
-   void setMessageCounterSamplePeriod(long period);
+   Configuration setMessageCounterSamplePeriod(long period);
 
    /**
     * Returns the maximum number of days kept in memory for message counter. <br>
@@ -827,7 +833,7 @@ public interface Configuration extends Serializable
     *
     * @param maxDayHistory value must be greater than 0
     */
-   void setMessageCounterMaxDayHistory(int maxDayHistory);
+   Configuration setMessageCounterMaxDayHistory(int maxDayHistory);
 
    /**
     * Returns the frequency (in milliseconds) to scan transactions to detect which transactions have
@@ -840,7 +846,7 @@ public interface Configuration extends Serializable
     * Sets the frequency (in milliseconds)  to scan transactions to detect which transactions
     * have timed out.
     */
-   void setTransactionTimeoutScanPeriod(long period);
+   Configuration setTransactionTimeoutScanPeriod(long period);
 
    /**
     * Returns the frequency (in milliseconds) to scan messages to detect which messages have
@@ -853,7 +859,7 @@ public interface Configuration extends Serializable
     * Sets the frequency (in milliseconds)  to scan messages to detect which messages
     * have expired.
     */
-   void setMessageExpiryScanPeriod(long messageExpiryScanPeriod);
+   Configuration setMessageExpiryScanPeriod(long messageExpiryScanPeriod);
 
    /**
     * Returns the priority of the thread used to scan message expiration. <br>
@@ -864,7 +870,7 @@ public interface Configuration extends Serializable
    /**
     * Sets the priority of the thread used to scan message expiration.
     */
-   void setMessageExpiryThreadPriority(int messageExpiryThreadPriority);
+   Configuration setMessageExpiryThreadPriority(int messageExpiryThreadPriority);
 
    /**
     * @return A list of AddressSettings per matching to be deployed to the address settings repository
@@ -875,19 +881,23 @@ public interface Configuration extends Serializable
     * @param addressesSettings list of AddressSettings per matching to be deployed to the address
     *                          settings repository
     */
-   void setAddressesSettings(Map<String, AddressSettings> addressesSettings);
+   Configuration setAddressesSettings(Map<String, AddressSettings> addressesSettings);
+
+   Configuration addAddressesSetting(String key, AddressSettings addressesSetting);
 
    /**
     * @param roles a list of roles per matching
     */
-   void setSecurityRoles(Map<String, Set<Role>> roles);
+   Configuration setSecurityRoles(Map<String, Set<Role>> roles);
 
    /**
     * @return a list of roles per matching
     */
    Map<String, Set<Role>> getSecurityRoles();
 
-   void setConnectorServiceConfigurations(List<ConnectorServiceConfiguration> configs);
+   Configuration setConnectorServiceConfigurations(List<ConnectorServiceConfiguration> configs);
+
+   Configuration addConnectorServiceConfiguration(ConnectorServiceConfiguration config);
 
    /**
     * @return list of {@link ConnectorServiceConfiguration}
@@ -897,7 +907,7 @@ public interface Configuration extends Serializable
    /**
     * Returns the delay to wait before fail-back occurs on restart.
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#getFailbackDelay()}
+    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.BackupPolicy#getFailbackDelay()}
     */
    @Deprecated
    long getFailbackDelay();
@@ -905,10 +915,10 @@ public interface Configuration extends Serializable
    /**
     * Sets the fail-back delay.
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setFailbackDelay(long)}
+    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.BackupPolicy#setFailbackDelay(long)}
     */
    @Deprecated
-   void setFailbackDelay(long delay);
+   Configuration setFailbackDelay(long delay);
 
    /**
     * Whether to check if the cluster already has a (live) node with our node-ID.
@@ -920,6 +930,7 @@ public interface Configuration extends Serializable
     *
     * @return true if we want to make the check
     */
+   @Deprecated
    boolean isCheckForLiveServer();
 
    /**
@@ -932,12 +943,13 @@ public interface Configuration extends Serializable
     *
     * @param checkForLiveServer true if we want to make the check
     */
-   void setCheckForLiveServer(boolean checkForLiveServer);
+   @Deprecated
+   Configuration setCheckForLiveServer(boolean checkForLiveServer);
 
    /**
     * The default password decoder
     */
-   void setPasswordCodec(String codec);
+   Configuration setPasswordCodec(String codec);
 
    /**
     * Gets the default password decoder
@@ -947,7 +959,7 @@ public interface Configuration extends Serializable
    /**
     * Sets if passwords should be masked or not. True means the passwords should be masked.
     */
-   void setMaskPassword(boolean maskPassword);
+   Configuration setMaskPassword(boolean maskPassword);
 
    /**
     * If passwords are masked. True means the passwords are masked.
@@ -962,46 +974,26 @@ public interface Configuration extends Serializable
     *
     * @param clusterName
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setReplicationClustername(String)}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
+
    @Deprecated
-   void setReplicationClustername(String clusterName);
+   Configuration setReplicationClustername(String clusterName);
 
    /**
     * @return name of the cluster configuration to use
     * @see #setReplicationClustername(String)
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#getReplicationClustername()}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
    String getReplicationClustername();
 
-   /**
-    * Name of the cluster configuration to use for scaling down.
-    * <p/>
-    * Only applicable for servers with more than one cluster configuration.
-    *
-    * @param clusterName
-    *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setScaleDownClustername(String)}
-    */
-   @Deprecated
-   void setScaleDownClustername(String clusterName);
-
-   /**
-    * @return name of the cluster configuration to use
-    * @see #setScaleDownClustername(String)
-    *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#getScaleDownClustername()}
-    */
-   @Deprecated
-   String getScaleDownClustername();
-
    /*
    * Whether or not that HornetQ should use all protocols available on the classpath. If false only the core protocol will
    * be set, any other protocols will need to be set directly on the HornetQServer
    * */
-   void setResolveProtocols(boolean resolveProtocols);
+   Configuration setResolveProtocols(boolean resolveProtocols);
 
    /*
    * @see #setResolveProtocols()
@@ -1018,41 +1010,27 @@ public interface Configuration extends Serializable
     *
     * @param maxSavedReplicatedJournalsSize
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#getMaxSavedReplicatedJournalsSize()}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
-   void setMaxSavedReplicatedJournalSize(int maxSavedReplicatedJournalsSize);
+   Configuration setMaxSavedReplicatedJournalSize(int maxSavedReplicatedJournalsSize);
 
    /**
     * @return the number of backup journals to keep after failback has occurred
     * @see #setMaxSavedReplicatedJournalSize(int)
     *
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#getMaxSavedReplicatedJournalsSize()}
+    * @deprecated you should replace by using the correct{@link org.hornetq.core.server.cluster.ha.HAPolicy}
     */
    @Deprecated
    int getMaxSavedReplicatedJournalsSize();
 
-   Set<Configuration> getBackupServerConfigurations();
-
    Configuration copy() throws Exception;
 
-   /**
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#setBackupStrategy(BackupStrategy)}
-    */
-   @Deprecated
-   void setBackupStrategy(BackupStrategy strategy);
-
-   /**
-    * @deprecated replaced by {@link org.hornetq.core.server.cluster.ha.HAPolicy#getBackupStrategy()}
-    */
-   @Deprecated
-   BackupStrategy getBackupStrategy();
-
-   void setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout);
+   Configuration setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout);
 
    long getJournalLockAcquisitionTimeout();
 
-   HAPolicy getHAPolicy();
+   HAPolicyConfiguration getHAPolicyConfiguration();
 
-   void setHAPolicy(HAPolicy haPolicy);
+   Configuration setHAPolicyConfiguration(HAPolicyConfiguration haPolicyConfiguration);
 }


[17/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingBackupActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingBackupActivation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingBackupActivation.java
new file mode 100644
index 0000000..ea2a976
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingBackupActivation.java
@@ -0,0 +1,498 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.HornetQInternalErrorException;
+import org.hornetq.api.core.Pair;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.TopologyMember;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.paging.PagingManager;
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.protocol.core.Channel;
+import org.hornetq.core.protocol.core.impl.wireformat.ReplicationLiveIsStoppingMessage;
+import org.hornetq.core.replication.ReplicationEndpoint;
+import org.hornetq.core.server.ActivationParams;
+import org.hornetq.core.server.HornetQMessageBundle;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.LiveNodeLocator;
+import org.hornetq.core.server.NodeManager;
+import org.hornetq.core.server.QueueFactory;
+import org.hornetq.core.server.cluster.ClusterControl;
+import org.hornetq.core.server.cluster.ClusterController;
+import org.hornetq.core.server.cluster.ha.ReplicaPolicy;
+import org.hornetq.core.server.cluster.ha.ScaleDownPolicy;
+import org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum;
+import org.hornetq.core.server.group.GroupingHandler;
+import org.hornetq.core.server.management.ManagementService;
+import org.hornetq.utils.ReusableLatch;
+
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_REPLICATING;
+import static org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAIL_OVER;
+import static org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum.BACKUP_ACTIVATION.STOP;
+
+public final class SharedNothingBackupActivation extends Activation
+{
+   //this is how we act when we start as a backup
+   private ReplicaPolicy replicaPolicy;
+
+   //this is the endpoint where we replicate too
+   private ReplicationEndpoint replicationEndpoint;
+
+   private final HornetQServerImpl hornetQServer;
+   private SharedNothingBackupQuorum backupQuorum;
+   private final boolean attemptFailBack;
+   private final Map<String, Object> activationParams;
+   private final HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO;
+   private String nodeID;
+   ClusterControl clusterControl;
+   private boolean closed;
+   private volatile boolean backupUpToDate = true;
+
+   private final ReusableLatch backupSyncLatch = new ReusableLatch(0);
+
+   public SharedNothingBackupActivation(HornetQServerImpl hornetQServer,
+                                        boolean attemptFailBack,
+                                        Map<String, Object> activationParams,
+                                        HornetQServerImpl.ShutdownOnCriticalErrorListener shutdownOnCriticalIO,
+                                        ReplicaPolicy replicaPolicy)
+   {
+      this.hornetQServer = hornetQServer;
+      this.attemptFailBack = attemptFailBack;
+      this.activationParams = activationParams;
+      this.shutdownOnCriticalIO = shutdownOnCriticalIO;
+      this.replicaPolicy = replicaPolicy;
+      backupSyncLatch.setCount(1);
+   }
+
+   public void init() throws Exception
+   {
+      assert replicationEndpoint == null;
+      hornetQServer.resetNodeManager();
+      backupUpToDate = false;
+      replicationEndpoint = new ReplicationEndpoint(hornetQServer, shutdownOnCriticalIO, attemptFailBack, this);
+   }
+
+   public void run()
+   {
+      try
+      {
+         synchronized (hornetQServer)
+         {
+            hornetQServer.setState(HornetQServerImpl.SERVER_STATE.STARTED);
+         }
+         // move all data away:
+         hornetQServer.getNodeManager().stop();
+         hornetQServer.moveServerData();
+         hornetQServer.getNodeManager().start();
+         synchronized (this)
+         {
+            if (closed)
+               return;
+         }
+
+         boolean scalingDown = replicaPolicy.getScaleDownPolicy() != null && replicaPolicy.getScaleDownPolicy().isEnabled();
+
+         if (!hornetQServer.initialisePart1(scalingDown))
+            return;
+
+         synchronized (this)
+         {
+            if (closed)
+               return;
+            backupQuorum = new SharedNothingBackupQuorum(hornetQServer.getStorageManager(), hornetQServer.getNodeManager(), hornetQServer.getScheduledPool());
+            hornetQServer.getClusterManager().getQuorumManager().registerQuorum(backupQuorum);
+         }
+
+         //use a Node Locator to connect to the cluster
+         LiveNodeLocator nodeLocator;
+         if (activationParams.get(ActivationParams.REPLICATION_ENDPOINT) != null)
+         {
+            TopologyMember member = (TopologyMember) activationParams.get(ActivationParams.REPLICATION_ENDPOINT);
+            nodeLocator = new NamedNodeIdNodeLocator(member.getNodeId(), new Pair<>(member.getLive(), member.getBackup()));
+         }
+         else
+         {
+            nodeLocator = replicaPolicy.getGroupName() == null ?
+                  new AnyLiveNodeLocatorForReplication(backupQuorum, hornetQServer) :
+                  new NamedLiveNodeLocatorForReplication(replicaPolicy.getGroupName(), backupQuorum);
+         }
+         ClusterController clusterController = hornetQServer.getClusterManager().getClusterController();
+         clusterController.addClusterTopologyListenerForReplication(nodeLocator);
+         //todo do we actually need to wait?
+         clusterController.awaitConnectionToReplicationCluster();
+
+         clusterController.addIncomingInterceptorForReplication(new ReplicationError(hornetQServer, nodeLocator));
+
+         // nodeManager.startBackup();
+
+         hornetQServer.getBackupManager().start();
+
+         replicationEndpoint.setBackupQuorum(backupQuorum);
+         replicationEndpoint.setExecutor(hornetQServer.getExecutorFactory().getExecutor());
+         EndpointConnector endpointConnector = new EndpointConnector();
+
+         HornetQServerLogger.LOGGER.backupServerStarted(hornetQServer.getVersion().getFullVersion(), hornetQServer.getNodeManager().getNodeId());
+         hornetQServer.setState(HornetQServerImpl.SERVER_STATE.STARTED);
+
+         SharedNothingBackupQuorum.BACKUP_ACTIVATION signal;
+         do
+         {
+            //locate the first live server to try to replicate
+            nodeLocator.locateNode();
+            if (closed)
+            {
+               return;
+            }
+            Pair<TransportConfiguration, TransportConfiguration> possibleLive = nodeLocator.getLiveConfiguration();
+            nodeID = nodeLocator.getNodeID();
+            //in a normal (non failback) scenario if we couldn't find our live server we should fail
+            if (!attemptFailBack)
+            {
+               //this shouldn't happen
+               if (nodeID == null)
+                  throw new RuntimeException("Could not establish the connection");
+               hornetQServer.getNodeManager().setNodeID(nodeID);
+            }
+
+            try
+            {
+               clusterControl =  clusterController.connectToNodeInReplicatedCluster(possibleLive.getA());
+            }
+            catch (Exception e)
+            {
+               if (possibleLive.getB() != null)
+               {
+                  try
+                  {
+                     clusterControl = clusterController.connectToNodeInReplicatedCluster(possibleLive.getB());
+                  }
+                  catch (Exception e1)
+                  {
+                     clusterControl = null;
+                  }
+               }
+            }
+            if (clusterControl == null)
+            {
+               //its ok to retry here since we haven't started replication yet
+               //it may just be the server has gone since discovery
+               Thread.sleep(clusterController.getRetryIntervalForReplicatedCluster());
+               signal = SharedNothingBackupQuorum.BACKUP_ACTIVATION.ALREADY_REPLICATING;
+               continue;
+            }
+
+            hornetQServer.getThreadPool().execute(endpointConnector);
+            /**
+             * Wait for a signal from the the quorum manager, at this point if replication has been successful we can
+             * fail over or if there is an error trying to replicate (such as already replicating) we try the
+             * process again on the next live server.  All the action happens inside {@link BackupQuorum}
+             */
+            signal = backupQuorum.waitForStatusChange();
+            /**
+             * replicationEndpoint will be holding lots of open files. Make sure they get
+             * closed/sync'ed.
+             */
+            HornetQServerImpl.stopComponent(replicationEndpoint);
+            // time to give up
+            if (!hornetQServer.isStarted() || signal == STOP)
+               return;
+               // time to fail over
+            else if (signal == FAIL_OVER)
+               break;
+               // something has gone badly run restart from scratch
+            else if (signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_REPLICATING)
+            {
+               Thread startThread = new Thread(new Runnable()
+               {
+                  @Override
+                  public void run()
+                  {
+                     try
+                     {
+                        hornetQServer.stop();
+                     }
+                     catch (Exception e)
+                     {
+                        HornetQServerLogger.LOGGER.errorRestartingBackupServer(e, hornetQServer);
+                     }
+                  }
+               });
+               startThread.start();
+               return;
+            }
+            //ok, this live is no good, let's reset and try again
+            //close this session factory, we're done with it
+            clusterControl.close();
+            backupQuorum.reset();
+            if (replicationEndpoint.getChannel() != null)
+            {
+               replicationEndpoint.getChannel().close();
+               replicationEndpoint.setChannel(null);
+            }
+         }
+         while (signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.ALREADY_REPLICATING);
+
+         hornetQServer.getClusterManager().getQuorumManager().unRegisterQuorum(backupQuorum);
+
+         if (!isRemoteBackupUpToDate())
+         {
+            throw HornetQMessageBundle.BUNDLE.backupServerNotInSync();
+         }
+
+         replicaPolicy.getReplicatedPolicy().setReplicaPolicy(replicaPolicy);
+         hornetQServer.setHAPolicy(replicaPolicy.getReplicatedPolicy());
+         synchronized (hornetQServer)
+         {
+            if (!hornetQServer.isStarted())
+               return;
+            HornetQServerLogger.LOGGER.becomingLive(hornetQServer);
+            hornetQServer.getNodeManager().stopBackup();
+            hornetQServer.getStorageManager().start();
+            hornetQServer.getBackupManager().activated();
+            if (scalingDown)
+            {
+               hornetQServer.initialisePart2(true);
+            }
+            else
+            {
+               hornetQServer.setActivation(new SharedNothingLiveActivation(hornetQServer, replicaPolicy.getReplicatedPolicy()));
+               hornetQServer.initialisePart2(false);
+
+               if (hornetQServer.getIdentity() != null)
+               {
+                  HornetQServerLogger.LOGGER.serverIsLive(hornetQServer.getIdentity());
+               }
+               else
+               {
+                  HornetQServerLogger.LOGGER.serverIsLive();
+               }
+
+            }
+         }
+      }
+      catch (Exception e)
+      {
+         if ((e instanceof InterruptedException || e instanceof IllegalStateException) && !hornetQServer.isStarted())
+            // do not log these errors if the server is being stopped.
+            return;
+         HornetQServerLogger.LOGGER.initializationError(e);
+         e.printStackTrace();
+      }
+   }
+
+   public void close(final boolean permanently, boolean restarting) throws Exception
+   {
+      synchronized (this)
+      {
+         if (backupQuorum != null)
+            backupQuorum.causeExit(STOP);
+         replicationEndpoint = null;
+         closed = true;
+      }
+      //we have to check as the server policy may have changed
+      if (hornetQServer.getHAPolicy().isBackup())
+      {
+         // To avoid a NPE cause by the stop
+         NodeManager nodeManagerInUse = hornetQServer.getNodeManager();
+
+         hornetQServer.interrupBackupThread(nodeManagerInUse);
+
+         if (nodeManagerInUse != null)
+         {
+            nodeManagerInUse.stopBackup();
+         }
+      }
+   }
+
+   @Override
+   public void preStorageClose() throws Exception
+   {
+      if (replicationEndpoint != null)
+      {
+         replicationEndpoint.stop();
+      }
+   }
+
+   @Override
+   public JournalLoader createJournalLoader(PostOffice postOffice, PagingManager pagingManager, StorageManager storageManager, QueueFactory queueFactory, NodeManager nodeManager, ManagementService managementService, GroupingHandler groupingHandler, Configuration configuration, HornetQServer parentServer) throws HornetQException
+   {
+      if (replicaPolicy.getScaleDownPolicy() != null)
+      {
+         return new BackupRecoveryJournalLoader(postOffice,
+               pagingManager,
+               storageManager,
+               queueFactory,
+               nodeManager,
+               managementService,
+               groupingHandler,
+               configuration,
+               parentServer,
+               ScaleDownPolicy.getScaleDownConnector(replicaPolicy.getScaleDownPolicy(), hornetQServer),
+               hornetQServer.getClusterManager().getClusterController());
+      }
+      else
+      {
+         return super.createJournalLoader(postOffice,
+               pagingManager,
+               storageManager,
+               queueFactory,
+               nodeManager,
+               managementService,
+               groupingHandler,
+               configuration,
+               parentServer);
+      }
+   }
+
+   @Override
+   public void haStarted()
+   {
+      hornetQServer.getClusterManager().getClusterController().setReplicatedClusterName(replicaPolicy.getClusterName());
+   }
+
+
+   /**
+    * Wait for backup synchronization when using synchronization
+    * @param timeout
+    * @param unit
+    * @see java.util.concurrent.CountDownLatch#await(long, TimeUnit)
+    * @return {@code true} if the server was already initialized or if it was initialized within the
+    *         timeout period, {@code false} otherwise.
+    * @throws InterruptedException
+    */
+   public boolean waitForBackupSync(long timeout, TimeUnit unit) throws InterruptedException
+   {
+      return backupSyncLatch.await(timeout, unit);
+   }
+
+   /**
+    * Live has notified this server that it is going to stop.
+    */
+   public void failOver(final ReplicationLiveIsStoppingMessage.LiveStopping finalMessage)
+   {
+      if (finalMessage == null)
+      {
+         backupQuorum.causeExit(FAILURE_REPLICATING);
+      }
+      else
+      {
+         backupQuorum.failOver(finalMessage);
+      }
+   }
+
+   public ReplicationEndpoint getReplicationEndpoint()
+   {
+      return replicationEndpoint;
+   }
+
+
+   /**
+    * Whether a remote backup server was in sync with its live server. If it was not in sync, it may
+    * not take over the live's functions.
+    * <p/>
+    * A local backup server or a live server should always return {@code true}
+    *
+    * @return whether the backup is up-to-date, if the server is not a backup it always returns
+    * {@code true}.
+    */
+   public boolean isRemoteBackupUpToDate()
+   {
+      return backupUpToDate;
+   }
+
+   public void setRemoteBackupUpToDate()
+   {
+      hornetQServer.getBackupManager().announceBackup();
+      backupUpToDate = true;
+      backupSyncLatch.countDown();
+   }
+
+   /**
+    * @throws org.hornetq.api.core.HornetQException
+    */
+   public void remoteFailOver(ReplicationLiveIsStoppingMessage.LiveStopping finalMessage) throws HornetQException
+   {
+      HornetQServerLogger.LOGGER.trace("Remote fail-over, got message=" + finalMessage + ", backupUpToDate=" +
+            backupUpToDate);
+      if (!hornetQServer.getHAPolicy().isBackup() || hornetQServer.getHAPolicy().isSharedStore())
+      {
+         throw new HornetQInternalErrorException();
+      }
+
+      if (!backupUpToDate)
+      {
+         failOver(null);
+      }
+      else
+      {
+         failOver(finalMessage);
+      }
+   }
+
+
+
+   private class EndpointConnector implements Runnable
+   {
+      @Override
+      public void run()
+      {
+         try
+         {
+            //we should only try once, if its not there we should move on.
+            clusterControl.getSessionFactory().setReconnectAttempts(1);
+            backupQuorum.setSessionFactory(clusterControl.getSessionFactory());
+            //get the connection and request replication to live
+            clusterControl.authorize();
+            connectToReplicationEndpoint(clusterControl);
+            replicationEndpoint.start();
+            clusterControl.announceReplicatingBackupToLive(attemptFailBack, replicaPolicy.getClusterName());
+         }
+         catch (Exception e)
+         {
+            //we shouldn't stop the server just mark the connector as tried and unavailable
+            HornetQServerLogger.LOGGER.replicationStartProblem(e);
+            backupQuorum.causeExit(FAILURE_REPLICATING);
+         }
+      }
+
+      private synchronized ReplicationEndpoint connectToReplicationEndpoint(final ClusterControl control) throws Exception
+      {
+         if (!hornetQServer.isStarted())
+            return null;
+         if (!hornetQServer.getHAPolicy().isBackup())
+         {
+            throw HornetQMessageBundle.BUNDLE.serverNotBackupServer();
+         }
+
+         Channel replicationChannel = control.createReplicationChannel();
+
+         replicationChannel.setHandler(replicationEndpoint);
+
+         if (replicationEndpoint.getChannel() != null)
+         {
+            throw HornetQMessageBundle.BUNDLE.alreadyHaveReplicationServer();
+         }
+
+         replicationEndpoint.setChannel(replicationChannel);
+
+         return replicationEndpoint;
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingLiveActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingLiveActivation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingLiveActivation.java
new file mode 100644
index 0000000..27ad9d8
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedNothingLiveActivation.java
@@ -0,0 +1,486 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.api.core.DiscoveryGroupConfiguration;
+import org.hornetq.api.core.HornetQAlreadyReplicatingException;
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.HornetQIllegalStateException;
+import org.hornetq.api.core.Pair;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.ClusterTopologyListener;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.api.core.client.TopologyMember;
+import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
+import org.hornetq.core.client.impl.ServerLocatorInternal;
+import org.hornetq.core.config.ClusterConnectionConfiguration;
+import org.hornetq.core.config.ConfigurationUtils;
+import org.hornetq.core.protocol.core.Channel;
+import org.hornetq.core.protocol.core.ChannelHandler;
+import org.hornetq.core.protocol.core.CoreRemotingConnection;
+import org.hornetq.core.protocol.core.Packet;
+import org.hornetq.core.protocol.core.impl.PacketImpl;
+import org.hornetq.core.protocol.core.impl.wireformat.BackupRegistrationMessage;
+import org.hornetq.core.protocol.core.impl.wireformat.BackupReplicationStartFailedMessage;
+import org.hornetq.core.protocol.core.impl.wireformat.ReplicationLiveIsStoppingMessage;
+import org.hornetq.core.remoting.CloseListener;
+import org.hornetq.core.remoting.FailureListener;
+import org.hornetq.core.remoting.server.RemotingService;
+import org.hornetq.core.replication.ReplicationManager;
+import org.hornetq.core.server.HornetQMessageBundle;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.NodeManager;
+import org.hornetq.core.server.cluster.ClusterConnection;
+import org.hornetq.core.server.cluster.ha.ReplicatedPolicy;
+import org.hornetq.spi.core.remoting.Acceptor;
+
+import java.lang.reflect.Array;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class SharedNothingLiveActivation extends LiveActivation
+{
+   //this is how we act when we initially start as a live
+   private ReplicatedPolicy replicatedPolicy;
+
+   private HornetQServerImpl hornetQServer;
+
+   private ReplicationManager replicationManager;
+
+   private final Object replicationLock = new Object();
+
+   public SharedNothingLiveActivation(HornetQServerImpl hornetQServer,
+                                      ReplicatedPolicy replicatedPolicy)
+   {
+      this.hornetQServer = hornetQServer;
+      this.replicatedPolicy = replicatedPolicy;
+   }
+
+   @Override
+   public void freezeConnections(RemotingService remotingService)
+   {
+      ReplicationManager localReplicationManager = replicationManager;
+
+      if (remotingService != null && localReplicationManager != null)
+      {
+         remotingService.freeze(null, localReplicationManager.getBackupTransportConnection());
+      }
+      else if (remotingService != null)
+      {
+         remotingService.freeze(null, null);
+      }
+   }
+
+   public void run()
+   {
+      try
+      {
+         if (replicatedPolicy.isCheckForLiveServer() && isNodeIdUsed())
+         {
+            //set for when we failback
+            replicatedPolicy.getReplicaPolicy().setReplicatedPolicy(replicatedPolicy);
+            hornetQServer.setHAPolicy(replicatedPolicy.getReplicaPolicy());
+            return;
+         }
+
+         hornetQServer.initialisePart1(false);
+
+         hornetQServer.initialisePart2(false);
+
+         if (hornetQServer.getIdentity() != null)
+         {
+            HornetQServerLogger.LOGGER.serverIsLive(hornetQServer.getIdentity());
+         }
+         else
+         {
+            HornetQServerLogger.LOGGER.serverIsLive();
+         }
+      }
+      catch (Exception e)
+      {
+         HornetQServerLogger.LOGGER.initializationError(e);
+      }
+   }
+
+   @Override
+   public ChannelHandler getActivationChannelHandler(final Channel channel, final Acceptor acceptorUsed)
+   {
+      return new ChannelHandler()
+      {
+         @Override
+         public void handlePacket(Packet packet)
+         {
+            if (packet.getType() == PacketImpl.BACKUP_REGISTRATION)
+            {
+               BackupRegistrationMessage msg = (BackupRegistrationMessage)packet;
+               ClusterConnection clusterConnection = acceptorUsed.getClusterConnection();
+               try
+               {
+                  startReplication(channel.getConnection(), clusterConnection, getPair(msg.getConnector(), true),
+                        msg.isFailBackRequest());
+               }
+               catch (HornetQAlreadyReplicatingException are)
+               {
+                  channel.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.ALREADY_REPLICATING));
+               }
+               catch (HornetQException e)
+               {
+                  channel.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.EXCEPTION));
+               }
+            }
+         }
+      };
+   }
+
+   public void startReplication(CoreRemotingConnection rc, final ClusterConnection clusterConnection,
+                                final Pair<TransportConfiguration, TransportConfiguration> pair, final boolean isFailBackRequest) throws HornetQException
+   {
+      if (replicationManager != null)
+      {
+         throw new HornetQAlreadyReplicatingException();
+      }
+
+      if (!hornetQServer.isStarted())
+      {
+         throw new HornetQIllegalStateException();
+      }
+
+      synchronized (replicationLock)
+      {
+
+         if (replicationManager != null)
+         {
+            throw new HornetQAlreadyReplicatingException();
+         }
+         ReplicationFailureListener listener = new ReplicationFailureListener();
+         rc.addCloseListener(listener);
+         rc.addFailureListener(listener);
+         replicationManager = new ReplicationManager(rc, hornetQServer.getExecutorFactory());
+         replicationManager.start();
+         Thread t = new Thread(new Runnable()
+         {
+            public void run()
+            {
+               try
+               {
+                  hornetQServer.getStorageManager().startReplication(replicationManager, hornetQServer.getPagingManager(), hornetQServer.getNodeID().toString(),
+                        isFailBackRequest && replicatedPolicy.isAllowAutoFailBack());
+
+                  clusterConnection.nodeAnnounced(System.currentTimeMillis(), hornetQServer.getNodeID().toString(), replicatedPolicy.getGroupName(), replicatedPolicy.getScaleDownGroupName(), pair, true);
+
+                  //todo, check why this was set here
+                  //backupUpToDate = false;
+
+                  if (isFailBackRequest && replicatedPolicy.isAllowAutoFailBack())
+                  {
+                     BackupTopologyListener listener1 = new BackupTopologyListener(hornetQServer.getNodeID().toString());
+                     clusterConnection.addClusterTopologyListener(listener1);
+                     if (listener1.waitForBackup())
+                     {
+                        try
+                        {
+                           Thread.sleep(replicatedPolicy.getFailbackDelay());
+                        }
+                        catch (InterruptedException e)
+                        {
+                           //
+                        }
+                        //if we have to many backups kept or arent configured to restart just stop, otherwise restart as a backup
+                        if (!replicatedPolicy.getReplicaPolicy().isRestartBackup() && hornetQServer.countNumberOfCopiedJournals() >= replicatedPolicy.getReplicaPolicy().getMaxSavedReplicatedJournalsSize() && replicatedPolicy.getReplicaPolicy().getMaxSavedReplicatedJournalsSize() >= 0)
+                        {
+                           hornetQServer.stop(true);
+                           HornetQServerLogger.LOGGER.stopReplicatedBackupAfterFailback();
+                        }
+                        else
+                        {
+                           hornetQServer.stop(true);
+                           HornetQServerLogger.LOGGER.restartingReplicatedBackupAfterFailback();
+                           hornetQServer.setHAPolicy(replicatedPolicy.getReplicaPolicy());
+                           hornetQServer.start();
+                        }
+                     }
+                     else
+                     {
+                        HornetQServerLogger.LOGGER.failbackMissedBackupAnnouncement();
+                     }
+                  }
+               }
+               catch (Exception e)
+               {
+                  if (hornetQServer.getState() == HornetQServerImpl.SERVER_STATE.STARTED)
+                  {
+                  /*
+                   * The reasoning here is that the exception was either caused by (1) the
+                   * (interaction with) the backup, or (2) by an IO Error at the storage. If (1), we
+                   * can swallow the exception and ignore the replication request. If (2) the live
+                   * will crash shortly.
+                   */
+                     HornetQServerLogger.LOGGER.errorStartingReplication(e);
+                  }
+                  try
+                  {
+                     HornetQServerImpl.stopComponent(replicationManager);
+                  }
+                  catch (Exception hqe)
+                  {
+                     HornetQServerLogger.LOGGER.errorStoppingReplication(hqe);
+                  }
+                  finally
+                  {
+                     synchronized (replicationLock)
+                     {
+                        replicationManager = null;
+                     }
+                  }
+               }
+            }
+         });
+
+         t.start();
+      }
+   }
+
+   private final class ReplicationFailureListener implements FailureListener, CloseListener
+   {
+
+      @Override
+      public void connectionFailed(HornetQException exception, boolean failedOver)
+      {
+         connectionClosed();
+      }
+
+      @Override
+      public void connectionFailed(final HornetQException me, boolean failedOver, String scaleDownTargetNodeID)
+      {
+         connectionFailed(me, failedOver);
+      }
+
+      @Override
+      public void connectionClosed()
+      {
+         hornetQServer.getThreadPool().execute(new Runnable()
+         {
+            public void run()
+            {
+               synchronized (replicationLock)
+               {
+                  if (replicationManager != null)
+                  {
+                     hornetQServer.getStorageManager().stopReplication();
+                     replicationManager = null;
+                  }
+               }
+            }
+         });
+      }
+   }
+
+   private Pair<TransportConfiguration, TransportConfiguration> getPair(TransportConfiguration conn,
+                                                                        boolean isBackup)
+   {
+      if (isBackup)
+      {
+         return new Pair<>(null, conn);
+      }
+      return new Pair<>(conn, null);
+   }
+   /**
+    * Determines whether there is another server already running with this server's nodeID.
+    * <p/>
+    * This can happen in case of a successful fail-over followed by the live's restart
+    * (attempting a fail-back).
+    *
+    * @throws Exception
+    */
+   private boolean isNodeIdUsed() throws Exception
+   {
+      if (hornetQServer.getConfiguration().getClusterConfigurations().isEmpty())
+         return false;
+      SimpleString nodeId0;
+      try
+      {
+         nodeId0 = hornetQServer.getNodeManager().readNodeId();
+      }
+      catch (HornetQIllegalStateException e)
+      {
+         nodeId0 = null;
+      }
+
+      ServerLocatorInternal locator;
+
+      ClusterConnectionConfiguration config = ConfigurationUtils.getReplicationClusterConfiguration(hornetQServer.getConfiguration(), replicatedPolicy.getClusterName());
+
+      locator = getLocator(config);
+
+      ClientSessionFactoryInternal factory = null;
+
+      NodeIdListener listener = new NodeIdListener(nodeId0);
+
+      locator.addClusterTopologyListener(listener);
+      try
+      {
+         locator.setReconnectAttempts(0);
+         try
+         {
+            locator.addClusterTopologyListener(listener);
+            factory = locator.connectNoWarnings();
+         }
+         catch (Exception notConnected)
+         {
+            return false;
+         }
+
+         listener.latch.await(5, TimeUnit.SECONDS);
+
+         return listener.isNodePresent;
+      }
+      finally
+      {
+         if (factory != null)
+            factory.close();
+         if (locator != null)
+            locator.close();
+      }
+   }
+
+   public void close(boolean permanently, boolean restarting) throws Exception
+   {
+
+      replicationManager = null;
+      // To avoid a NPE cause by the stop
+      NodeManager nodeManagerInUse = hornetQServer.getNodeManager();
+
+      if (nodeManagerInUse != null)
+      {
+         //todo does this actually make any difference, we only set a different flag in the lock file which replication doesnt use
+         if (permanently)
+         {
+            nodeManagerInUse.crashLiveServer();
+         }
+         else
+         {
+            nodeManagerInUse.pauseLiveServer();
+         }
+      }
+   }
+
+   @Override
+   public void sendLiveIsStopping()
+   {
+      final ReplicationManager localReplicationManager = replicationManager;
+
+      if (localReplicationManager != null)
+      {
+         localReplicationManager.sendLiveIsStopping(ReplicationLiveIsStoppingMessage.LiveStopping.STOP_CALLED);
+         // Schedule for 10 seconds
+         // this pool gets a 'hard' shutdown, no need to manage the Future of this Runnable.
+         hornetQServer.getScheduledPool().schedule(new Runnable()
+         {
+            @Override
+            public void run()
+            {
+               localReplicationManager.clearReplicationTokens();
+            }
+         }, 30, TimeUnit.SECONDS);
+      }
+   }
+
+   public ReplicationManager getReplicationManager()
+   {
+      synchronized (replicationLock)
+      {
+         return replicationManager;
+      }
+   }
+
+   private ServerLocatorInternal getLocator(ClusterConnectionConfiguration config) throws HornetQException
+   {
+      ServerLocatorInternal locator;
+      if (config.getDiscoveryGroupName() != null)
+      {
+         DiscoveryGroupConfiguration dg = hornetQServer.getConfiguration().getDiscoveryGroupConfigurations().get(config.getDiscoveryGroupName());
+
+         if (dg == null)
+         {
+            throw HornetQMessageBundle.BUNDLE.noDiscoveryGroupFound(dg);
+         }
+         locator = (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(dg);
+      }
+      else
+      {
+         TransportConfiguration[] tcConfigs = config.getStaticConnectors() != null ? connectorNameListToArray(config.getStaticConnectors())
+               : null;
+
+         locator = (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(tcConfigs);
+      }
+      return locator;
+   }
+
+
+   static final class NodeIdListener implements ClusterTopologyListener
+   {
+      volatile boolean isNodePresent = false;
+
+      private final SimpleString nodeId;
+      private final CountDownLatch latch = new CountDownLatch(1);
+
+      public NodeIdListener(SimpleString nodeId)
+      {
+         this.nodeId = nodeId;
+      }
+
+      @Override
+      public void nodeUP(TopologyMember topologyMember, boolean last)
+      {
+         boolean isOurNodeId = nodeId != null && nodeId.toString().equals(topologyMember.getNodeId());
+         if (isOurNodeId)
+         {
+            isNodePresent = true;
+         }
+         if (isOurNodeId || last)
+         {
+            latch.countDown();
+         }
+      }
+
+      @Override
+      public void nodeDown(long eventUID, String nodeID)
+      {
+         // no-op
+      }
+   }
+
+   private TransportConfiguration[] connectorNameListToArray(final List<String> connectorNames)
+   {
+      TransportConfiguration[] tcConfigs = (TransportConfiguration[]) Array.newInstance(TransportConfiguration.class,
+            connectorNames.size());
+      int count = 0;
+      for (String connectorName : connectorNames)
+      {
+         TransportConfiguration connector = hornetQServer.getConfiguration().getConnectorConfigurations().get(connectorName);
+
+         if (connector == null)
+         {
+            HornetQServerLogger.LOGGER.bridgeNoConnector(connectorName);
+
+            return null;
+         }
+
+         tcConfigs[count++] = connector;
+      }
+
+      return tcConfigs;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreBackupActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreBackupActivation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreBackupActivation.java
new file mode 100644
index 0000000..6c27e12
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreBackupActivation.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.paging.PagingManager;
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.NodeManager;
+import org.hornetq.core.server.QueueFactory;
+import org.hornetq.core.server.cluster.ha.ScaleDownPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreSlavePolicy;
+import org.hornetq.core.server.group.GroupingHandler;
+import org.hornetq.core.server.management.ManagementService;
+
+import java.nio.channels.ClosedChannelException;
+import java.util.concurrent.TimeUnit;
+
+public final class SharedStoreBackupActivation extends Activation
+{
+   //this is how we act as a backup
+   private SharedStoreSlavePolicy sharedStoreSlavePolicy;
+
+   private HornetQServerImpl hornetQServer;
+
+   private final Object failbackCheckerGuard = new Object();
+
+   private boolean cancelFailBackChecker;
+
+   public SharedStoreBackupActivation(HornetQServerImpl server, SharedStoreSlavePolicy sharedStoreSlavePolicy)
+   {
+      this.hornetQServer = server;
+      this.sharedStoreSlavePolicy = sharedStoreSlavePolicy;
+      synchronized (failbackCheckerGuard)
+      {
+         cancelFailBackChecker = false;
+      }
+   }
+
+   public void run()
+   {
+      try
+      {
+         hornetQServer.getNodeManager().startBackup();
+
+         boolean scalingDown = sharedStoreSlavePolicy.getScaleDownPolicy() != null;
+
+         if (!hornetQServer.initialisePart1(scalingDown))
+            return;
+
+         hornetQServer.getBackupManager().start();
+
+         hornetQServer.setState(HornetQServerImpl.SERVER_STATE.STARTED);
+
+         HornetQServerLogger.LOGGER.backupServerStarted(hornetQServer.getVersion().getFullVersion(), hornetQServer.getNodeManager().getNodeId());
+
+         hornetQServer.getNodeManager().awaitLiveNode();
+
+         sharedStoreSlavePolicy.getSharedStoreMasterPolicy().setSharedStoreSlavePolicy(sharedStoreSlavePolicy);
+
+         hornetQServer.setHAPolicy(sharedStoreSlavePolicy.getSharedStoreMasterPolicy());
+
+         //hornetQServer.configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
+
+         hornetQServer.getBackupManager().activated();
+         if (hornetQServer.getState() != HornetQServerImpl.SERVER_STATE.STARTED)
+         {
+            return;
+         }
+
+         hornetQServer.initialisePart2(scalingDown);
+
+         if (scalingDown)
+         {
+            HornetQServerLogger.LOGGER.backupServerScaledDown();
+            Thread t = new Thread(new Runnable()
+            {
+               @Override
+               public void run()
+               {
+                  try
+                  {
+                     hornetQServer.stop();
+                     //we are shared store but if we were started by a parent server then we shouldn't restart
+                     if (sharedStoreSlavePolicy.isRestartBackup())
+                     {
+                        hornetQServer.start();
+                     }
+                  }
+                  catch (Exception e)
+                  {
+                     HornetQServerLogger.LOGGER.serverRestartWarning();
+                  }
+               }
+            });
+            t.start();
+            return;
+         }
+         else
+         {
+            HornetQServerLogger.LOGGER.backupServerIsLive();
+
+            hornetQServer.getNodeManager().releaseBackup();
+         }
+         if (sharedStoreSlavePolicy.isAllowAutoFailBack())
+         {
+            startFailbackChecker();
+         }
+      }
+      catch (InterruptedException e)
+      {
+         // this is ok, we are being stopped
+      }
+      catch (ClosedChannelException e)
+      {
+         // this is ok too, we are being stopped
+      }
+      catch (Exception e)
+      {
+         if (!(e.getCause() instanceof InterruptedException))
+         {
+            HornetQServerLogger.LOGGER.initializationError(e);
+         }
+      }
+      catch (Throwable e)
+      {
+         HornetQServerLogger.LOGGER.initializationError(e);
+      }
+   }
+
+   public void close(boolean permanently, boolean restarting) throws Exception
+   {
+      if (!restarting)
+      {
+         synchronized (failbackCheckerGuard)
+         {
+            cancelFailBackChecker = true;
+         }
+      }
+      // To avoid a NPE cause by the stop
+      NodeManager nodeManagerInUse = hornetQServer.getNodeManager();
+
+      //we need to check as the servers policy may have changed
+      if (hornetQServer.getHAPolicy().isBackup())
+      {
+
+         hornetQServer.interrupBackupThread(nodeManagerInUse);
+
+
+         if (nodeManagerInUse != null)
+         {
+            nodeManagerInUse.stopBackup();
+         }
+      }
+      else
+      {
+
+         if (nodeManagerInUse != null)
+         {
+            // if we are now live, behave as live
+            // We need to delete the file too, otherwise the backup will failover when we shutdown or if the backup is
+            // started before the live
+            if (sharedStoreSlavePolicy.isFailoverOnServerShutdown() || permanently)
+            {
+               nodeManagerInUse.crashLiveServer();
+            }
+            else
+            {
+               nodeManagerInUse.pauseLiveServer();
+            }
+         }
+      }
+   }
+
+   @Override
+   public JournalLoader createJournalLoader(PostOffice postOffice, PagingManager pagingManager, StorageManager storageManager, QueueFactory queueFactory, NodeManager nodeManager, ManagementService managementService, GroupingHandler groupingHandler, Configuration configuration, HornetQServer parentServer) throws HornetQException
+   {
+      if (sharedStoreSlavePolicy.getScaleDownPolicy() != null)
+      {
+         return new BackupRecoveryJournalLoader(postOffice,
+               pagingManager,
+               storageManager,
+               queueFactory,
+               nodeManager,
+               managementService,
+               groupingHandler,
+               configuration,
+               parentServer,
+               ScaleDownPolicy.getScaleDownConnector(sharedStoreSlavePolicy.getScaleDownPolicy(), hornetQServer),
+               hornetQServer.getClusterManager().getClusterController());
+      }
+      else
+      {
+         return super.createJournalLoader(postOffice,
+               pagingManager,
+               storageManager,
+               queueFactory,
+               nodeManager,
+               managementService,
+               groupingHandler,
+               configuration,
+               parentServer);
+      }
+   }
+
+   /**
+    * To be called by backup trying to fail back the server
+    */
+   private void startFailbackChecker()
+   {
+      hornetQServer.getScheduledPool().scheduleAtFixedRate(new FailbackChecker(), 1000L, 1000L, TimeUnit.MILLISECONDS);
+   }
+   private class FailbackChecker implements Runnable
+   {
+      private boolean restarting = false;
+
+      public void run()
+      {
+         try
+         {
+            if (!restarting && hornetQServer.getNodeManager().isAwaitingFailback())
+            {
+               HornetQServerLogger.LOGGER.awaitFailBack();
+               restarting = true;
+               Thread t = new Thread(new Runnable()
+               {
+                  public void run()
+                  {
+                     try
+                     {
+                        HornetQServerLogger.LOGGER.debug(hornetQServer + "::Stopping live node in favor of failback");
+
+                        hornetQServer.stop(true, false, true);
+                        // We need to wait some time before we start the backup again
+                        // otherwise we may eventually start before the live had a chance to get it
+                        Thread.sleep(sharedStoreSlavePolicy.getFailbackDelay());
+                        synchronized (failbackCheckerGuard)
+                        {
+                           if (cancelFailBackChecker || !sharedStoreSlavePolicy.isRestartBackup())
+                              return;
+
+                           hornetQServer.setHAPolicy(sharedStoreSlavePolicy);
+                           HornetQServerLogger.LOGGER.debug(hornetQServer +
+                                 "::Starting backup node now after failback");
+                           hornetQServer.start();
+                        }
+                     }
+                     catch (Exception e)
+                     {
+                        HornetQServerLogger.LOGGER.serverRestartWarning();
+                     }
+                  }
+               });
+               t.start();
+            }
+         }
+         catch (Exception e)
+         {
+            HornetQServerLogger.LOGGER.serverRestartWarning(e);
+         }
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreLiveActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreLiveActivation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreLiveActivation.java
new file mode 100644
index 0000000..4f8baf2
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/SharedStoreLiveActivation.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.NodeManager;
+import org.hornetq.core.server.cluster.ha.SharedStoreMasterPolicy;
+
+/**
+* Created by andy on 04/09/14.
+*/
+public final class SharedStoreLiveActivation extends LiveActivation
+{
+   //this is how we act when we initially start as live
+   private SharedStoreMasterPolicy sharedStoreMasterPolicy;
+
+   private HornetQServerImpl hornetQServer;
+
+   public SharedStoreLiveActivation(HornetQServerImpl server, SharedStoreMasterPolicy sharedStoreMasterPolicy)
+   {
+      this.hornetQServer = server;
+      this.sharedStoreMasterPolicy = sharedStoreMasterPolicy;
+   }
+
+   public void run()
+   {
+      try
+      {
+         HornetQServerLogger.LOGGER.awaitingLiveLock();
+
+         hornetQServer.checkJournalDirectory();
+
+         if (HornetQServerLogger.LOGGER.isDebugEnabled())
+         {
+            HornetQServerLogger.LOGGER.debug("First part initialization on " + this);
+         }
+
+         if (!hornetQServer.initialisePart1(false))
+            return;
+
+         if (hornetQServer.getNodeManager().isBackupLive())
+         {
+            /*
+             * looks like we've failed over at some point need to inform that we are the backup
+             * so when the current live goes down they failover to us
+             */
+            if (HornetQServerLogger.LOGGER.isDebugEnabled())
+            {
+               HornetQServerLogger.LOGGER.debug("announcing backup to the former live" + this);
+            }
+            hornetQServer.getBackupManager().start();
+            hornetQServer.getBackupManager().announceBackup();
+            Thread.sleep(sharedStoreMasterPolicy.getFailbackDelay());
+         }
+
+         hornetQServer.getNodeManager().startLiveNode();
+
+         if (hornetQServer.getState() == HornetQServerImpl.SERVER_STATE.STOPPED || hornetQServer.getState() == HornetQServerImpl.SERVER_STATE.STOPPING)
+         {
+            return;
+         }
+
+         hornetQServer.initialisePart2(false);
+
+         HornetQServerLogger.LOGGER.serverIsLive();
+      }
+      catch (Exception e)
+      {
+         HornetQServerLogger.LOGGER.initializationError(e);
+      }
+   }
+
+   public void close(boolean permanently, boolean restarting) throws Exception
+   {
+      // TO avoid a NPE from stop
+      NodeManager nodeManagerInUse = hornetQServer.getNodeManager();
+
+      if (nodeManagerInUse != null)
+      {
+         if (sharedStoreMasterPolicy.isFailoverOnServerShutdown() || permanently)
+         {
+            nodeManagerInUse.crashLiveServer();
+         }
+         else
+         {
+            nodeManagerInUse.pauseLiveServer();
+         }
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/management/impl/ManagementServiceImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/management/impl/ManagementServiceImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/management/impl/ManagementServiceImpl.java
index a460d59..59f51f9 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/management/impl/ManagementServiceImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/management/impl/ManagementServiceImpl.java
@@ -392,7 +392,7 @@ public class ManagementServiceImpl implements ManagementService
    public ServerMessage handleMessage(final ServerMessage message) throws Exception
    {
       // a reply message is sent with the result stored in the message body.
-      ServerMessage reply = new ServerMessageImpl(storageManager.generateUniqueID(), 512);
+      ServerMessage reply = new ServerMessageImpl(storageManager.generateID(), 512);
 
       String resourceName = message.getStringProperty(ManagementHelper.HDR_RESOURCE_NAME);
       if (HornetQServerLogger.LOGGER.isDebugEnabled())
@@ -700,7 +700,7 @@ public class ManagementServiceImpl implements ManagementService
                   return;
                }
 
-               long messageID = storageManager.generateUniqueID();
+               long messageID = storageManager.generateID();
 
                ServerMessage notificationMessage = new ServerMessageImpl(messageID, 512);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/settings/impl/AddressSettings.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/settings/impl/AddressSettings.java b/hornetq-server/src/main/java/org/hornetq/core/settings/impl/AddressSettings.java
index 51412cc..88dd300 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/settings/impl/AddressSettings.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/settings/impl/AddressSettings.java
@@ -58,6 +58,12 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
 
    public static final boolean DEFAULT_SEND_TO_DLA_ON_NO_ROUTE = false;
 
+   public static final long DEFAULT_SLOW_CONSUMER_THRESHOLD = -1;
+
+   public static final long DEFAULT_SLOW_CONSUMER_CHECK_PERIOD = 5;
+
+   public static final SlowConsumerPolicy DEFAULT_SLOW_CONSUMER_POLICY = SlowConsumerPolicy.NOTIFY;
+
    private AddressFullMessagePolicy addressFullMessagePolicy = null;
 
    private Long maxSizeBytes = null;
@@ -90,6 +96,12 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
 
    private Boolean sendToDLAOnNoRoute = null;
 
+   private Long slowConsumerThreshold = null;
+
+   private Long slowConsumerCheckPeriod = null;
+
+   private SlowConsumerPolicy slowConsumerPolicy = null;
+
    public AddressSettings(AddressSettings other)
    {
       this.addressFullMessagePolicy = other.addressFullMessagePolicy;
@@ -108,6 +120,9 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
       this.lastValueQueue = other.lastValueQueue;
       this.redistributionDelay = other.redistributionDelay;
       this.sendToDLAOnNoRoute = other.sendToDLAOnNoRoute;
+      this.slowConsumerThreshold = other.slowConsumerThreshold;
+      this.slowConsumerCheckPeriod = other.slowConsumerCheckPeriod;
+      this.slowConsumerPolicy = other.slowConsumerPolicy;
    }
 
    public AddressSettings()
@@ -269,6 +284,37 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
       this.redistributionDelay = redistributionDelay;
    }
 
+   public long getSlowConsumerThreshold()
+   {
+      return slowConsumerThreshold != null ? slowConsumerThreshold : AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD;
+   }
+
+   public void setSlowConsumerThreshold(final long slowConsumerThreshold)
+   {
+      this.slowConsumerThreshold = slowConsumerThreshold;
+   }
+
+   public long getSlowConsumerCheckPeriod()
+   {
+      return slowConsumerCheckPeriod != null ? slowConsumerCheckPeriod : AddressSettings.DEFAULT_SLOW_CONSUMER_CHECK_PERIOD;
+   }
+
+   public void setSlowConsumerCheckPeriod(final long slowConsumerCheckPeriod)
+   {
+      this.slowConsumerCheckPeriod = slowConsumerCheckPeriod;
+   }
+
+   public SlowConsumerPolicy getSlowConsumerPolicy()
+   {
+      return slowConsumerPolicy != null ? slowConsumerPolicy
+         : AddressSettings.DEFAULT_SLOW_CONSUMER_POLICY;
+   }
+
+   public void setSlowConsumerPolicy(final SlowConsumerPolicy slowConsumerPolicy)
+   {
+      this.slowConsumerPolicy = slowConsumerPolicy;
+   }
+
    /**
     * merge 2 objects in to 1
     *
@@ -336,6 +382,18 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
       {
          addressFullMessagePolicy = merged.addressFullMessagePolicy;
       }
+      if (slowConsumerThreshold == null)
+      {
+         slowConsumerThreshold = merged.slowConsumerThreshold;
+      }
+      if (slowConsumerCheckPeriod == null)
+      {
+         slowConsumerCheckPeriod = merged.slowConsumerCheckPeriod;
+      }
+      if (slowConsumerPolicy == null)
+      {
+         slowConsumerPolicy = merged.slowConsumerPolicy;
+      }
    }
 
    @Override
@@ -381,14 +439,29 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
       redistributionDelay = BufferHelper.readNullableLong(buffer);
 
       sendToDLAOnNoRoute = BufferHelper.readNullableBoolean(buffer);
+
+      slowConsumerThreshold = BufferHelper.readNullableLong(buffer);
+
+      slowConsumerCheckPeriod = BufferHelper.readNullableLong(buffer);
+
+      policyStr = buffer.readNullableSimpleString();
+
+      if (policyStr != null)
+      {
+         slowConsumerPolicy = SlowConsumerPolicy.valueOf(policyStr.toString());
+      }
+      else
+      {
+         slowConsumerPolicy = null;
+      }
    }
 
    @Override
    public int getEncodeSize()
    {
 
-      return BufferHelper.sizeOfNullableSimpleString(addressFullMessagePolicy != null ? addressFullMessagePolicy.toString()
-                                                        : null) + BufferHelper.sizeOfNullableLong(maxSizeBytes) +
+      return BufferHelper.sizeOfNullableSimpleString(addressFullMessagePolicy != null ? addressFullMessagePolicy.toString() : null) +
+         BufferHelper.sizeOfNullableLong(maxSizeBytes) +
          BufferHelper.sizeOfNullableLong(pageSizeBytes) +
          BufferHelper.sizeOfNullableInteger(pageMaxCache) +
          BufferHelper.sizeOfNullableBoolean(dropMessagesWhenFull) +
@@ -402,7 +475,10 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
          BufferHelper.sizeOfNullableLong(expiryDelay) +
          BufferHelper.sizeOfNullableBoolean(lastValueQueue) +
          BufferHelper.sizeOfNullableLong(redistributionDelay) +
-         BufferHelper.sizeOfNullableBoolean(sendToDLAOnNoRoute);
+         BufferHelper.sizeOfNullableBoolean(sendToDLAOnNoRoute) +
+         BufferHelper.sizeOfNullableLong(slowConsumerCheckPeriod) +
+         BufferHelper.sizeOfNullableLong(slowConsumerThreshold) +
+         BufferHelper.sizeOfNullableSimpleString(slowConsumerPolicy != null ? slowConsumerPolicy.toString() : null);
    }
 
    @Override
@@ -440,6 +516,12 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
       BufferHelper.writeNullableLong(buffer, redistributionDelay);
 
       BufferHelper.writeNullableBoolean(buffer, sendToDLAOnNoRoute);
+
+      BufferHelper.writeNullableLong(buffer, slowConsumerThreshold);
+
+      BufferHelper.writeNullableLong(buffer, slowConsumerCheckPeriod);
+
+      buffer.writeNullableSimpleString(slowConsumerPolicy != null ? new SimpleString(slowConsumerPolicy.toString()) : null);
    }
 
    /* (non-Javadoc)
@@ -467,6 +549,9 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
       result = prime * result + ((maxRedeliveryDelay == null) ? 0 : maxRedeliveryDelay.hashCode());
       result = prime * result + ((redistributionDelay == null) ? 0 : redistributionDelay.hashCode());
       result = prime * result + ((sendToDLAOnNoRoute == null) ? 0 : sendToDLAOnNoRoute.hashCode());
+      result = prime * result + ((slowConsumerThreshold == null) ? 0 : slowConsumerThreshold.hashCode());
+      result = prime * result + ((slowConsumerCheckPeriod == null) ? 0 : slowConsumerCheckPeriod.hashCode());
+      result = prime * result + ((slowConsumerPolicy == null) ? 0 : slowConsumerPolicy.hashCode());
       return result;
    }
 
@@ -595,6 +680,27 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
       }
       else if (!sendToDLAOnNoRoute.equals(other.sendToDLAOnNoRoute))
          return false;
+      if (slowConsumerThreshold == null)
+      {
+         if (other.slowConsumerThreshold != null)
+            return false;
+      }
+      else if (!slowConsumerThreshold.equals(other.slowConsumerThreshold))
+         return false;
+      if (slowConsumerCheckPeriod == null)
+      {
+         if (other.slowConsumerCheckPeriod != null)
+            return false;
+      }
+      else if (!slowConsumerCheckPeriod.equals(other.slowConsumerCheckPeriod))
+         return false;
+      if (slowConsumerPolicy == null)
+      {
+         if (other.slowConsumerPolicy != null)
+            return false;
+      }
+      else if (!slowConsumerPolicy.equals(other.slowConsumerPolicy))
+         return false;
       return true;
    }
 
@@ -635,6 +741,12 @@ public class AddressSettings implements Mergeable<AddressSettings>, Serializable
          redistributionDelay +
          ", sendToDLAOnNoRoute=" +
          sendToDLAOnNoRoute +
+         ", slowConsumerThreshold=" +
+         slowConsumerThreshold +
+         ", slowConsumerCheckPeriod=" +
+         slowConsumerCheckPeriod +
+         ", slowConsumerPolicy=" +
+         slowConsumerPolicy +
          "]";
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/settings/impl/Match.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/settings/impl/Match.java b/hornetq-server/src/main/java/org/hornetq/core/settings/impl/Match.java
index 3537160..f4eb5b0 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/settings/impl/Match.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/settings/impl/Match.java
@@ -27,7 +27,9 @@ public class Match<T>
 
    public static final String WILDCARD = "#";
 
-   private static final String WILDCARD_REPLACEMENT = ".+";
+   public static final String DOT_WILDCARD = ".#";
+
+   private static final String WILDCARD_REPLACEMENT = ".*";
 
    private static final String DOT = ".";
 
@@ -50,9 +52,14 @@ public class Match<T>
       }
       else
       {
+         // this is to match with what's documented
+         actMatch = actMatch.replace(DOT_WILDCARD, WILDCARD);
+
          actMatch = actMatch.replace(Match.DOT, Match.DOT_REPLACEMENT);
-         actMatch = actMatch.replace(Match.WILDCARD, Match.WILDCARD_REPLACEMENT);
          actMatch = actMatch.replace(Match.WORD_WILDCARD, Match.WORD_WILDCARD_REPLACEMENT);
+
+         // this one has to be done by last as we are using .* and it could be replaced wrongly
+         actMatch = actMatch.replace(Match.WILDCARD, Match.WILDCARD_REPLACEMENT);
       }
       pattern = Pattern.compile(actMatch);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/settings/impl/SlowConsumerPolicy.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/settings/impl/SlowConsumerPolicy.java b/hornetq-server/src/main/java/org/hornetq/core/settings/impl/SlowConsumerPolicy.java
new file mode 100644
index 0000000..a16b02d
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/settings/impl/SlowConsumerPolicy.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.settings.impl;
+
+/**
+ * A SlowConsumerPolicy
+ *
+ * @author Justin Bertram
+ *
+ */
+public enum SlowConsumerPolicy
+{
+   KILL, NOTIFY;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/transaction/Transaction.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/transaction/Transaction.java b/hornetq-server/src/main/java/org/hornetq/core/transaction/Transaction.java
index 6044d13..1010d35 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/transaction/Transaction.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/transaction/Transaction.java
@@ -17,6 +17,8 @@ import java.util.List;
 import javax.transaction.xa.Xid;
 
 import org.hornetq.api.core.HornetQException;
+import org.hornetq.core.server.Queue;
+import org.hornetq.core.server.impl.RefsOperation;
 
 /**
  * A HornetQ internal transaction
@@ -70,4 +72,6 @@ public interface Transaction
    void setContainsPersistent();
 
    void setTimeout(int timeout);
+
+   RefsOperation createRefsOperation(Queue queue);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/transaction/TransactionFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/transaction/TransactionFactory.java b/hornetq-server/src/main/java/org/hornetq/core/transaction/TransactionFactory.java
new file mode 100644
index 0000000..bd6db6b
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/transaction/TransactionFactory.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.transaction;
+
+import org.hornetq.core.persistence.StorageManager;
+
+import javax.transaction.xa.Xid;
+
+/**
+ * Created by andy on 22/07/14.
+ */
+public interface TransactionFactory
+{
+   Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/BindingsTransactionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/BindingsTransactionImpl.java b/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/BindingsTransactionImpl.java
index bc11138..bcb32a2 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/BindingsTransactionImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/BindingsTransactionImpl.java
@@ -13,6 +13,8 @@
 package org.hornetq.core.transaction.impl;
 
 import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.server.Queue;
+import org.hornetq.core.server.impl.RefsOperation;
 
 /**
  * A BindingsTransactionImpl
@@ -48,4 +50,9 @@ public class BindingsTransactionImpl extends TransactionImpl
       }
    }
 
+   @Override
+   public RefsOperation createRefsOperation(Queue queue)
+   {
+      return null;
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/TransactionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/TransactionImpl.java b/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/TransactionImpl.java
index bdef73e..fe050fe 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/TransactionImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/transaction/impl/TransactionImpl.java
@@ -26,6 +26,7 @@
 package org.hornetq.core.transaction.impl;
 
 import javax.transaction.xa.Xid;
+
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
@@ -34,6 +35,8 @@ import org.hornetq.api.core.HornetQException;
 import org.hornetq.core.journal.IOAsyncTask;
 import org.hornetq.core.persistence.StorageManager;
 import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.Queue;
+import org.hornetq.core.server.impl.RefsOperation;
 import org.hornetq.core.transaction.Transaction;
 import org.hornetq.core.transaction.TransactionOperation;
 
@@ -76,7 +79,7 @@ public class TransactionImpl implements Transaction
 
       xid = null;
 
-      id = storageManager.generateUniqueID();
+      id = storageManager.generateID();
 
       createTime = System.currentTimeMillis();
 
@@ -89,7 +92,7 @@ public class TransactionImpl implements Transaction
 
       xid = null;
 
-      id = storageManager.generateUniqueID();
+      id = storageManager.generateID();
 
       createTime = System.currentTimeMillis();
    }
@@ -100,7 +103,7 @@ public class TransactionImpl implements Transaction
 
       this.xid = xid;
 
-      id = storageManager.generateUniqueID();
+      id = storageManager.generateID();
 
       createTime = System.currentTimeMillis();
 
@@ -136,6 +139,12 @@ public class TransactionImpl implements Transaction
       this.timeoutSeconds = timeout;
    }
 
+   @Override
+   public RefsOperation createRefsOperation(Queue queue)
+   {
+      return new RefsOperation(queue, storageManager);
+   }
+
    public long getID()
    {
       return id;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/MessageConverter.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/MessageConverter.java b/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/MessageConverter.java
new file mode 100644
index 0000000..b031b31
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/MessageConverter.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.spi.core.protocol;
+
+import org.hornetq.core.server.ServerMessage;
+
+/**
+ * @author Clebert Suconic
+ */
+// TODO: use this interface properly on OpenWire
+public interface MessageConverter
+{
+   ServerMessage inbound(Object messageInbound) throws Exception;
+
+   Object outbound(ServerMessage messageOutbound, int deliveryCount) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/ProtocolManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/ProtocolManager.java b/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/ProtocolManager.java
index 002f503..125b17c 100644
--- a/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/ProtocolManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/ProtocolManager.java
@@ -35,5 +35,12 @@ public interface ProtocolManager
 
    boolean isProtocol(byte[] array);
 
+   /**
+    * Gets the Message Converter towards HornetQ.
+    * Notice this being null means no need to convert
+    * @return
+    */
+   MessageConverter getConverter();
+
    void handshake(NettyServerConnection connection, HornetQBuffer buffer);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/SessionCallback.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/SessionCallback.java b/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/SessionCallback.java
index 9660ec1..d91af22 100644
--- a/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/SessionCallback.java
+++ b/hornetq-server/src/main/java/org/hornetq/spi/core/protocol/SessionCallback.java
@@ -13,6 +13,7 @@
 package org.hornetq.spi.core.protocol;
 
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.server.ServerConsumer;
 import org.hornetq.core.server.ServerMessage;
 import org.hornetq.spi.core.remoting.ReadyListener;
 
@@ -25,15 +26,18 @@ import org.hornetq.spi.core.remoting.ReadyListener;
  */
 public interface SessionCallback
 {
+   /** This one gives a chance for Proton to have its own flow control. */
+   boolean hasCredits(ServerConsumer consumerID);
+
    void sendProducerCreditsMessage(int credits, SimpleString address);
 
    void sendProducerCreditsFailMessage(int credits, SimpleString address);
 
-   int sendMessage(ServerMessage message, long consumerID, int deliveryCount);
+   int sendMessage(ServerMessage message, ServerConsumer consumerID, int deliveryCount);
 
-   int sendLargeMessage(ServerMessage message, long consumerID, long bodySize, int deliveryCount);
+   int sendLargeMessage(ServerMessage message, ServerConsumer consumerID, long bodySize, int deliveryCount);
 
-   int sendLargeMessageContinuation(long consumerID, byte[] body, boolean continues, boolean requiresResponse);
+   int sendLargeMessageContinuation(ServerConsumer consumerID, byte[] body, boolean continues, boolean requiresResponse);
 
    void closed();
 
@@ -41,5 +45,5 @@ public interface SessionCallback
 
    void removeReadyListener(ReadyListener listener);
 
-   void disconnect(long consumerId, String queueName);
+   void disconnect(ServerConsumer consumerId, String queueName);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/resources/META-INF/services/org/hornetq/security/basic-security
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/resources/META-INF/services/org/hornetq/security/basic-security b/hornetq-server/src/main/resources/META-INF/services/org/hornetq/security/basic-security
new file mode 100644
index 0000000..4b7875a
--- /dev/null
+++ b/hornetq-server/src/main/resources/META-INF/services/org/hornetq/security/basic-security
@@ -0,0 +1,13 @@
+## ---------------------------------------------------------------------------
+## Copyright 2005-2014 Red Hat, Inc.
+## Red Hat licenses this file to you under the Apache License, version
+## 2.0 (the "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##    http://www.apache.org/licenses/LICENSE-2.0
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+## implied.  See the License for the specific language governing
+## permissions and limitations under the License.
+## ---------------------------------------------------------------------------
+class=org.hornetq.spi.core.security.HornetQSecurityManagerImpl
\ No newline at end of file


[42/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageImpl.java
index 71fedc1..cb68c47 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageImpl.java
@@ -20,11 +20,13 @@ import java.nio.ByteBuffer;
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQBuffers;
 import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.HornetQPropertyConversionException;
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.message.BodyEncoder;
 import org.hornetq.core.message.impl.MessageImpl;
+import org.hornetq.reader.MessageUtil;
 
 /**
  *
@@ -37,7 +39,8 @@ import org.hornetq.core.message.impl.MessageImpl;
 public class ClientMessageImpl extends MessageImpl implements ClientMessageInternal
 {
    // added this constant here so that the client package have no dependency on JMS
-   public static final SimpleString REPLYTO_HEADER_NAME = new SimpleString("JMSReplyTo");
+   public static final SimpleString REPLYTO_HEADER_NAME = MessageUtil.REPLYTO_HEADER_NAME;
+
 
    private int deliveryCount;
 
@@ -68,42 +71,54 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
       super(type, durable, expiration, timestamp, priority, initialMessageBufferSize);
    }
 
+   @Override
    public boolean isServerMessage()
    {
       return false;
    }
 
+   @Override
    public void onReceipt(final ClientConsumerInternal consumer)
    {
       this.consumer = consumer;
    }
 
-   public void setDeliveryCount(final int deliveryCount)
+   @Override
+   public ClientMessageImpl setDeliveryCount(final int deliveryCount)
    {
       this.deliveryCount = deliveryCount;
+      return this;
    }
 
+   @Override
    public int getDeliveryCount()
    {
       return deliveryCount;
    }
 
-   public void acknowledge() throws HornetQException
+   @Override
+   public ClientMessageImpl acknowledge() throws HornetQException
    {
       if (consumer != null)
       {
          consumer.acknowledge(this);
       }
+
+      return this;
    }
 
-   public void individualAcknowledge() throws HornetQException
+   @Override
+   public ClientMessageImpl individualAcknowledge() throws HornetQException
    {
       if (consumer != null)
       {
          consumer.individualAcknowledge(this);
       }
+
+      return this;
    }
 
+   @Override
    public int getFlowControlSize()
    {
       if (flowControlSize < 0)
@@ -113,6 +128,7 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
       return flowControlSize;
    }
 
+   @Override
    public void setFlowControlSize(final int flowControlSize)
    {
       this.flowControlSize = flowControlSize;
@@ -121,16 +137,19 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
    /**
     * @return the largeMessage
     */
+   @Override
    public boolean isLargeMessage()
    {
       return false;
    }
 
+   @Override
    public boolean isCompressed()
    {
       return properties.getBooleanProperty(Message.HDR_LARGE_COMPRESSED);
    }
 
+   @Override
    public int getBodySize()
    {
       return buffer.writerIndex() - buffer.readerIndex();
@@ -159,9 +178,10 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
    }
 
    @Override
-   public void setOutputStream(final OutputStream out) throws HornetQException
+   public ClientMessageImpl setOutputStream(final OutputStream out) throws HornetQException
    {
       saveToOutputStream(out);
+      return this;
    }
 
    @Override
@@ -178,6 +198,7 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
    /**
     * @return the bodyInputStream
     */
+   @Override
    public InputStream getBodyInputStream()
    {
       return bodyInputStream;
@@ -186,9 +207,11 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
    /**
     * @param bodyInputStream the bodyInputStream to set
     */
-   public void setBodyInputStream(final InputStream bodyInputStream)
+   @Override
+   public ClientMessageImpl setBodyInputStream(final InputStream bodyInputStream)
    {
       this.bodyInputStream = bodyInputStream;
+      return this;
    }
 
    @Override
@@ -197,21 +220,168 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
       return new DecodingContext();
    }
 
+   @Override
+   public ClientMessageImpl putBooleanProperty(final SimpleString key, final boolean value)
+   {
+      return (ClientMessageImpl) super.putBooleanProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putByteProperty(final SimpleString key, final byte value)
+   {
+      return (ClientMessageImpl) super.putByteProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putBytesProperty(final SimpleString key, final byte[] value)
+   {
+      return (ClientMessageImpl) super.putBytesProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putCharProperty(SimpleString key, char value)
+   {
+      return (ClientMessageImpl) super.putCharProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putCharProperty(String key, char value)
+   {
+      return (ClientMessageImpl) super.putCharProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putShortProperty(final SimpleString key, final short value)
+   {
+      return (ClientMessageImpl) super.putShortProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putIntProperty(final SimpleString key, final int value)
+   {
+      return (ClientMessageImpl) super.putIntProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putLongProperty(final SimpleString key, final long value)
+   {
+      return (ClientMessageImpl) super.putLongProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putFloatProperty(final SimpleString key, final float value)
+   {
+      return (ClientMessageImpl) super.putFloatProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putDoubleProperty(final SimpleString key, final double value)
+   {
+      return (ClientMessageImpl) super.putDoubleProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putStringProperty(final SimpleString key, final SimpleString value)
+   {
+      return (ClientMessageImpl) super.putStringProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putObjectProperty(final SimpleString key, final Object value) throws HornetQPropertyConversionException
+   {
+      return (ClientMessageImpl) super.putObjectProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putObjectProperty(final String key, final Object value) throws HornetQPropertyConversionException
+   {
+      return (ClientMessageImpl) super.putObjectProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putBooleanProperty(final String key, final boolean value)
+   {
+      return (ClientMessageImpl) super.putBooleanProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putByteProperty(final String key, final byte value)
+   {
+      return (ClientMessageImpl) super.putByteProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putBytesProperty(final String key, final byte[] value)
+   {
+      return (ClientMessageImpl) super.putBytesProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putShortProperty(final String key, final short value)
+   {
+      return (ClientMessageImpl) super.putShortProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putIntProperty(final String key, final int value)
+   {
+      return (ClientMessageImpl) super.putIntProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putLongProperty(final String key, final long value)
+   {
+      return (ClientMessageImpl) super.putLongProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putFloatProperty(final String key, final float value)
+   {
+      return (ClientMessageImpl) super.putFloatProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putDoubleProperty(final String key, final double value)
+   {
+      return (ClientMessageImpl) super.putDoubleProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl putStringProperty(final String key, final String value)
+   {
+      return (ClientMessageImpl) super.putStringProperty(key, value);
+   }
+
+   @Override
+   public ClientMessageImpl writeBodyBufferBytes(byte[] bytes)
+   {
+      return (ClientMessageImpl) super.writeBodyBufferBytes(bytes);
+   }
+
+   @Override
+   public ClientMessageImpl writeBodyBufferString(String string)
+   {
+      return (ClientMessageImpl) super.writeBodyBufferString(string);
+   }
+
    private final class DecodingContext implements BodyEncoder
    {
       public DecodingContext()
       {
       }
 
+      @Override
       public void open()
       {
          getBodyBuffer().readerIndex(0);
       }
 
+      @Override
       public void close()
       {
       }
 
+      @Override
       public long getLargeBodySize()
       {
          if (isLargeMessage())
@@ -224,12 +394,14 @@ public class ClientMessageImpl extends MessageImpl implements ClientMessageInter
          }
       }
 
+      @Override
       public int encode(final ByteBuffer bufferRead) throws HornetQException
       {
          HornetQBuffer buffer1 = HornetQBuffers.wrappedBuffer(bufferRead);
          return encode(buffer1, bufferRead.capacity());
       }
 
+      @Override
       public int encode(final HornetQBuffer bufferOut, final int size)
       {
          byte[] bytes = new byte[size];

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageInternal.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageInternal.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageInternal.java
index 132be0f..2a1e291 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageInternal.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientMessageInternal.java
@@ -13,8 +13,8 @@
 
 package org.hornetq.core.client.impl;
 
+import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.ClientMessage;
-import org.hornetq.core.message.impl.MessageInternal;
 import org.hornetq.utils.TypedProperties;
 
 /**
@@ -22,7 +22,7 @@ import org.hornetq.utils.TypedProperties;
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  */
-public interface ClientMessageInternal extends ClientMessage, MessageInternal
+public interface ClientMessageInternal extends ClientMessage
 {
 
    TypedProperties getProperties();
@@ -33,6 +33,8 @@ public interface ClientMessageInternal extends ClientMessage, MessageInternal
    /** Size used for FlowControl */
    void setFlowControlSize(int flowControlSize);
 
+   void setAddressTransient(SimpleString address);
+
    void onReceipt(ClientConsumerInternal consumer);
 
    /**

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManager.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManager.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManager.java
index 5b12ade..156d526 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManager.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManager.java
@@ -13,6 +13,7 @@
 package org.hornetq.core.client.impl;
 
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.spi.core.remoting.SessionContext;
 
 /**
  * A ClientProducerCreditManager
@@ -23,7 +24,7 @@ import org.hornetq.api.core.SimpleString;
  */
 public interface ClientProducerCreditManager
 {
-   ClientProducerCredits getCredits(SimpleString address, boolean anon);
+   ClientProducerCredits getCredits(SimpleString address, boolean anon, SessionContext context);
 
    void returnCredits(SimpleString address);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManagerImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManagerImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManagerImpl.java
index f9fab0d..7477543 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManagerImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditManagerImpl.java
@@ -17,6 +17,7 @@ import java.util.LinkedHashMap;
 import java.util.Map;
 
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.spi.core.remoting.SessionContext;
 
 /**
  * A ProducerCreditManager
@@ -42,7 +43,7 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana
       this.windowSize = windowSize;
    }
 
-   public synchronized ClientProducerCredits getCredits(final SimpleString address, final boolean anon)
+   public synchronized ClientProducerCredits getCredits(final SimpleString address, final boolean anon, SessionContext context)
    {
       if (windowSize == -1)
       {
@@ -84,7 +85,7 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana
          // while this is still sending requests causing a dead lock
          if (needInit)
          {
-            credits.init();
+            credits.init(context);
          }
 
          return credits;
@@ -202,7 +203,7 @@ public class ClientProducerCreditManagerImpl implements ClientProducerCreditMana
          return false;
       }
 
-      public void init()
+      public void init(SessionContext ctx)
       {
       }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCredits.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCredits.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCredits.java
index a1eeafc..f4398f1 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCredits.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCredits.java
@@ -13,6 +13,7 @@
 package org.hornetq.core.client.impl;
 
 import org.hornetq.api.core.HornetQException;
+import org.hornetq.spi.core.remoting.SessionContext;
 
 /**
  * A ClientProducerCredits
@@ -31,7 +32,7 @@ public interface ClientProducerCredits
 
    boolean isBlocked();
 
-   void init();
+   void init(SessionContext sessionContext);
 
    void reset();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditsImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditsImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditsImpl.java
index 4deb64d..3290f27 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditsImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerCreditsImpl.java
@@ -16,6 +16,7 @@ import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.client.HornetQClientMessageBundle;
+import org.hornetq.spi.core.remoting.SessionContext;
 
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
@@ -47,6 +48,8 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits
 
    private boolean serverRespondedWithFail;
 
+   private SessionContext sessionContext;
+
    public ClientProducerCreditsImpl(final ClientSessionInternal session,
                                     final SimpleString address,
                                     final int windowSize)
@@ -62,11 +65,15 @@ public class ClientProducerCreditsImpl implements ClientProducerCredits
       semaphore = new Semaphore(0, false);
    }
 
-   public void init()
+   public void init(SessionContext sessionContext)
    {
       // We initial request twice as many credits as we request in subsequent requests
       // This allows the producer to keep sending as more arrive, minimising pauses
       checkCredits(windowSize);
+
+      this.sessionContext = sessionContext;
+
+      this.sessionContext.linkFlowControl(address, this);
    }
 
    public void acquireCredits(final int credits) throws InterruptedException, HornetQException

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerImpl.java
index 71e6b8f..ac12955 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientProducerImpl.java
@@ -326,7 +326,7 @@ public class ClientProducerImpl implements ClientProducerInternal
          throw new HornetQInterruptedException(e);
       }
 
-      sessionContext.sendFullMessage(msgI, sendBlocking, handler);
+      sessionContext.sendFullMessage(msgI, sendBlocking, handler, address);
    }
 
    private void checkClosed() throws HornetQException

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java
index c9736d5..8660a2d 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryImpl.java
@@ -20,7 +20,6 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.Executor;
 import java.util.concurrent.Future;
@@ -45,8 +44,6 @@ import org.hornetq.api.core.client.SessionFailureListener;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.protocol.core.CoreRemotingConnection;
-import org.hornetq.core.protocol.core.impl.HornetQClientProtocolManager;
-import org.hornetq.core.protocol.core.impl.PacketDecoder;
 import org.hornetq.core.remoting.FailureListener;
 import org.hornetq.core.server.HornetQComponent;
 import org.hornetq.spi.core.protocol.RemotingConnection;
@@ -56,7 +53,7 @@ import org.hornetq.spi.core.remoting.Connection;
 import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener;
 import org.hornetq.spi.core.remoting.Connector;
 import org.hornetq.spi.core.remoting.ConnectorFactory;
-import org.hornetq.spi.core.remoting.ProtocolResponseHandler;
+import org.hornetq.spi.core.remoting.TopologyResponseHandler;
 import org.hornetq.spi.core.remoting.SessionContext;
 import org.hornetq.utils.ClassloadingUtil;
 import org.hornetq.utils.ConcurrentHashSet;
@@ -69,15 +66,11 @@ import org.hornetq.utils.UUIDGenerator;
 /**
  * @author Tim Fox
  * @author Clebert Suconic
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 
 public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, ConnectionLifeCycleListener
 {
-
-
-   // TODO use the factory here
-   protected ClientProtocolManager clientProtocolManager = new HornetQClientProtocolManager(this);
-
    // Constants
    // ------------------------------------------------------------------------------------
 
@@ -90,6 +83,8 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
 
    private final ServerLocatorInternal serverLocator;
 
+   private final ClientProtocolManager clientProtocolManager;
+
    private TransportConfiguration connectorConfig;
 
    private TransportConfiguration backupConfig;
@@ -159,7 +154,6 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
 
    private String liveNodeID;
 
-
    public ClientSessionFactoryImpl(final ServerLocatorInternal serverLocator,
                                    final TransportConfiguration connectorConfig,
                                    final long callTimeout,
@@ -173,18 +167,21 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
                                    final Executor threadPool,
                                    final ScheduledExecutorService scheduledThreadPool,
                                    final List<Interceptor> incomingInterceptors,
-                                   final List<Interceptor> outgoingInterceptors,
-                                   PacketDecoder packetDecoder)
+                                   final List<Interceptor> outgoingInterceptors)
    {
       createTrace = new Exception();
 
       this.serverLocator = serverLocator;
 
+      this.clientProtocolManager = serverLocator.newProtocolManager();
+
+      this.clientProtocolManager.setSessionFactory(this);
+
       this.connectorConfig = connectorConfig;
 
       connectorFactory = instantiateConnectorFactory(connectorConfig.getFactoryClassName());
 
-      checkTransportKeys(connectorFactory, connectorConfig.getParams());
+      checkTransportKeys(connectorFactory, connectorConfig);
 
       this.callTimeout = callTimeout;
 
@@ -227,10 +224,6 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
 
       confirmationWindowWarning = new ConfirmationWindowWarning(serverLocator.getConfirmationWindowSize() < 0);
 
-
-      // TODO : Get rid of this / encapsulate it through the ClientProtocolManager (create a ExchangeServerProtocol for instance)
-      ((HornetQClientProtocolManager) clientProtocolManager).replacePacketDecoder(packetDecoder);
-
    }
 
    public void disableFinalizeCheck()
@@ -281,7 +274,8 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
                                                            this,
                                                            closeExecutor,
                                                            threadPool,
-                                                           scheduledThreadPool);
+                                                           scheduledThreadPool,
+                                                           clientProtocolManager);
       }
 
       if (localConnector.isEquivalent(live.getParams()) && backUp != null && !localConnector.isEquivalent(backUp.getParams()))
@@ -472,9 +466,10 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
       return listeners.remove(listener);
    }
 
-   public void addFailoverListener(FailoverEventListener listener)
+   public ClientSessionFactoryImpl addFailoverListener(FailoverEventListener listener)
    {
       failoverListeners.add(listener);
+      return this;
    }
 
    public boolean removeFailoverListener(FailoverEventListener listener)
@@ -645,7 +640,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
          {
 
 
-            if (clientProtocolManager.cleanupBeforeFailover())
+            if (clientProtocolManager.cleanupBeforeFailover(me))
             {
 
 
@@ -677,7 +672,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
 
                connector = null;
 
-               reconnectSessions(oldConnection, reconnectAttempts);
+               reconnectSessions(oldConnection, reconnectAttempts, me);
 
                if (oldConnection != null)
                {
@@ -785,8 +780,6 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
                                                             orderedExecutorFactory.getExecutor(),
                                                             orderedExecutorFactory.getExecutor());
 
-      context.setSession(session);
-
       synchronized (sessions)
       {
          if (closed || !clientProtocolManager.isAlive())
@@ -859,7 +852,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
    /*
     * Re-attach sessions all pre-existing sessions to the new remoting connection
     */
-   private void reconnectSessions(final RemotingConnection oldConnection, final int reconnectAttempts)
+   private void reconnectSessions(final RemotingConnection oldConnection, final int reconnectAttempts, final HornetQException cause)
    {
       HashSet<ClientSessionInternal> sessionsToFailover;
       synchronized (sessions)
@@ -906,7 +899,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
 
       for (ClientSessionInternal session : sessionsToFailover)
       {
-         session.handleFailover(connection);
+         session.handleFailover(connection, cause);
       }
    }
 
@@ -1111,25 +1104,26 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
 
    protected void schedulePing()
    {
-      if (clientFailureCheckPeriod != -1)
+      if (pingerFuture == null)
       {
-         if (pingerFuture == null)
-         {
-            pingRunnable = new ClientSessionFactoryImpl.PingRunnable();
+         pingRunnable = new ClientSessionFactoryImpl.PingRunnable();
 
+         if (clientFailureCheckPeriod != -1)
+         {
             pingerFuture = scheduledThreadPool.scheduleWithFixedDelay(new ClientSessionFactoryImpl.ActualScheduledPinger(pingRunnable),
                                                                       0,
                                                                       clientFailureCheckPeriod,
                                                                       TimeUnit.MILLISECONDS);
-            // To make sure the first ping will be sent
-            pingRunnable.send();
-         }
-         // send a ping every time we create a new remoting connection
-         // to set up its TTL on the server side
-         else
-         {
-            pingRunnable.run();
          }
+
+         // To make sure the first ping will be sent
+         pingRunnable.send();
+      }
+      // send a ping every time we create a new remoting connection
+      // to set up its TTL on the server side
+      else
+      {
+         pingRunnable.run();
       }
    }
 
@@ -1262,14 +1256,15 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
                                               this,
                                               closeExecutor,
                                               threadPool,
-                                              scheduledThreadPool);
+                                              scheduledThreadPool,
+                                              clientProtocolManager);
    }
 
-   private void checkTransportKeys(final ConnectorFactory factory, final Map<String, Object> params)
+   private void checkTransportKeys(final ConnectorFactory factory, final TransportConfiguration tc)
    {
-      if (params != null)
+      if (tc.getParams() != null)
       {
-         Set<String> invalid = ConfigurationHelper.checkKeys(factory.getAllowableProperties(), params.keySet());
+         Set<String> invalid = ConfigurationHelper.checkKeys(factory.getAllowableProperties(), tc.getParams().keySet());
 
          if (!invalid.isEmpty())
          {
@@ -1282,7 +1277,6 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
       }
    }
 
-
    /**
     * It will connect to either live or backup accordingly to the current configurations
     * it will also switch to backup case it can't connect to live and there's a backup configured
@@ -1535,7 +1529,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
       RemotingConnection newConnection = clientProtocolManager.connect(transportConnection, callTimeout,
                                                                        callFailoverTimeout, incomingInterceptors,
                                                                        outgoingInterceptors,
-                                                                       new SessionFactoryProtocolHandler());
+                                                                       new SessionFactoryTopologyHandler());
 
       newConnection.addFailureListener(new DelegatingFailureListener(newConnection.getID()));
 
@@ -1566,8 +1560,13 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
       }
    }
 
+   @Override
+   public String getLiveNodeId()
+   {
+      return liveNodeID;
+   }
 
-   class SessionFactoryProtocolHandler implements ProtocolResponseHandler
+   class SessionFactoryTopologyHandler implements TopologyResponseHandler
    {
 
       @Override
@@ -1607,5 +1606,4 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
          serverLocator.notifyNodeDown(eventTime, nodeID);
       }
    }
-
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryInternal.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryInternal.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryInternal.java
index 43afd66..e09823d 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryInternal.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionFactoryInternal.java
@@ -24,6 +24,7 @@ import org.hornetq.utils.ConfirmationWindowWarning;
  * A ClientSessionFactoryInternal
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  *
  */
 public interface ClientSessionFactoryInternal extends ClientSessionFactory
@@ -36,6 +37,8 @@ public interface ClientSessionFactoryInternal extends ClientSessionFactory
 
    void disableFinalizeCheck();
 
+   String getLiveNodeId();
+
    // for testing
 
    int numConnections();
@@ -56,6 +59,5 @@ public interface ClientSessionFactoryInternal extends ClientSessionFactory
 
    ConfirmationWindowWarning getConfirmationWindowWarning();
 
-
    Lock lockFailover();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionImpl.java
index 3975223..197d80c 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionImpl.java
@@ -40,6 +40,7 @@ import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.remoting.FailureListener;
 import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.remoting.ConsumerContext;
 import org.hornetq.spi.core.remoting.SessionContext;
 import org.hornetq.utils.ConfirmationWindowWarning;
 import org.hornetq.utils.TokenBucketLimiterImpl;
@@ -51,6 +52,7 @@ import org.hornetq.utils.XidCodecSupport;
  * @author <a href="mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  * @author <a href="mailto:ataylor@redhat.com">Andy Taylor</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public final class ClientSessionImpl implements ClientSessionInternal, FailureListener
 {
@@ -77,7 +79,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
    private final Set<ClientProducerInternal> producers = new HashSet<ClientProducerInternal>();
 
    // Consumers must be an ordered map so if we fail we recreate them in the same order with the same ids
-   private final Map<Long, ClientConsumerInternal> consumers = new LinkedHashMap<Long, ClientConsumerInternal>();
+   private final Map<ConsumerContext, ClientConsumerInternal> consumers = new LinkedHashMap<ConsumerContext, ClientConsumerInternal>();
 
    private volatile boolean closed;
 
@@ -223,6 +225,8 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
 
       this.sessionContext = sessionContext;
 
+      sessionContext.setSession(this);
+
       confirmationWindowWarning = sessionFactory.getConfirmationWindowWarning();
    }
 
@@ -652,7 +656,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
       }
    }
 
-   public void start() throws HornetQException
+   public ClientSessionImpl start() throws HornetQException
    {
       checkClosed();
 
@@ -667,6 +671,8 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
 
          started = true;
       }
+
+      return this;
    }
 
    public void stop() throws HornetQException
@@ -721,6 +727,12 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
       return inClose;
    }
 
+   @Override
+   public String getNodeId()
+   {
+      return sessionFactory.getLiveNodeId();
+   }
+
    // ClientSessionInternal implementation
    // ------------------------------------------------------------
 
@@ -812,7 +824,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
    {
       synchronized (consumers)
       {
-         consumers.put(consumer.getID(), consumer);
+         consumers.put(consumer.getConsumerContext(), consumer);
       }
    }
 
@@ -828,7 +840,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
    {
       synchronized (consumers)
       {
-         consumers.remove(consumer.getID());
+         consumers.remove(consumer.getConsumerContext());
       }
    }
 
@@ -840,7 +852,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
       }
    }
 
-   public void handleReceiveMessage(final long consumerID, final ClientMessageInternal message) throws Exception
+   public void handleReceiveMessage(final ConsumerContext consumerID, final ClientMessageInternal message) throws Exception
    {
       ClientConsumerInternal consumer = getConsumer(consumerID);
 
@@ -850,7 +862,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
       }
    }
 
-   public void handleReceiveLargeMessage(final long consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception
+   public void handleReceiveLargeMessage(final ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception
    {
       ClientConsumerInternal consumer = getConsumer(consumerID);
 
@@ -860,7 +872,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
       }
    }
 
-   public void handleReceiveContinuation(final long consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception
+   public void handleReceiveContinuation(final ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception
    {
       ClientConsumerInternal consumer = getConsumer(consumerID);
 
@@ -871,9 +883,9 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
    }
 
    @Override
-   public void handleConsumerDisconnect(long consumerID) throws HornetQException
+   public void handleConsumerDisconnect(ConsumerContext context) throws HornetQException
    {
-      final ClientConsumerInternal consumer = getConsumer(consumerID);
+      final ClientConsumerInternal consumer = getConsumer(context);
 
       if (consumer != null)
       {
@@ -944,9 +956,10 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
       doCleanup(failingOver);
    }
 
-   public void setSendAcknowledgementHandler(final SendAcknowledgementHandler handler)
+   public ClientSessionImpl setSendAcknowledgementHandler(final SendAcknowledgementHandler handler)
    {
       sessionContext.setSendAcknowledgementHandler(handler);
+      return this;
    }
 
    public void preHandleFailover(RemotingConnection connection)
@@ -959,7 +972,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
 
    // Needs to be synchronized to prevent issues with occurring concurrently with close()
 
-   public void handleFailover(final RemotingConnection backupConnection)
+   public void handleFailover(final RemotingConnection backupConnection, HornetQException cause)
    {
       synchronized (this)
       {
@@ -1008,7 +1021,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
                                                  minLargeMessageSize, xa, autoCommitSends,
                                                  autoCommitAcks, preAcknowledge, defaultAddress);
 
-                  for (Map.Entry<Long, ClientConsumerInternal> entryx : consumers.entrySet())
+                  for (Map.Entry<ConsumerContext, ClientConsumerInternal> entryx : consumers.entrySet())
                   {
 
                      ClientConsumerInternal consumerInternal = entryx.getValue();
@@ -1043,7 +1056,7 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
                   resetCreditManager = true;
                }
 
-               sessionContext.returnBlocking();
+               sessionContext.returnBlocking(cause);
             }
          }
          catch (Throwable t)
@@ -1137,7 +1150,9 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
 
    public synchronized ClientProducerCredits getCredits(final SimpleString address, final boolean anon)
    {
-      return producerCreditManager.getCredits(address, anon);
+      ClientProducerCredits credits = producerCreditManager.getCredits(address, anon, sessionContext);
+
+      return credits;
    }
 
    public void returnCredits(final SimpleString address)
@@ -1343,21 +1358,47 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
    {
       checkXA();
 
-      if (!(xares instanceof ClientSessionInternal))
+      if (forceNotSameRM)
       {
          return false;
       }
 
-      if (forceNotSameRM)
+      ClientSessionInternal other = getSessionInternalFromXAResource(xares);
+
+      if (other == null)
       {
          return false;
       }
 
-      ClientSessionInternal other = (ClientSessionInternal) xares;
+      String liveNodeId = sessionFactory.getLiveNodeId();
+      String otherLiveNodeId = ((ClientSessionFactoryInternal) other.getSessionFactory()).getLiveNodeId();
 
+      if (liveNodeId != null && otherLiveNodeId != null)
+      {
+         return liveNodeId.equals(otherLiveNodeId);
+      }
+
+      //we shouldn't get here, live node id should always be set
       return sessionFactory == other.getSessionFactory();
    }
 
+   private ClientSessionInternal getSessionInternalFromXAResource(final XAResource xares)
+   {
+      if (xares == null)
+      {
+         return null;
+      }
+      if (xares instanceof ClientSessionInternal)
+      {
+         return (ClientSessionInternal) xares;
+      }
+      else if (xares instanceof HornetQXAResource)
+      {
+         return getSessionInternalFromXAResource(((HornetQXAResource)xares).getResource());
+      }
+      return null;
+   }
+
    public int prepare(final Xid xid) throws XAException
    {
       checkXA();
@@ -1732,15 +1773,11 @@ public final class ClientSessionImpl implements ClientSessionInternal, FailureLi
       }
    }
 
-   /**
-    * @param consumerID
-    * @return
-    */
-   private ClientConsumerInternal getConsumer(final long consumerID)
+   private ClientConsumerInternal getConsumer(final ConsumerContext consumerContext)
    {
       synchronized (consumers)
       {
-         ClientConsumerInternal consumer = consumers.get(consumerID);
+         ClientConsumerInternal consumer = consumers.get(consumerContext);
          return consumer;
       }
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionInternal.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionInternal.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionInternal.java
index 67ea4fa..a05e6a3 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionInternal.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ClientSessionInternal.java
@@ -19,6 +19,7 @@ import org.hornetq.api.core.client.ClientConsumer;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.SendAcknowledgementHandler;
 import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.remoting.ConsumerContext;
 
 /**
  * A ClientSessionInternal
@@ -49,17 +50,17 @@ public interface ClientSessionInternal extends ClientSession
 
    void removeProducer(ClientProducerInternal producer);
 
-   void handleReceiveMessage(long consumerID, ClientMessageInternal message) throws Exception;
+   void handleReceiveMessage(ConsumerContext consumerID, ClientMessageInternal message) throws Exception;
 
-   void handleReceiveLargeMessage(long consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception;
+   void handleReceiveLargeMessage(ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception;
 
-   void handleReceiveContinuation(long consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception;
+   void handleReceiveContinuation(ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception;
 
-   void handleConsumerDisconnect(long consumerID) throws HornetQException;
+   void handleConsumerDisconnect(ConsumerContext consumerContext) throws HornetQException;
 
    void preHandleFailover(RemotingConnection connection);
 
-   void handleFailover(RemotingConnection backupConnection);
+   void handleFailover(RemotingConnection backupConnection, HornetQException cause);
 
    RemotingConnection getConnection();
 
@@ -116,4 +117,5 @@ public interface ClientSessionInternal extends ClientSession
 
    boolean isClosing();
 
+   String getNodeId();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/DelegatingSession.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/DelegatingSession.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/DelegatingSession.java
index f7e0c61..5b90f55 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/DelegatingSession.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/DelegatingSession.java
@@ -29,6 +29,7 @@ import org.hornetq.api.core.client.SendAcknowledgementHandler;
 import org.hornetq.api.core.client.SessionFailureListener;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.remoting.ConsumerContext;
 import org.hornetq.utils.ConcurrentHashSet;
 
 /**
@@ -38,6 +39,7 @@ import org.hornetq.utils.ConcurrentHashSet;
  * on GC if it has not already been closed
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class DelegatingSession implements ClientSessionInternal
 {
@@ -388,33 +390,33 @@ public class DelegatingSession implements ClientSessionInternal
       session.preHandleFailover(connection);
    }
 
-   public void handleFailover(final RemotingConnection backupConnection)
+   public void handleFailover(final RemotingConnection backupConnection, HornetQException cause)
    {
-      session.handleFailover(backupConnection);
+      session.handleFailover(backupConnection, cause);
    }
 
    @Override
-   public void handleReceiveMessage(long consumerID, ClientMessageInternal message) throws Exception
+   public void handleReceiveMessage(ConsumerContext consumerID, ClientMessageInternal message) throws Exception
    {
       session.handleReceiveMessage(consumerID, message);
    }
 
    @Override
-   public void handleReceiveLargeMessage(long consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception
+   public void handleReceiveLargeMessage(ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception
    {
       session.handleReceiveLargeMessage(consumerID, clientLargeMessage, largeMessageSize);
    }
 
    @Override
-   public void handleReceiveContinuation(long consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception
+   public void handleReceiveContinuation(ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception
    {
       session.handleReceiveContinuation(consumerID, chunk, flowControlSize, isContinues);
    }
 
    @Override
-   public void handleConsumerDisconnect(long consumerID) throws HornetQException
+   public void handleConsumerDisconnect(ConsumerContext consumerContext) throws HornetQException
    {
-      session.handleConsumerDisconnect(consumerID);
+      session.handleConsumerDisconnect(consumerContext);
    }
 
    public boolean isAutoCommitAcks()
@@ -507,9 +509,10 @@ public class DelegatingSession implements ClientSessionInternal
       session.rollback(xid);
    }
 
-   public void setSendAcknowledgementHandler(final SendAcknowledgementHandler handler)
+   public DelegatingSession setSendAcknowledgementHandler(final SendAcknowledgementHandler handler)
    {
       session.setSendAcknowledgementHandler(handler);
+      return this;
    }
 
    public boolean setTransactionTimeout(final int seconds) throws XAException
@@ -522,9 +525,10 @@ public class DelegatingSession implements ClientSessionInternal
       session.resetIfNeeded();
    }
 
-   public void start() throws HornetQException
+   public DelegatingSession start() throws HornetQException
    {
       session.start();
+      return this;
    }
 
    public void start(final Xid xid, final int flags) throws XAException
@@ -642,4 +646,10 @@ public class DelegatingSession implements ClientSessionInternal
    {
       session.scheduleConfirmation(handler, msg);
    }
+
+   @Override
+   public String getNodeId()
+   {
+      return session.getNodeId();
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/HornetQXAResource.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/HornetQXAResource.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/HornetQXAResource.java
new file mode 100644
index 0000000..e278b8c
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/HornetQXAResource.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.client.impl;
+
+import javax.transaction.xa.XAResource;
+
+public interface HornetQXAResource extends XAResource
+{
+   XAResource getResource();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorImpl.java
index d5612a2..5aa37b8 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorImpl.java
@@ -53,9 +53,10 @@ import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.cluster.DiscoveryEntry;
 import org.hornetq.core.cluster.DiscoveryGroup;
 import org.hornetq.core.cluster.DiscoveryListener;
-import org.hornetq.core.protocol.ClientPacketDecoder;
-import org.hornetq.core.protocol.core.impl.PacketDecoder;
+import org.hornetq.core.protocol.core.impl.HornetQClientProtocolManagerFactory;
 import org.hornetq.core.remoting.FailureListener;
+import org.hornetq.spi.core.remoting.ClientProtocolManager;
+import org.hornetq.spi.core.remoting.ClientProtocolManagerFactory;
 import org.hornetq.spi.core.remoting.Connector;
 import org.hornetq.utils.ClassloadingUtil;
 import org.hornetq.utils.HornetQThreadFactory;
@@ -81,6 +82,10 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
 
    private static final long serialVersionUID = -1615857864410205260L;
 
+
+   // This is the default value
+   private ClientProtocolManagerFactory protocolManagerFactory = HornetQClientProtocolManagerFactory.getInstance();
+
    private final boolean ha;
 
    private boolean finalizeCheck = true;
@@ -208,12 +213,6 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
    * If you need to, make them transient and handle the serialization yourself
    * */
 
-
-   /*
-   * we use the client decoder by default but there are times when we want to use the server packet decoder
-   */
-   private transient PacketDecoder packetDecoder = ClientPacketDecoder.INSTANCE;
-
    private final Exception traceException = new Exception();
 
    // To be called when there are ServerLocator being finalized.
@@ -642,6 +641,28 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       }
    }
 
+
+   public ClientProtocolManager newProtocolManager()
+   {
+      return getProtocolManagerFactory().newProtocolManager();
+   }
+
+   public ClientProtocolManagerFactory getProtocolManagerFactory()
+   {
+      if (protocolManagerFactory == null)
+      {
+         // this could happen over serialization from older versions
+         protocolManagerFactory = HornetQClientProtocolManagerFactory.getInstance();
+      }
+      return protocolManagerFactory;
+   }
+
+   public void setProtocolManagerFactory(ClientProtocolManagerFactory protocolManagerFactory)
+   {
+      this.protocolManagerFactory = protocolManagerFactory;
+   }
+
+
    public void disableFinalizeCheck()
    {
       finalizeCheck = false;
@@ -675,9 +696,10 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return connect(true);
    }
 
-   public void setAfterConnectionInternalListener(AfterConnectInternalListener listener)
+   public ServerLocatorImpl setAfterConnectionInternalListener(AfterConnectInternalListener listener)
    {
       this.afterConnectListener = listener;
+      return this;
    }
 
    public AfterConnectInternalListener getAfterConnectInternalListener()
@@ -736,8 +758,7 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
                                                                           threadPool,
                                                                           scheduledThreadPool,
                                                                           incomingInterceptors,
-                                                                          outgoingInterceptors,
-                                                                          packetDecoder);
+                                                                          outgoingInterceptors);
 
       addToConnecting(factory);
       try
@@ -780,8 +801,7 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
                                                                           threadPool,
                                                                           scheduledThreadPool,
                                                                           incomingInterceptors,
-                                                                          outgoingInterceptors,
-                                                                          packetDecoder);
+                                                                          outgoingInterceptors);
 
       addToConnecting(factory);
       try
@@ -873,8 +893,7 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
                                                       threadPool,
                                                       scheduledThreadPool,
                                                       incomingInterceptors,
-                                                      outgoingInterceptors,
-                                                      packetDecoder);
+                                                      outgoingInterceptors);
                try
                {
                   addToConnecting(factory);
@@ -963,9 +982,10 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return cacheLargeMessagesClient;
    }
 
-   public void setCacheLargeMessagesClient(final boolean cached)
+   public ServerLocatorImpl setCacheLargeMessagesClient(final boolean cached)
    {
       cacheLargeMessagesClient = cached;
+      return this;
    }
 
    public long getClientFailureCheckPeriod()
@@ -973,10 +993,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return clientFailureCheckPeriod;
    }
 
-   public void setClientFailureCheckPeriod(final long clientFailureCheckPeriod)
+   public ServerLocatorImpl setClientFailureCheckPeriod(final long clientFailureCheckPeriod)
    {
       checkWrite();
       this.clientFailureCheckPeriod = clientFailureCheckPeriod;
+      return this;
    }
 
    public long getConnectionTTL()
@@ -984,10 +1005,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return connectionTTL;
    }
 
-   public void setConnectionTTL(final long connectionTTL)
+   public ServerLocatorImpl setConnectionTTL(final long connectionTTL)
    {
       checkWrite();
       this.connectionTTL = connectionTTL;
+      return this;
    }
 
    public long getCallTimeout()
@@ -995,10 +1017,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return callTimeout;
    }
 
-   public void setCallTimeout(final long callTimeout)
+   public ServerLocatorImpl setCallTimeout(final long callTimeout)
    {
       checkWrite();
       this.callTimeout = callTimeout;
+      return this;
    }
 
    public long getCallFailoverTimeout()
@@ -1006,10 +1029,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return callFailoverTimeout;
    }
 
-   public void setCallFailoverTimeout(long callFailoverTimeout)
+   public ServerLocatorImpl setCallFailoverTimeout(long callFailoverTimeout)
    {
       checkWrite();
       this.callFailoverTimeout = callFailoverTimeout;
+      return this;
    }
 
    public int getMinLargeMessageSize()
@@ -1017,10 +1041,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return minLargeMessageSize;
    }
 
-   public void setMinLargeMessageSize(final int minLargeMessageSize)
+   public ServerLocatorImpl setMinLargeMessageSize(final int minLargeMessageSize)
    {
       checkWrite();
       this.minLargeMessageSize = minLargeMessageSize;
+      return this;
    }
 
    public int getConsumerWindowSize()
@@ -1028,10 +1053,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return consumerWindowSize;
    }
 
-   public void setConsumerWindowSize(final int consumerWindowSize)
+   public ServerLocatorImpl setConsumerWindowSize(final int consumerWindowSize)
    {
       checkWrite();
       this.consumerWindowSize = consumerWindowSize;
+      return this;
    }
 
    public int getConsumerMaxRate()
@@ -1039,10 +1065,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return consumerMaxRate;
    }
 
-   public void setConsumerMaxRate(final int consumerMaxRate)
+   public ServerLocatorImpl setConsumerMaxRate(final int consumerMaxRate)
    {
       checkWrite();
       this.consumerMaxRate = consumerMaxRate;
+      return this;
    }
 
    public int getConfirmationWindowSize()
@@ -1050,10 +1077,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return confirmationWindowSize;
    }
 
-   public void setConfirmationWindowSize(final int confirmationWindowSize)
+   public ServerLocatorImpl setConfirmationWindowSize(final int confirmationWindowSize)
    {
       checkWrite();
       this.confirmationWindowSize = confirmationWindowSize;
+      return this;
    }
 
    public int getProducerWindowSize()
@@ -1061,10 +1089,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return producerWindowSize;
    }
 
-   public void setProducerWindowSize(final int producerWindowSize)
+   public ServerLocatorImpl setProducerWindowSize(final int producerWindowSize)
    {
       checkWrite();
       this.producerWindowSize = producerWindowSize;
+      return this;
    }
 
    public int getProducerMaxRate()
@@ -1072,10 +1101,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return producerMaxRate;
    }
 
-   public void setProducerMaxRate(final int producerMaxRate)
+   public ServerLocatorImpl setProducerMaxRate(final int producerMaxRate)
    {
       checkWrite();
       this.producerMaxRate = producerMaxRate;
+      return this;
    }
 
    public boolean isBlockOnAcknowledge()
@@ -1083,10 +1113,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return blockOnAcknowledge;
    }
 
-   public void setBlockOnAcknowledge(final boolean blockOnAcknowledge)
+   public ServerLocatorImpl setBlockOnAcknowledge(final boolean blockOnAcknowledge)
    {
       checkWrite();
       this.blockOnAcknowledge = blockOnAcknowledge;
+      return this;
    }
 
    public boolean isBlockOnDurableSend()
@@ -1094,10 +1125,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return blockOnDurableSend;
    }
 
-   public void setBlockOnDurableSend(final boolean blockOnDurableSend)
+   public ServerLocatorImpl setBlockOnDurableSend(final boolean blockOnDurableSend)
    {
       checkWrite();
       this.blockOnDurableSend = blockOnDurableSend;
+      return this;
    }
 
    public boolean isBlockOnNonDurableSend()
@@ -1105,10 +1137,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return blockOnNonDurableSend;
    }
 
-   public void setBlockOnNonDurableSend(final boolean blockOnNonDurableSend)
+   public ServerLocatorImpl setBlockOnNonDurableSend(final boolean blockOnNonDurableSend)
    {
       checkWrite();
       this.blockOnNonDurableSend = blockOnNonDurableSend;
+      return this;
    }
 
    public boolean isAutoGroup()
@@ -1116,10 +1149,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return autoGroup;
    }
 
-   public void setAutoGroup(final boolean autoGroup)
+   public ServerLocatorImpl setAutoGroup(final boolean autoGroup)
    {
       checkWrite();
       this.autoGroup = autoGroup;
+      return this;
    }
 
    public boolean isPreAcknowledge()
@@ -1127,10 +1161,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return preAcknowledge;
    }
 
-   public void setPreAcknowledge(final boolean preAcknowledge)
+   public ServerLocatorImpl setPreAcknowledge(final boolean preAcknowledge)
    {
       checkWrite();
       this.preAcknowledge = preAcknowledge;
+      return this;
    }
 
    public int getAckBatchSize()
@@ -1138,10 +1173,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return ackBatchSize;
    }
 
-   public void setAckBatchSize(final int ackBatchSize)
+   public ServerLocatorImpl setAckBatchSize(final int ackBatchSize)
    {
       checkWrite();
       this.ackBatchSize = ackBatchSize;
+      return this;
    }
 
    public boolean isUseGlobalPools()
@@ -1149,10 +1185,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return useGlobalPools;
    }
 
-   public void setUseGlobalPools(final boolean useGlobalPools)
+   public ServerLocatorImpl setUseGlobalPools(final boolean useGlobalPools)
    {
       checkWrite();
       this.useGlobalPools = useGlobalPools;
+      return this;
    }
 
    public int getScheduledThreadPoolMaxSize()
@@ -1160,10 +1197,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return scheduledThreadPoolMaxSize;
    }
 
-   public void setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize)
+   public ServerLocatorImpl setScheduledThreadPoolMaxSize(final int scheduledThreadPoolMaxSize)
    {
       checkWrite();
       this.scheduledThreadPoolMaxSize = scheduledThreadPoolMaxSize;
+      return this;
    }
 
    public int getThreadPoolMaxSize()
@@ -1171,10 +1209,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return threadPoolMaxSize;
    }
 
-   public void setThreadPoolMaxSize(final int threadPoolMaxSize)
+   public ServerLocatorImpl setThreadPoolMaxSize(final int threadPoolMaxSize)
    {
       checkWrite();
       this.threadPoolMaxSize = threadPoolMaxSize;
+      return this;
    }
 
    public long getRetryInterval()
@@ -1182,10 +1221,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return retryInterval;
    }
 
-   public void setRetryInterval(final long retryInterval)
+   public ServerLocatorImpl setRetryInterval(final long retryInterval)
    {
       checkWrite();
       this.retryInterval = retryInterval;
+      return this;
    }
 
    public long getMaxRetryInterval()
@@ -1193,10 +1233,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return maxRetryInterval;
    }
 
-   public void setMaxRetryInterval(final long retryInterval)
+   public ServerLocatorImpl setMaxRetryInterval(final long retryInterval)
    {
       checkWrite();
       maxRetryInterval = retryInterval;
+      return this;
    }
 
    public double getRetryIntervalMultiplier()
@@ -1204,10 +1245,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return retryIntervalMultiplier;
    }
 
-   public void setRetryIntervalMultiplier(final double retryIntervalMultiplier)
+   public ServerLocatorImpl setRetryIntervalMultiplier(final double retryIntervalMultiplier)
    {
       checkWrite();
       this.retryIntervalMultiplier = retryIntervalMultiplier;
+      return this;
    }
 
    public int getReconnectAttempts()
@@ -1215,16 +1257,18 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return reconnectAttempts;
    }
 
-   public void setReconnectAttempts(final int reconnectAttempts)
+   public ServerLocatorImpl setReconnectAttempts(final int reconnectAttempts)
    {
       checkWrite();
       this.reconnectAttempts = reconnectAttempts;
+      return this;
    }
 
-   public void setInitialConnectAttempts(int initialConnectAttempts)
+   public ServerLocatorImpl setInitialConnectAttempts(int initialConnectAttempts)
    {
       checkWrite();
       this.initialConnectAttempts = initialConnectAttempts;
+      return this;
    }
 
    public int getInitialConnectAttempts()
@@ -1237,10 +1281,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return this.failoverOnInitialConnection;
    }
 
-   public void setFailoverOnInitialConnection(final boolean failover)
+   public ServerLocatorImpl setFailoverOnInitialConnection(final boolean failover)
    {
       checkWrite();
       this.failoverOnInitialConnection = failover;
+      return this;
    }
 
    public String getConnectionLoadBalancingPolicyClassName()
@@ -1248,10 +1293,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return connectionLoadBalancingPolicyClassName;
    }
 
-   public void setConnectionLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName)
+   public ServerLocatorImpl setConnectionLoadBalancingPolicyClassName(final String loadBalancingPolicyClassName)
    {
       checkWrite();
       connectionLoadBalancingPolicyClassName = loadBalancingPolicyClassName;
+      return this;
    }
 
    public TransportConfiguration[] getStaticTransportConfigurations()
@@ -1272,14 +1318,16 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       addIncomingInterceptor(interceptor);
    }
 
-   public void addIncomingInterceptor(final Interceptor interceptor)
+   public ServerLocatorImpl addIncomingInterceptor(final Interceptor interceptor)
    {
       incomingInterceptors.add(interceptor);
+      return this;
    }
 
-   public void addOutgoingInterceptor(final Interceptor interceptor)
+   public ServerLocatorImpl addOutgoingInterceptor(final Interceptor interceptor)
    {
       outgoingInterceptors.add(interceptor);
+      return this;
    }
 
    @Override
@@ -1304,16 +1352,18 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return initialMessagePacketSize;
    }
 
-   public void setInitialMessagePacketSize(final int size)
+   public ServerLocatorImpl setInitialMessagePacketSize(final int size)
    {
       checkWrite();
       initialMessagePacketSize = size;
+      return this;
    }
 
-   public void setGroupID(final String groupID)
+   public ServerLocatorImpl setGroupID(final String groupID)
    {
       checkWrite();
       this.groupID = groupID;
+      return this;
    }
 
    public String getGroupID()
@@ -1326,9 +1376,10 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return compressLargeMessage;
    }
 
-   public void setCompressLargeMessage(boolean avoid)
+   public ServerLocatorImpl setCompressLargeMessage(boolean avoid)
    {
       this.compressLargeMessage = avoid;
+      return this;
    }
 
    private void checkWrite()
@@ -1348,14 +1399,16 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return initialConnectors.length;
    }
 
-   public void setIdentity(String identity)
+   public ServerLocatorImpl setIdentity(String identity)
    {
       this.identity = identity;
+      return this;
    }
 
-   public void setNodeID(String nodeID)
+   public ServerLocatorImpl setNodeID(String nodeID)
    {
       this.nodeID = nodeID;
+      return this;
    }
 
    public String getNodeID()
@@ -1363,9 +1416,10 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return nodeID;
    }
 
-   public void setClusterConnection(boolean clusterConnection)
+   public ServerLocatorImpl setClusterConnection(boolean clusterConnection)
    {
       this.clusterConnection = clusterConnection;
+      return this;
    }
 
    public boolean isClusterConnection()
@@ -1378,9 +1432,10 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       return clusterTransportConfiguration;
    }
 
-   public void setClusterTransportConfiguration(TransportConfiguration tc)
+   public ServerLocatorImpl setClusterTransportConfiguration(TransportConfiguration tc)
    {
       this.clusterTransportConfiguration = tc;
+      return this;
    }
 
    @Override
@@ -1742,20 +1797,15 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
    }
 
    @Override
-   public void setPacketDecoder(PacketDecoder packetDecoder)
-   {
-      this.packetDecoder = packetDecoder;
-   }
-
-   @Override
    public boolean isConnectable()
    {
       return getNumInitialConnectors() > 0 || getDiscoveryGroupConfiguration() != null;
    }
 
-   public void addClusterTopologyListener(final ClusterTopologyListener listener)
+   public ServerLocatorImpl addClusterTopologyListener(final ClusterTopologyListener listener)
    {
       topology.addClusterTopologyListener(listener);
+      return this;
    }
 
    public void removeClusterTopologyListener(final ClusterTopologyListener listener)
@@ -1802,8 +1852,6 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
       {
          topologyArrayGuard = new String();
       }
-      //is transient so need to create, for compatibility issues
-      packetDecoder = ClientPacketDecoder.INSTANCE;
    }
 
    private final class StaticConnector implements Serializable
@@ -1951,8 +1999,7 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
                                                                                    threadPool,
                                                                                    scheduledThreadPool,
                                                                                    incomingInterceptors,
-                                                                                   outgoingInterceptors,
-                                                                                   packetDecoder);
+                                                                                   outgoingInterceptors);
 
                factory.disableFinalizeCheck();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorInternal.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorInternal.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorInternal.java
index 40c117b..4d8c258 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorInternal.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/ServerLocatorInternal.java
@@ -18,8 +18,8 @@ import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
-import org.hornetq.core.protocol.core.impl.PacketDecoder;
 import org.hornetq.api.core.Pair;
+import org.hornetq.spi.core.remoting.ClientProtocolManager;
 
 /**
  * A ServerLocatorInternal
@@ -36,14 +36,14 @@ public interface ServerLocatorInternal extends ServerLocator
 
    AfterConnectInternalListener getAfterConnectInternalListener();
 
-   void setAfterConnectionInternalListener(AfterConnectInternalListener listener);
+   ServerLocatorInternal setAfterConnectionInternalListener(AfterConnectInternalListener listener);
 
    /** Used to better identify Cluster Connection Locators on logs. To facilitate eventual debugging.
     *
     *  This method used to be on tests interface, but I'm now making it part of the public interface since*/
-   void setIdentity(String identity);
+   ServerLocatorInternal setIdentity(String identity);
 
-   void setNodeID(String nodeID);
+   ServerLocatorInternal setNodeID(String nodeID);
 
    String getNodeID();
 
@@ -70,17 +70,17 @@ public interface ServerLocatorInternal extends ServerLocator
     */
    void notifyNodeDown(long uniqueEventID, String nodeID);
 
-   void setClusterConnection(boolean clusterConnection);
+   ServerLocatorInternal setClusterConnection(boolean clusterConnection);
 
    boolean isClusterConnection();
 
    TransportConfiguration getClusterTransportConfiguration();
 
-   void setClusterTransportConfiguration(TransportConfiguration tc);
+   ServerLocatorInternal setClusterTransportConfiguration(TransportConfiguration tc);
 
    Topology getTopology();
 
-   void setPacketDecoder(PacketDecoder instance);
+   ClientProtocolManager newProtocolManager();
 
    boolean isConnectable();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/Topology.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/Topology.java b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/Topology.java
index 898d194..22f6b90 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/Topology.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/client/impl/Topology.java
@@ -156,8 +156,11 @@ public final class Topology implements Serializable
          TopologyMemberImpl currentMember = getMember(nodeId);
          if (currentMember == null)
          {
-            HornetQClientLogger.LOGGER.debug("There's no live to be updated on backup update, node=" + nodeId + " memberInput=" + memberInput,
-                     new Exception("trace"));
+            if (HornetQClientLogger.LOGGER.isTraceEnabled())
+            {
+               HornetQClientLogger.LOGGER.trace("There's no live to be updated on backup update, node=" + nodeId + " memberInput=" + memberInput,
+                                                new Exception("trace"));
+            }
 
             currentMember = memberInput;
             topology.put(nodeId, currentMember);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/cluster/DiscoveryGroup.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/cluster/DiscoveryGroup.java b/hornetq-core-client/src/main/java/org/hornetq/core/cluster/DiscoveryGroup.java
index c0981a3..43beff4 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/cluster/DiscoveryGroup.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/cluster/DiscoveryGroup.java
@@ -26,7 +26,7 @@ import org.hornetq.api.core.HornetQBuffers;
 import org.hornetq.api.core.HornetQInterruptedException;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.server.HornetQComponent;
 import org.hornetq.core.server.management.Notification;
@@ -118,7 +118,7 @@ public final class DiscoveryGroup implements HornetQComponent
 
          props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name));
 
-         Notification notification = new Notification(nodeID, NotificationType.DISCOVERY_GROUP_STARTED, props);
+         Notification notification = new Notification(nodeID, CoreNotificationType.DISCOVERY_GROUP_STARTED, props);
 
          notificationService.sendNotification(notification);
       }
@@ -170,7 +170,7 @@ public final class DiscoveryGroup implements HornetQComponent
       {
          TypedProperties props = new TypedProperties();
          props.putSimpleStringProperty(new SimpleString("name"), new SimpleString(name));
-         Notification notification = new Notification(nodeID, NotificationType.DISCOVERY_GROUP_STOPPED, props);
+         Notification notification = new Notification(nodeID, CoreNotificationType.DISCOVERY_GROUP_STOPPED, props);
          try
          {
             notificationService.sendNotification(notification);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageImpl.java
index cc9a390..057dcf6 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageImpl.java
@@ -26,6 +26,7 @@ import org.hornetq.api.core.SimpleString;
 import org.hornetq.core.buffers.impl.ResetLimitWrappedHornetQBuffer;
 import org.hornetq.core.message.BodyEncoder;
 import org.hornetq.core.protocol.core.impl.PacketImpl;
+import org.hornetq.utils.ByteUtil;
 import org.hornetq.utils.DataConstants;
 import org.hornetq.utils.TypedProperties;
 import org.hornetq.utils.UUID;
@@ -45,7 +46,9 @@ public abstract class MessageImpl implements MessageInternal
 {
    public static final SimpleString HDR_ROUTE_TO_IDS = new SimpleString("_HQ_ROUTE_TO");
 
-   public static final SimpleString HDR_ROUTE_TO_ACK_IDS = new SimpleString("_HQ_ROUTE_TO_ACK");
+   public static final SimpleString HDR_SCALEDOWN_TO_IDS = new SimpleString("_HQ_SCALEDOWN_TO");
+
+   public static final SimpleString HDR_ROUTE_TO_ACK_IDS = new SimpleString("_HQ_ACK_ROUTE_TO");
 
    // used by the bridges to set duplicates
    public static final SimpleString HDR_BRIDGE_DUPLICATE_ID = new SimpleString("_HQ_BRIDGE_DUP");
@@ -268,6 +271,20 @@ public abstract class MessageImpl implements MessageInternal
       return bodyBuffer;
    }
 
+   public Message writeBodyBufferBytes(byte[] bytes)
+   {
+      getBodyBuffer().writeBytes(bytes);
+
+      return this;
+   }
+
+   public Message writeBodyBufferString(String string)
+   {
+      getBodyBuffer().writeString(string);
+
+      return this;
+   }
+
    public void checkCompletion() throws HornetQException
    {
       // no op on regular messages
@@ -295,9 +312,10 @@ public abstract class MessageImpl implements MessageInternal
       return userID;
    }
 
-   public void setUserID(final UUID userID)
+   public MessageImpl setUserID(final UUID userID)
    {
       this.userID = userID;
+      return this;
    }
 
    /**
@@ -345,7 +363,7 @@ public abstract class MessageImpl implements MessageInternal
       return durable;
    }
 
-   public void setDurable(final boolean durable)
+   public MessageImpl setDurable(final boolean durable)
    {
       if (this.durable != durable)
       {
@@ -353,6 +371,7 @@ public abstract class MessageImpl implements MessageInternal
 
          bufferValid = false;
       }
+      return this;
    }
 
    public long getExpiration()
@@ -360,7 +379,7 @@ public abstract class MessageImpl implements MessageInternal
       return expiration;
    }
 
-   public void setExpiration(final long expiration)
+   public MessageImpl setExpiration(final long expiration)
    {
       if (this.expiration != expiration)
       {
@@ -368,6 +387,7 @@ public abstract class MessageImpl implements MessageInternal
 
          bufferValid = false;
       }
+      return this;
    }
 
    public long getTimestamp()
@@ -375,7 +395,7 @@ public abstract class MessageImpl implements MessageInternal
       return timestamp;
    }
 
-   public void setTimestamp(final long timestamp)
+   public MessageImpl setTimestamp(final long timestamp)
    {
       if (this.timestamp != timestamp)
       {
@@ -383,6 +403,7 @@ public abstract class MessageImpl implements MessageInternal
 
          bufferValid = false;
       }
+      return this;
    }
 
    public byte getPriority()
@@ -390,7 +411,7 @@ public abstract class MessageImpl implements MessageInternal
       return priority;
    }
 
-   public void setPriority(final byte priority)
+   public MessageImpl setPriority(final byte priority)
    {
       if (this.priority != priority)
       {
@@ -398,6 +419,7 @@ public abstract class MessageImpl implements MessageInternal
 
          bufferValid = false;
       }
+      return this;
    }
 
    public boolean isExpired()
@@ -924,6 +946,37 @@ public abstract class MessageImpl implements MessageInternal
       return false;
    }
 
+   /**
+    * Debug Helper!!!!
+    *
+    * I'm leaving this message here without any callers for a reason:
+    * During debugs it's important eventually to identify what's on the bodies, and this method will give you a good idea about them.
+    * Add the message.bodyToString() to the Watch variables on the debugger view and this will show up like a charm!!!
+    * @return
+    */
+   public String bodyToString()
+   {
+      getEndOfBodyPosition();
+      int readerIndex1 = this.buffer.readerIndex();
+      buffer.readerIndex(0);
+      byte[] buffer1 = new byte[buffer.writerIndex()];
+      buffer.readBytes(buffer1);
+      buffer.readerIndex(readerIndex1);
+
+      byte[] buffer2 = null;
+      if (bodyBuffer != null)
+      {
+         int readerIndex2 = this.bodyBuffer.readerIndex();
+         bodyBuffer.readerIndex(0);
+         buffer2 = new byte[bodyBuffer.writerIndex() - bodyBuffer.readerIndex()];
+         bodyBuffer.readBytes(buffer2);
+         bodyBuffer.readerIndex(readerIndex2);
+      }
+
+      return "ServerMessage@" + Integer.toHexString(System.identityHashCode(this)) + "[" + ",bodyStart=" + getEndOfBodyPosition() + " buffer=" + ByteUtil.bytesToHex(buffer1, 1) + ", bodyBuffer=" + ByteUtil.bytesToHex(buffer2, 1);
+   }
+
+
 
 
    @Override
@@ -961,6 +1014,10 @@ public abstract class MessageImpl implements MessageInternal
 
          int bodySize = getEndOfBodyPosition();
 
+         // Clebert: I've started sending this on encoding due to conversions between protocols
+         //          and making sure we are not losing the buffer start position between protocols
+         this.endOfBodyPosition = bodySize;
+
          // write it
          buffer.setInt(BUFFER_HEADER_SPACE, bodySize);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageInternal.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageInternal.java b/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageInternal.java
index b49aff7..f84cf0a 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageInternal.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/message/impl/MessageInternal.java
@@ -26,8 +26,6 @@ import org.hornetq.utils.TypedProperties;
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  *
- * TODO - this can be refactored further to separate out large message specific stuff
- *
  *
  */
 public interface MessageInternal extends Message

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/Channel.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/Channel.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/Channel.java
index 86bccd6..fd043fe 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/Channel.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/Channel.java
@@ -136,6 +136,11 @@ public interface Channel
    void returnBlocking();
 
    /**
+    * forces any {@link org.hornetq.core.protocol.core.Channel#sendBlocking(Packet, byte)} request to return with an exception.
+    */
+   void returnBlocking(Throwable cause);
+
+   /**
     * returns the channel lock
     *
     * @return the lock

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/ChannelImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/ChannelImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/ChannelImpl.java
index 89303ef..0a6202a 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/ChannelImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/ChannelImpl.java
@@ -184,11 +184,16 @@ public final class ChannelImpl implements Channel
 
    public void returnBlocking()
    {
+      returnBlocking(null);
+   }
+
+   public void returnBlocking(Throwable cause)
+   {
       lock.lock();
 
       try
       {
-         response = new HornetQExceptionMessage(HornetQClientMessageBundle.BUNDLE.unblockingACall());
+         response = new HornetQExceptionMessage(HornetQClientMessageBundle.BUNDLE.unblockingACall(cause));
 
          sendCondition.signal();
       }


[40/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/reader/TextMessageUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/reader/TextMessageUtil.java b/hornetq-core-client/src/main/java/org/hornetq/reader/TextMessageUtil.java
new file mode 100644
index 0000000..9601f5e
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/reader/TextMessageUtil.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.reader;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.Message;
+import org.hornetq.api.core.SimpleString;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class TextMessageUtil extends MessageUtil
+{
+
+   /**
+    * Utility method to set the Text message on a message body
+    */
+   public static void writeBodyText(Message message, SimpleString text)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      buff.clear();
+      buff.writeNullableSimpleString(text);
+   }
+
+   /**
+    * Utility method to set the Text message on a message body
+    */
+   public static SimpleString readBodyText(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      buff.resetReaderIndex();
+      return buff.readNullableSimpleString();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/reader/package-info.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/reader/package-info.java b/hornetq-core-client/src/main/java/org/hornetq/reader/package-info.java
new file mode 100644
index 0000000..5e75719
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/reader/package-info.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+/**
+ * Provides reading methods for JMS like objects.
+ * This isolates the logic from the JMS client case you need this kind of functionality from core.
+ * This is also used on conversions between protocols such as AMQP and Core where
+ * this is done at the server's
+ * @author Clebert Suconic
+ */
+package org.hornetq.reader;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/AbstractRemotingConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/AbstractRemotingConnection.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/AbstractRemotingConnection.java
new file mode 100644
index 0000000..f5a910e
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/AbstractRemotingConnection.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.spi.core.protocol;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.HornetQInterruptedException;
+import org.hornetq.core.client.HornetQClientLogger;
+import org.hornetq.core.client.HornetQClientMessageBundle;
+import org.hornetq.core.remoting.CloseListener;
+import org.hornetq.core.remoting.FailureListener;
+import org.hornetq.spi.core.remoting.Connection;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public abstract class AbstractRemotingConnection implements RemotingConnection
+{
+   protected final List<FailureListener> failureListeners = new CopyOnWriteArrayList<FailureListener>();
+   protected final List<CloseListener> closeListeners = new CopyOnWriteArrayList<CloseListener>();
+   protected final Connection transportConnection;
+   protected final Executor executor;
+   protected final long creationTime;
+   protected volatile boolean dataReceived;
+
+   public AbstractRemotingConnection(final Connection transportConnection, final Executor executor)
+   {
+      this.transportConnection = transportConnection;
+      this.executor = executor;
+      this.creationTime = System.currentTimeMillis();
+   }
+
+   public List<FailureListener> getFailureListeners()
+   {
+      return new ArrayList<FailureListener>(failureListeners);
+   }
+
+   protected void callFailureListeners(final HornetQException me, String scaleDownTargetNodeID)
+   {
+      final List<FailureListener> listenersClone = new ArrayList<FailureListener>(failureListeners);
+
+      for (final FailureListener listener : listenersClone)
+      {
+         try
+         {
+            listener.connectionFailed(me, false, scaleDownTargetNodeID);
+         }
+         catch (HornetQInterruptedException interrupted)
+         {
+            // this is an expected behaviour.. no warn or error here
+            HornetQClientLogger.LOGGER.debug("thread interrupted", interrupted);
+         }
+         catch (final Throwable t)
+         {
+            // Failure of one listener to execute shouldn't prevent others
+            // from
+            // executing
+            HornetQClientLogger.LOGGER.errorCallingFailureListener(t);
+         }
+      }
+   }
+
+
+   protected void callClosingListeners()
+   {
+      final List<CloseListener> listenersClone = new ArrayList<CloseListener>(closeListeners);
+
+      for (final CloseListener listener : listenersClone)
+      {
+         try
+         {
+            listener.connectionClosed();
+         }
+         catch (final Throwable t)
+         {
+            // Failure of one listener to execute shouldn't prevent others
+            // from
+            // executing
+            HornetQClientLogger.LOGGER.errorCallingFailureListener(t);
+         }
+      }
+   }
+
+   public void setFailureListeners(final List<FailureListener> listeners)
+   {
+      failureListeners.clear();
+
+      failureListeners.addAll(listeners);
+   }
+
+   public Object getID()
+   {
+      return transportConnection.getID();
+   }
+
+   public String getRemoteAddress()
+   {
+      return transportConnection.getRemoteAddress();
+   }
+
+   public void addFailureListener(final FailureListener listener)
+   {
+      if (listener == null)
+      {
+         throw HornetQClientMessageBundle.BUNDLE.failListenerCannotBeNull();
+      }
+      failureListeners.add(listener);
+   }
+
+   public boolean removeFailureListener(final FailureListener listener)
+   {
+      if (listener == null)
+      {
+         throw HornetQClientMessageBundle.BUNDLE.failListenerCannotBeNull();
+      }
+
+      return failureListeners.remove(listener);
+   }
+
+   public void addCloseListener(final CloseListener listener)
+   {
+      if (listener == null)
+      {
+         throw HornetQClientMessageBundle.BUNDLE.closeListenerCannotBeNull();
+      }
+
+      closeListeners.add(listener);
+   }
+
+   public boolean removeCloseListener(final CloseListener listener)
+   {
+      if (listener == null)
+      {
+         throw HornetQClientMessageBundle.BUNDLE.closeListenerCannotBeNull();
+      }
+
+      return closeListeners.remove(listener);
+   }
+
+   public List<CloseListener> removeCloseListeners()
+   {
+      List<CloseListener> ret = new ArrayList<CloseListener>(closeListeners);
+
+      closeListeners.clear();
+
+      return ret;
+   }
+
+   public List<FailureListener> removeFailureListeners()
+   {
+      List<FailureListener> ret = getFailureListeners();
+
+      failureListeners.clear();
+
+      return ret;
+   }
+
+   public void setCloseListeners(List<CloseListener> listeners)
+   {
+      closeListeners.clear();
+
+      closeListeners.addAll(listeners);
+   }
+
+   public HornetQBuffer createBuffer(final int size)
+   {
+      return transportConnection.createBuffer(size);
+   }
+
+   public Connection getTransportConnection()
+   {
+      return transportConnection;
+   }
+
+   public long getCreationTime()
+   {
+      return creationTime;
+   }
+
+   public boolean checkDataReceived()
+   {
+      boolean res = dataReceived;
+
+      dataReceived = false;
+
+      return res;
+   }
+
+   /*
+    * This can be called concurrently by more than one thread so needs to be locked
+    */
+   public void fail(final HornetQException me)
+   {
+      fail(me, null);
+   }
+
+   public void bufferReceived(final Object connectionID, final HornetQBuffer buffer)
+   {
+      dataReceived = true;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/ConnectionEntry.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/ConnectionEntry.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/ConnectionEntry.java
index 1d1219f..5b60aac 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/ConnectionEntry.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/ConnectionEntry.java
@@ -32,6 +32,11 @@ public class ConnectionEntry
 
    public final Executor connectionExecutor;
 
+   public Object getID()
+   {
+      return connection.getID();
+   }
+
    public ConnectionEntry(final RemotingConnection connection, final Executor connectionExecutor, final long lastCheck, final long ttl)
    {
       this.connection = connection;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/RemotingConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/RemotingConnection.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/RemotingConnection.java
index 7e4114f..932f771 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/RemotingConnection.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/protocol/RemotingConnection.java
@@ -24,6 +24,10 @@ import org.hornetq.spi.core.remoting.Connection;
 /**
  * A RemotingConnection is a connection between a client and a server.
  *
+ *
+ * Perhaps a better name for this class now would be ProtocolConnection as this
+ * represents the link with the used protocol
+ *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  */

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/AbstractConnector.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/AbstractConnector.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/AbstractConnector.java
index db552a2..e56f1ac 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/AbstractConnector.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/AbstractConnector.java
@@ -14,8 +14,6 @@ package org.hornetq.spi.core.remoting;
 
 import java.util.Map;
 
-import org.hornetq.core.protocol.core.impl.HornetQClientProtocolManagerFactory;
-
 /**
  * Abstract connector
  *
@@ -25,16 +23,8 @@ public abstract class AbstractConnector implements Connector
 {
    protected final Map<String, Object> configuration;
 
-   private static final ClientProtocolManagerFactory protocolWrapperFactory = new HornetQClientProtocolManagerFactory();
-
    protected AbstractConnector(Map<String, Object> configuration)
    {
       this.configuration = configuration;
    }
-
-   public ClientProtocolManagerFactory getProtocolManagerFactory()
-   {
-      return protocolWrapperFactory;
-   }
-
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManager.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManager.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManager.java
index dc614b4..8ae772b 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManager.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManager.java
@@ -16,8 +16,10 @@ package org.hornetq.spi.core.remoting;
 import java.util.List;
 import java.util.concurrent.locks.Lock;
 
+import io.netty.channel.ChannelPipeline;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Interceptor;
+import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 
 /**
@@ -29,12 +31,10 @@ public interface ClientProtocolManager
 
    /// Life Cycle Methods:
 
-   RemotingConnection connect(Connection transportConnection, long callTimeout, long callFailoverTimeout,  List<Interceptor> incomingInterceptors, List<Interceptor> outgoingInterceptors, ProtocolResponseHandler protocolResponseHandler);
+   RemotingConnection connect(Connection transportConnection, long callTimeout, long callFailoverTimeout, List<Interceptor> incomingInterceptors, List<Interceptor> outgoingInterceptors, TopologyResponseHandler topologyResponseHandler);
 
    RemotingConnection getCurrentConnection();
 
-   void setResponseHandler(ProtocolResponseHandler handler);
-
    Lock lockSessionCreation();
 
    boolean waitOnLatch(long milliseconds) throws InterruptedException;
@@ -49,11 +49,10 @@ public interface ClientProtocolManager
 
    /// Sending methods
 
+   void addChannelHandlers(ChannelPipeline pipeline);
 
    void sendSubscribeTopology(boolean isServer);
 
-   void shakeHands();
-
    void ping(long connectionTTL);
 
    SessionContext createSessionContext(final String name,
@@ -66,7 +65,14 @@ public interface ClientProtocolManager
                                        int minLargeMessageSize,
                                        int confirmationWindowSize) throws HornetQException;
 
-   boolean cleanupBeforeFailover();
+   boolean cleanupBeforeFailover(HornetQException cause);
 
    boolean checkForFailover(String liveNodeID) throws HornetQException;
+
+   void setSessionFactory(ClientSessionFactory factory);
+
+   ClientSessionFactory getSessionFactory();
+
+   String getName();
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManagerFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManagerFactory.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManagerFactory.java
index 0c40e86..448f92d 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManagerFactory.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ClientProtocolManagerFactory.java
@@ -12,12 +12,13 @@
  */
 package org.hornetq.spi.core.remoting;
 
-import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
+import java.io.Serializable;
 
 /**
  * @author Clebert Suconic
  */
-public interface ClientProtocolManagerFactory
+public interface ClientProtocolManagerFactory extends Serializable
 {
-   ClientProtocolManager newProtocolManager(ClientSessionFactoryInternal factoryInternal);
+
+   ClientProtocolManager newProtocolManager();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connection.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connection.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connection.java
index 1df470b..69c338b 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connection.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connection.java
@@ -12,14 +12,17 @@
  */
 package org.hornetq.spi.core.remoting;
 
+import io.netty.channel.ChannelFutureListener;
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.security.HornetQPrincipal;
+import org.hornetq.spi.core.protocol.RemotingConnection;
 
 /**
  * The connection used by a channel to write data to.
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author Clebert Suconic
  */
 public interface Connection
 {
@@ -31,6 +34,11 @@ public interface Connection
     */
    HornetQBuffer createBuffer(int size);
 
+
+   RemotingConnection getProtocolConnection();
+
+   void setProtocolConnection(RemotingConnection connection);
+
    /**
     * returns the unique id of this wire.
     *
@@ -48,12 +56,29 @@ public interface Connection
    void write(HornetQBuffer buffer, boolean flush, boolean batched);
 
    /**
+    * writes the buffer to the connection and if flush is true returns only when the buffer has been physically written to the connection.
+    *
+    * @param buffer the buffer to write
+    * @param flush  whether to flush the buffers onto the wire
+    * @param batched whether the packet is allowed to batched for better performance
+    */
+   void write(HornetQBuffer buffer, boolean flush, boolean batched, ChannelFutureListener futureListener);
+
+   /**
     * writes the buffer to the connection with no flushing or batching
     *
     * @param buffer the buffer to write
     */
    void write(HornetQBuffer buffer);
 
+
+   /**
+    * This should close the internal channel without calling any listeners.
+    * This is to avoid a situation where the broker is busy writing on an internal thread.
+    * This should close the socket releasing any pending threads.
+    */
+   void forceClose();
+
    /**
     * Closes the connection.
     */
@@ -77,9 +102,16 @@ public interface Connection
    /**
     * Generates a {@link TransportConfiguration} to be used to connect to the same target this is
     * connected to.
-    * @return TranportConfiguration
+    * @return TransportConfiguration
     */
    TransportConfiguration getConnectorConfig();
 
    HornetQPrincipal getDefaultHornetQPrincipal();
+
+   /**
+    * the InVM Connection has some special handling as it doesn't use Netty ProtocolChannel
+    * we will use this method Instead of using instanceof
+    * @return
+    */
+   boolean isUsingProtocolHandling();
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connector.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connector.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connector.java
index 99dfa43..474f189 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connector.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/Connector.java
@@ -50,8 +50,6 @@ public interface Connector
     */
    Connection createConnection();
 
-   ClientProtocolManagerFactory getProtocolManagerFactory();
-
    /**
     * If the configuration is equivalent to this connector, which means
     * if the parameter configuration is used to create a connection to a target

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConnectorFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConnectorFactory.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConnectorFactory.java
index d77b107..5d0b458 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConnectorFactory.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConnectorFactory.java
@@ -17,6 +17,8 @@ import java.util.Set;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
 
+import org.hornetq.api.core.TransportConfigurationHelper;
+
 /**
  * A ConnectorFactory is used by the client for creating connectors.
  * <p>
@@ -24,7 +26,7 @@ import java.util.concurrent.ScheduledExecutorService;
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  */
-public interface ConnectorFactory
+public interface ConnectorFactory extends TransportConfigurationHelper
 {
    /**
     * creates a new instance of a connector.
@@ -42,7 +44,8 @@ public interface ConnectorFactory
                              ConnectionLifeCycleListener listener,
                              Executor closeExecutor,
                              Executor threadPool,
-                             ScheduledExecutorService scheduledThreadPool);
+                             ScheduledExecutorService scheduledThreadPool,
+                             ClientProtocolManager protocolManager);
 
    /**
     * Returns the allowable properties for this connector.

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConsumerContext.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConsumerContext.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConsumerContext.java
new file mode 100644
index 0000000..082bcd4
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ConsumerContext.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.spi.core.remoting;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public abstract class ConsumerContext
+{
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ProtocolResponseHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ProtocolResponseHandler.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ProtocolResponseHandler.java
deleted file mode 100644
index e5a7c91..0000000
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/ProtocolResponseHandler.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.spi.core.remoting;
-
-import org.hornetq.api.core.Pair;
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.spi.core.protocol.RemotingConnection;
-
-/**
- * @author Clebert Suconic
- */
-
-public interface ProtocolResponseHandler
-{
-   // This is sent when the server is telling the client the node is being disconnected
-   void nodeDisconnected(RemotingConnection conn, String nodeID, String scaleDownTargetNodeID);
-
-   void notifyNodeUp(long uniqueEventID,
-                     final String backupGroupName,
-                     final String scaleDownGroupName,
-                     final String nodeName,
-                     final Pair<TransportConfiguration, TransportConfiguration> connectorPair,
-                     final boolean isLast);
-
-   // This is sent when any node on the cluster topology is going down
-   void notifyNodeDown(final long eventTime, final String nodeID);
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/SessionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/SessionContext.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/SessionContext.java
index af6e2f0..87d97de 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/SessionContext.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/SessionContext.java
@@ -27,6 +27,7 @@ import org.hornetq.api.core.client.SendAcknowledgementHandler;
 import org.hornetq.core.client.impl.ClientConsumerInternal;
 import org.hornetq.core.client.impl.ClientLargeMessageInternal;
 import org.hornetq.core.client.impl.ClientMessageInternal;
+import org.hornetq.core.client.impl.ClientProducerCreditsImpl;
 import org.hornetq.core.client.impl.ClientSessionInternal;
 import org.hornetq.core.message.impl.MessageInternal;
 import org.hornetq.spi.core.protocol.RemotingConnection;
@@ -41,8 +42,6 @@ public abstract class SessionContext
 {
    protected ClientSessionInternal session;
 
-   protected final String name;
-
    protected SendAcknowledgementHandler sendAckHandler;
 
    protected volatile RemotingConnection remotingConnection;
@@ -50,10 +49,9 @@ public abstract class SessionContext
    protected final IDGenerator idGenerator = new SimpleIDGenerator(0);
 
 
-   public SessionContext(final String name, RemotingConnection remotingConnection)
+   public SessionContext(RemotingConnection remotingConnection)
    {
       this.remotingConnection = remotingConnection;
-      this.name = name;
    }
 
 
@@ -88,7 +86,7 @@ public abstract class SessionContext
 
    public abstract boolean supportsLargeMessage();
 
-   protected void handleReceiveLargeMessage(long consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception
+   protected void handleReceiveLargeMessage(ConsumerContext consumerID, ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception
    {
       ClientSessionInternal session = this.session;
       if (session != null)
@@ -97,7 +95,7 @@ public abstract class SessionContext
       }
    }
 
-   protected void handleReceiveMessage(final long consumerID, final ClientMessageInternal message) throws Exception
+   protected void handleReceiveMessage(ConsumerContext consumerID, final ClientMessageInternal message) throws Exception
    {
 
       ClientSessionInternal session = this.session;
@@ -107,7 +105,7 @@ public abstract class SessionContext
       }
    }
 
-   protected void handleReceiveContinuation(final long consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception
+   protected void handleReceiveContinuation(final ConsumerContext consumerID, byte[] chunk, int flowControlSize, boolean isContinues) throws Exception
    {
       ClientSessionInternal session = this.session;
       if (session != null)
@@ -138,7 +136,7 @@ public abstract class SessionContext
 
    public abstract int getCreditsOnSendingFull(MessageInternal msgI);
 
-   public abstract void sendFullMessage(MessageInternal msgI, boolean sendBlocking, SendAcknowledgementHandler handler) throws HornetQException;
+   public abstract void sendFullMessage(MessageInternal msgI, boolean sendBlocking, SendAcknowledgementHandler handler, SimpleString defaultAddress) throws HornetQException;
 
    /**
     * it should return the number of credits (or bytes) used to send this packet
@@ -252,7 +250,7 @@ public abstract class SessionContext
    /**
     * Interrupt and return any blocked calls
     */
-   public abstract void returnBlocking();
+   public abstract void returnBlocking(HornetQException cause);
 
    /**
     * it will lock the communication channel of the session avoiding anything to come while failover is happening.
@@ -266,4 +264,5 @@ public abstract class SessionContext
    public abstract void cleanup();
 
 
+   public abstract void linkFlowControl(SimpleString address, ClientProducerCreditsImpl clientProducerCredits);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/TopologyResponseHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/TopologyResponseHandler.java b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/TopologyResponseHandler.java
new file mode 100644
index 0000000..f7b99ec
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/spi/core/remoting/TopologyResponseHandler.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.spi.core.remoting;
+
+import org.hornetq.api.core.Pair;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.spi.core.protocol.RemotingConnection;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface TopologyResponseHandler
+{
+   // This is sent when the server is telling the client the node is being disconnected
+   void nodeDisconnected(RemotingConnection conn, String nodeID, String scaleDownTargetNodeID);
+
+   void notifyNodeUp(long uniqueEventID,
+                     final String backupGroupName,
+                     final String scaleDownGroupName,
+                     final String nodeName,
+                     final Pair<TransportConfiguration, TransportConfiguration> connectorPair,
+                     final boolean isLast);
+
+   // This is sent when any node on the cluster topology is going down
+   void notifyNodeDown(final long eventTime, final String nodeID);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/utils/FutureLatch.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/utils/FutureLatch.java b/hornetq-core-client/src/main/java/org/hornetq/utils/FutureLatch.java
index 70facaf..51a32a0 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/utils/FutureLatch.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/utils/FutureLatch.java
@@ -22,7 +22,19 @@ import java.util.concurrent.TimeUnit;
  */
 public class FutureLatch implements Runnable
 {
-   private final CountDownLatch latch = new CountDownLatch(1);
+   private final CountDownLatch latch;
+
+   public FutureLatch()
+   {
+      super();
+      latch = new CountDownLatch(1);
+   }
+
+   public FutureLatch(int latches)
+   {
+      super();
+      latch =  new CountDownLatch(latches);
+   }
 
    public boolean await(final long timeout)
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-dto/pom.xml b/hornetq-dto/pom.xml
new file mode 100644
index 0000000..ed253c8
--- /dev/null
+++ b/hornetq-dto/pom.xml
@@ -0,0 +1,147 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.hornetq</groupId>
+      <artifactId>hornetq-pom</artifactId>
+      <version>2.5.0-SNAPSHOT</version>
+   </parent>
+
+   <artifactId>hornetq-dto</artifactId>
+   <packaging>jar</packaging>
+   <name>HornetQ DTO</name>
+
+   <properties>
+     <hornetq.basedir>${project.basedir}/..</hornetq.basedir>
+   </properties>
+
+   <dependencies>
+      <dependency>
+        <groupId>com.fasterxml.jackson.core</groupId>
+        <artifactId>jackson-databind</artifactId>
+        <version>${jackson-databind.version}</version>
+      </dependency>
+   </dependencies>
+
+   <build>
+     <resources>
+       <resource>
+         <directory>target/schema</directory>
+         <includes>
+           <include>**/*</include>
+         </includes>
+       </resource>
+       <resource>
+         <directory>src/main/resources</directory>
+         <includes>
+           <include>**/*</include>
+         </includes>
+         <filtering>true</filtering>
+       </resource>
+     </resources>
+
+     <plugins>
+       <plugin>
+         <artifactId>maven-antrun-plugin</artifactId>
+         <version>1.7</version>
+         <executions>
+           <execution>
+             <phase>generate-resources</phase>
+             <configuration>
+               <tasks>
+                 <taskdef name="schemagen" classname="com.sun.tools.jxc.SchemaGenTask"/>
+                 <mkdir dir="${project.build.directory}/schema/org/hornetq/dto"/>
+                 <echo message="Generating XSD to: ${project.build.directory}/schema/org/hornetq/dto"/>
+                 <schemagen srcdir="${basedir}/.." destdir="${project.build.directory}/schema/org/hornetq/dto"
+                            includeantruntime="false">
+                   <schema namespace="http://hornetq.org/schema" file="hornetq.xsd"/>
+                   <classpath refid="maven.compile.classpath"/>
+                   <include name="**/package-info.java"/>
+                   <include name="**/*DTO.java"/>
+                   <exclude name="**/.git/**"/>
+                   <exclude name="**/.svn/**"/>
+                 </schemagen>
+                 <copy todir="${project.build.directory}/classes">
+                   <fileset dir="${project.build.directory}/schema"/>
+                 </copy>
+               </tasks>
+             </configuration>
+             <goals>
+               <goal>run</goal>
+             </goals>
+           </execution>
+         </executions>
+         <dependencies>
+            <dependency>
+               <groupId>javax.xml.bind</groupId>
+               <artifactId>jaxb-api</artifactId>
+               <version>2.2.7</version>
+            </dependency>
+            <dependency>
+               <groupId>com.sun.xml.bind</groupId>
+               <artifactId>jaxb-impl</artifactId>
+               <version>2.2.7</version>
+            </dependency>
+            <dependency>
+               <groupId>com.sun.xml.bind</groupId>
+               <artifactId>jaxb-jxc</artifactId>
+               <version>2.2.7</version>
+            </dependency>
+         </dependencies>
+       </plugin>
+     </plugins>
+   </build>
+
+   <profiles>
+     <profile>
+       <id>jdk-1.5</id>
+       <activation>
+         <jdk>1.5</jdk>
+       </activation>
+       <dependencies>
+         <dependency>
+           <groupId>javax.xml.bind</groupId>
+           <artifactId>jaxb-api</artifactId>
+           <version>${jaxb-api-version}</version>
+         </dependency>
+         <dependency>
+           <groupId>com.sun.xml.bind</groupId>
+           <artifactId>jaxb-impl</artifactId>
+           <version>${jaxb-version}</version>
+         </dependency>
+       </dependencies>
+     </profile>
+
+    <profile>
+       <id>ibmjdk</id>
+       <activation>
+         <file>
+           <exists>${java.home}/../lib/tools.jar</exists>
+         </file>
+       </activation>
+       <build>
+         <pluginManagement>
+           <plugins>
+             <plugin>
+               <groupId>org.apache.maven.plugins</groupId>
+               <artifactId>maven-antrun-plugin</artifactId>
+               <dependencies>
+                 <dependency>
+                   <groupId>com.sun</groupId>
+                   <artifactId>tools</artifactId>
+                   <!--the real JDK version could be 1.5 or 1.6-->
+                   <version>1.5.0</version>
+                   <scope>system</scope>
+                   <optional>true</optional>
+                   <systemPath>${java.home}/../lib/tools.jar</systemPath>
+                 </dependency>
+               </dependencies>
+             </plugin>
+           </plugins>
+         </pluginManagement>
+       </build>
+     </profile>
+   </profiles>
+
+</project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/BasicSecurityDTO.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/BasicSecurityDTO.java b/hornetq-dto/src/main/java/org/hornetq/dto/BasicSecurityDTO.java
new file mode 100644
index 0000000..d9836b5
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/BasicSecurityDTO.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.dto;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "basic-security")
+@XmlAccessorType(XmlAccessType.FIELD)
+public class BasicSecurityDTO extends SecurityDTO
+{
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/BrokerDTO.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/BrokerDTO.java b/hornetq-dto/src/main/java/org/hornetq/dto/BrokerDTO.java
new file mode 100644
index 0000000..9c31e80
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/BrokerDTO.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.dto;
+
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "broker")
+@XmlAccessorType(XmlAccessType.FIELD)
+@JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, include = JsonTypeInfo.As.PROPERTY, property = "@class")
+public class BrokerDTO
+{
+
+   @XmlElementRef
+   public CoreDTO core;
+
+   @XmlElementRef(required = false)
+   public JmsDTO jms;
+
+   @XmlElementRef
+   public SecurityDTO security;
+
+   @XmlElementRef
+   public NamingDTO naming;
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/CoreDTO.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/CoreDTO.java b/hornetq-dto/src/main/java/org/hornetq/dto/CoreDTO.java
new file mode 100644
index 0000000..7cd62a8
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/CoreDTO.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.dto;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "core")
+@XmlAccessorType(XmlAccessType.FIELD)
+public class CoreDTO
+{
+
+   @XmlAttribute
+   public String configuration;
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/JmsDTO.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/JmsDTO.java b/hornetq-dto/src/main/java/org/hornetq/dto/JmsDTO.java
new file mode 100644
index 0000000..6990298
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/JmsDTO.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.dto;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "jms")
+@XmlAccessorType(XmlAccessType.FIELD)
+public class JmsDTO
+{
+
+   @XmlAttribute
+   public String configuration;
+
+}
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/NamingDTO.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/NamingDTO.java b/hornetq-dto/src/main/java/org/hornetq/dto/NamingDTO.java
new file mode 100644
index 0000000..8e614ae
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/NamingDTO.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.dto;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "naming")
+@XmlAccessorType(XmlAccessType.FIELD)
+public class NamingDTO
+{
+   @XmlAttribute
+   public String bindAddress = "localhost";
+
+   @XmlAttribute
+   public int port = 1099;
+
+   @XmlAttribute
+   public String rmiBindAddress = "localhost";
+
+   @XmlAttribute
+   public int rmiPort = 1098;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/SecurityDTO.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/SecurityDTO.java b/hornetq-dto/src/main/java/org/hornetq/dto/SecurityDTO.java
new file mode 100644
index 0000000..bf52ae3
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/SecurityDTO.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.dto;
+
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlType(name = "security")
+@XmlAccessorType(XmlAccessType.FIELD)
+@JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, include = JsonTypeInfo.As.PROPERTY, property = "@class")
+public class SecurityDTO
+{
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/XmlUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/XmlUtil.java b/hornetq-dto/src/main/java/org/hornetq/dto/XmlUtil.java
new file mode 100644
index 0000000..58037ff
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/XmlUtil.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.dto;
+
+import javax.xml.XMLConstants;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.util.StreamReaderDelegate;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class XmlUtil
+{
+
+   /**
+    * Changes ${property} with values from a properties object
+    */
+   static class PropertiesFilter extends StreamReaderDelegate
+   {
+
+      static final Pattern pattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
+      private final Properties props;
+
+      public PropertiesFilter(XMLStreamReader parent, Properties props)
+      {
+         super(parent);
+         this.props = props;
+      }
+
+      public String getAttributeValue(int index)
+      {
+         return filter(super.getAttributeValue(index));
+      }
+
+      public String filter(String str)
+      {
+         int start = 0;
+         while (true)
+         {
+            Matcher matcher = pattern.matcher(str);
+            if (!matcher.find(start))
+            {
+               break;
+            }
+            String group = matcher.group(1);
+            String property = props.getProperty(group);
+            if (property != null)
+            {
+               str = matcher.replaceFirst(Matcher.quoteReplacement(property));
+            }
+            else
+            {
+               start = matcher.end();
+            }
+         }
+         return str;
+      }
+
+   }
+
+   private static final XMLInputFactory factory = XMLInputFactory.newInstance();
+
+   public static <T> T decode(Class<T> clazz, File configuration) throws Exception
+   {
+      JAXBContext jaxbContext = JAXBContext.newInstance("org.hornetq.dto");
+
+      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
+      SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+      sf.setFeature("http://apache.org/xml/features/validation/schema-full-checking", false);
+      InputStream xsdStream = XmlUtil.class.getClassLoader().getResourceAsStream("org/hornetq/dto/hornetq.xsd");
+      StreamSource xsdSource = new StreamSource(xsdStream);
+      Schema schema = sf.newSchema(xsdSource);
+      unmarshaller.setSchema(schema);
+
+      XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream(configuration));
+      //TODO - support properties files
+      Properties props = System.getProperties();
+
+      if (props != null)
+      {
+         reader = new PropertiesFilter(reader, props);
+      }
+
+      return clazz.cast(unmarshaller.unmarshal(reader));
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/java/org/hornetq/dto/package-info.java
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/java/org/hornetq/dto/package-info.java b/hornetq-dto/src/main/java/org/hornetq/dto/package-info.java
new file mode 100644
index 0000000..4da6f69
--- /dev/null
+++ b/hornetq-dto/src/main/java/org/hornetq/dto/package-info.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+/**
+ * The JAXB POJOs for the XML configuration of HornetQ broker
+ */
+@javax.xml.bind.annotation.XmlSchema(
+        namespace = "http://hornetq.org/schema",
+        elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+package org.hornetq.dto;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-dto/src/main/resources/org/hornetq/dto/jaxb.index
----------------------------------------------------------------------
diff --git a/hornetq-dto/src/main/resources/org/hornetq/dto/jaxb.index b/hornetq-dto/src/main/resources/org/hornetq/dto/jaxb.index
new file mode 100644
index 0000000..3cec94b
--- /dev/null
+++ b/hornetq-dto/src/main/resources/org/hornetq/dto/jaxb.index
@@ -0,0 +1,19 @@
+## ---------------------------------------------------------------------------
+## Copyright 2005-2014 Red Hat, Inc.
+## Red Hat licenses this file to you under the Apache License, version
+## 2.0 (the "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##    http://www.apache.org/licenses/LICENSE-2.0
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+## implied.  See the License for the specific language governing
+## permissions and limitations under the License.
+## ---------------------------------------------------------------------------
+BrokerDTO
+CoreDTO
+JmsDTO
+SecurityDTO
+BasicSecurityDTO
+NamingDTO
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSQueueControl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSQueueControl.java b/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSQueueControl.java
index b672ab7..ae7cba1 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSQueueControl.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSQueueControl.java
@@ -277,4 +277,12 @@ public interface JMSQueueControl extends DestinationControl
    @Operation(desc = "List all the existent consumers on the Queue")
    String listConsumersAsJSON() throws Exception;
 
+   /**
+    * it will flush one cycle on internal executors, so you would be sure that any pending tasks are done before you call
+    * any other measure.
+    * It is useful if you need the exact number of counts on a message
+    * @throws Exception
+    */
+   void flushExecutor();
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSServerControl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSServerControl.java b/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSServerControl.java
index d0d7f6c..f58692e 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSServerControl.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/api/jms/management/JMSServerControl.java
@@ -268,6 +268,18 @@ public interface JMSServerControl
    boolean closeConnectionsForAddress(@Parameter(desc = "an IP address", name = "ipAddress") String ipAddress) throws Exception;
 
    /**
+    * Closes all the connections on this server for consumers which are consuming from a queue associated with a particular address.
+    */
+   @Operation(desc = "Closes all the consumer connections for the given HornetQ address", impact = MBeanOperationInfo.INFO)
+   boolean closeConsumerConnectionsForAddress(@Parameter(desc = "a HornetQ address", name = "address") String address) throws Exception;
+
+   /**
+    * Closes all the connections on this server for sessions using a particular user name.
+    */
+   @Operation(desc = "Closes all the connections for session using a particular user name", impact = MBeanOperationInfo.INFO)
+   boolean closeConnectionsForUser(@Parameter(desc = "a user name", name = "userName") String address) throws Exception;
+
+   /**
     * Lists all the IDs of the connections connected to this server.
     */
    @Operation(desc = "List all the connection IDs", impact = MBeanOperationInfo.INFO)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQBytesMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQBytesMessage.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQBytesMessage.java
index 55a55dc..2cf4154 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQBytesMessage.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQBytesMessage.java
@@ -24,6 +24,31 @@ import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.core.message.impl.MessageImpl;
 
+import static org.hornetq.reader.BytesMessageUtil.bytesMessageReset;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadBoolean;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadByte;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadBytes;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadChar;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadDouble;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadFloat;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadInt;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadLong;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadShort;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadUTF;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadUnsignedByte;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadUnsignedShort;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteBoolean;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteByte;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteBytes;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteChar;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteDouble;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteFloat;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteInt;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteLong;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteObject;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteShort;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteUTF;
+
 /**
  * HornetQ implementation of a JMS {@link BytesMessage}.
  *
@@ -85,7 +110,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readBoolean();
+         return bytesReadBoolean(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -98,7 +123,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readByte();
+         return bytesReadByte(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -111,7 +136,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readUnsignedByte();
+         return bytesReadUnsignedByte(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -124,7 +149,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readShort();
+         return bytesReadShort(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -137,7 +162,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readUnsignedShort();
+         return bytesReadUnsignedShort(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -150,7 +175,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return (char)getBuffer().readShort();
+         return bytesReadChar(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -163,7 +188,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readInt();
+         return bytesReadInt(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -176,7 +201,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readLong();
+         return bytesReadLong(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -189,7 +214,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return Float.intBitsToFloat(getBuffer().readInt());
+         return bytesReadFloat(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -202,7 +227,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return Double.longBitsToDouble(getBuffer().readLong());
+         return bytesReadDouble(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -215,7 +240,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkRead();
       try
       {
-         return getBuffer().readUTF();
+         return bytesReadUTF(message);
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -232,74 +257,63 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
 
    public int readBytes(final byte[] value) throws JMSException
    {
-      return readBytes(value, value.length);
+      checkRead();
+      return bytesReadBytes(message, value);
    }
 
    public int readBytes(final byte[] value, final int length) throws JMSException
    {
       checkRead();
+      return bytesReadBytes(message, value, length);
 
-      if (!getBuffer().readable())
-      {
-         return -1;
-      }
-
-      int read = Math.min(length, getBuffer().readableBytes());
-
-      if (read != 0)
-      {
-         getBuffer().readBytes(value, 0, read);
-      }
-
-      return read;
    }
 
    public void writeBoolean(final boolean value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeBoolean(value);
+      bytesWriteBoolean(message, value);
    }
 
    public void writeByte(final byte value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeByte(value);
+      bytesWriteByte(message, value);
    }
 
    public void writeShort(final short value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeShort(value);
+      bytesWriteShort(message, value);
    }
 
    public void writeChar(final char value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeShort((short)value);
+      bytesWriteChar(message, value);
    }
 
    public void writeInt(final int value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeInt(value);
+      bytesWriteInt(message, value);
    }
 
    public void writeLong(final long value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeLong(value);
+      bytesWriteLong(message, value);
    }
 
    public void writeFloat(final float value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeInt(Float.floatToIntBits(value));
+      bytesWriteFloat(message, value);
    }
 
    public void writeDouble(final double value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeLong(Double.doubleToLongBits(value));
+      bytesWriteDouble(message, value);
    }
 
    public void writeUTF(final String value) throws JMSException
@@ -307,7 +321,7 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
       checkWrite();
       try
       {
-         getBuffer().writeUTF(value);
+         bytesWriteUTF(message, value);
       }
       catch (Exception e)
       {
@@ -316,67 +330,25 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
          je.initCause(e);
          throw je;
       }
+
    }
 
    public void writeBytes(final byte[] value) throws JMSException
    {
       checkWrite();
-      getBuffer().writeBytes(value);
+      bytesWriteBytes(message, value);
    }
 
    public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException
    {
       checkWrite();
-      getBuffer().writeBytes(value, offset, length);
+      bytesWriteBytes(message, value, offset, length);
    }
 
    public void writeObject(final Object value) throws JMSException
    {
-      if (value == null)
-      {
-         throw new NullPointerException("Attempt to write a null value");
-      }
-      if (value instanceof String)
-      {
-         writeUTF((String)value);
-      }
-      else if (value instanceof Boolean)
-      {
-         writeBoolean((Boolean)value);
-      }
-      else if (value instanceof Character)
-      {
-         writeChar((Character)value);
-      }
-      else if (value instanceof Byte)
-      {
-         writeByte((Byte)value);
-      }
-      else if (value instanceof Short)
-      {
-         writeShort((Short)value);
-      }
-      else if (value instanceof Integer)
-      {
-         writeInt((Integer)value);
-      }
-      else if (value instanceof Long)
-      {
-         writeLong((Long)value);
-      }
-      else if (value instanceof Float)
-      {
-         writeFloat((Float)value);
-      }
-      else if (value instanceof Double)
-      {
-         writeDouble((Double)value);
-      }
-      else if (value instanceof byte[])
-      {
-         writeBytes((byte[])value);
-      }
-      else
+      checkWrite();
+      if (!bytesWriteObject(message, value))
       {
          throw new MessageFormatException("Invalid object for properties");
       }
@@ -389,13 +361,9 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
          readOnly = true;
 
          bodyLength = message.getBodySize();
-
-         getBuffer().resetReaderIndex();
-      }
-      else
-      {
-         getBuffer().resetReaderIndex();
       }
+
+      bytesMessageReset(message);
    }
 
    @Override
@@ -407,11 +375,20 @@ public class HornetQBytesMessage extends HornetQMessage implements BytesMessage
    // HornetQRAMessage overrides ----------------------------------------
 
    @Override
-   public void clearBody()
+   public void clearBody() throws JMSException
    {
       super.clearBody();
 
-      getBuffer().clear();
+      try
+      {
+         getBuffer().clear();
+      }
+      catch (RuntimeException e)
+      {
+         JMSException e2 = new JMSException(e.getMessage());
+         e2.initCause(e);
+         throw e2;
+      }
    }
 
    public long getBodyLength() throws JMSException

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQConnection.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQConnection.java
index 5c13b1f..5d4413b 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQConnection.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQConnection.java
@@ -43,6 +43,7 @@ import org.hornetq.api.core.client.SessionFailureListener;
 import org.hornetq.api.jms.HornetQJMSConstants;
 import org.hornetq.core.client.impl.ClientSessionInternal;
 import org.hornetq.core.version.Version;
+import org.hornetq.reader.MessageUtil;
 import org.hornetq.utils.ConcurrentHashSet;
 import org.hornetq.utils.UUIDGenerator;
 import org.hornetq.utils.VersionLoader;
@@ -70,7 +71,7 @@ public class HornetQConnection extends HornetQConnectionForContextImpl implement
 
    public static final String EXCEPTION_DISCONNECT = "DISCONNECT";
 
-   public static final SimpleString CONNECTION_ID_PROPERTY_NAME = new SimpleString("__HQ_CID");
+   public static final SimpleString CONNECTION_ID_PROPERTY_NAME = MessageUtil.CONNECTION_ID_PROPERTY_NAME;
 
    // Static ---------------------------------------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMapMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMapMessage.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMapMessage.java
index 564da7d..d8d9cf7 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMapMessage.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMapMessage.java
@@ -28,6 +28,10 @@ import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.utils.TypedProperties;
 
+
+import static org.hornetq.reader.MapMessageUtil.writeBodyMap;
+import static org.hornetq.reader.MapMessageUtil.readBodyMap;
+
 /**
  * HornetQ implementation of a JMS MapMessage.
  *
@@ -46,7 +50,7 @@ public final class HornetQMapMessage extends HornetQMessage implements MapMessag
 
    // Attributes ----------------------------------------------------
 
-   private TypedProperties map = new TypedProperties();
+   private final TypedProperties map = new TypedProperties();
 
    private boolean invalid;
 
@@ -61,8 +65,6 @@ public final class HornetQMapMessage extends HornetQMessage implements MapMessag
    {
       super(HornetQMapMessage.TYPE, session);
 
-      map = new TypedProperties();
-
       invalid = true;
    }
 
@@ -368,7 +370,7 @@ public final class HornetQMapMessage extends HornetQMessage implements MapMessag
    // HornetQRAMessage overrides ----------------------------------------
 
    @Override
-   public void clearBody()
+   public void clearBody() throws JMSException
    {
       super.clearBody();
 
@@ -382,10 +384,7 @@ public final class HornetQMapMessage extends HornetQMessage implements MapMessag
    {
       if (invalid)
       {
-         message.getBodyBuffer().resetWriterIndex();
-
-         map.encode(message.getBodyBuffer());
-
+         writeBodyMap(message, map);
          invalid = false;
       }
 
@@ -397,7 +396,7 @@ public final class HornetQMapMessage extends HornetQMessage implements MapMessag
    {
       super.doBeforeReceive();
 
-      map.decode(message.getBodyBuffer());
+      readBodyMap(message, map);
    }
 
    // Package protected ---------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMessage.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMessage.java
index ac66539..16fb52e 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMessage.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQMessage.java
@@ -15,12 +15,10 @@ package org.hornetq.jms.client;
 import java.io.InputStream;
 import java.io.ObjectInputStream;
 import java.io.OutputStream;
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Map;
 
 import javax.jms.DeliveryMode;
@@ -40,10 +38,11 @@ import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.jms.HornetQJMSConstants;
-import org.hornetq.core.client.impl.ClientMessageImpl;
 import org.hornetq.core.message.impl.MessageInternal;
+import org.hornetq.reader.MessageUtil;
 import org.hornetq.utils.UUID;
 
+
 /**
  * HornetQ implementation of a JMS Message.
  * <br>
@@ -64,23 +63,6 @@ import org.hornetq.utils.UUID;
 public class HornetQMessage implements javax.jms.Message
 {
    // Constants -----------------------------------------------------
-
-   private static final SimpleString REPLYTO_HEADER_NAME = ClientMessageImpl.REPLYTO_HEADER_NAME;
-
-   private static final SimpleString CORRELATIONID_HEADER_NAME = new SimpleString("JMSCorrelationID");
-
-   private static final SimpleString TYPE_HEADER_NAME = new SimpleString("JMSType");
-
-   private static final SimpleString JMS = new SimpleString("JMS");
-
-   private static final SimpleString JMSX = new SimpleString("JMSX");
-
-   private static final SimpleString JMS_ = new SimpleString("JMS_");
-
-   private static final String JMSXDELIVERYCOUNT = "JMSXDeliveryCount";
-
-   private static final String JMSXGROUPID = "JMSXGroupID";
-
    public static final byte TYPE = org.hornetq.api.core.Message.DEFAULT_TYPE;
 
    public static Map<String, Object> coreMaptoJMSMap(final Map<String, Object> coreMessage)
@@ -363,55 +345,34 @@ public class HornetQMessage implements javax.jms.Message
 
    public byte[] getJMSCorrelationIDAsBytes() throws JMSException
    {
-      Object obj = message.getObjectProperty(HornetQMessage.CORRELATIONID_HEADER_NAME);
-
-      if (obj instanceof byte[])
-      {
-         return (byte[])obj;
-      }
-      else
-      {
-         return null;
-      }
+      return MessageUtil.getJMSCorrelationIDAsBytes(message);
    }
 
    public void setJMSCorrelationIDAsBytes(final byte[] correlationID) throws JMSException
    {
-      if (correlationID == null || correlationID.length == 0)
+      try
+      {
+         MessageUtil.setJMSCorrelationIDAsBytes(message, correlationID);
+      }
+      catch (HornetQException e)
       {
-         throw new JMSException("Please specify a non-zero length byte[]");
+         JMSException ex = new JMSException(e.getMessage());
+         ex.initCause(e);
+         throw ex;
       }
-      message.putBytesProperty(HornetQMessage.CORRELATIONID_HEADER_NAME, correlationID);
    }
 
    public void setJMSCorrelationID(final String correlationID) throws JMSException
    {
-      if (correlationID == null)
-      {
-         message.removeProperty(HornetQMessage.CORRELATIONID_HEADER_NAME);
-
-         jmsCorrelationID = null;
-      }
-      else
-      {
-         message.putStringProperty(HornetQMessage.CORRELATIONID_HEADER_NAME, new SimpleString(correlationID));
-
-         jmsCorrelationID = correlationID;
-      }
+      MessageUtil.setJMSCorrelationID(message, correlationID);
+      jmsCorrelationID = correlationID;
    }
 
    public String getJMSCorrelationID() throws JMSException
    {
       if (jmsCorrelationID == null)
       {
-         try
-         {
-            jmsCorrelationID = message.getStringProperty(HornetQMessage.CORRELATIONID_HEADER_NAME);
-         }
-         catch (HornetQPropertyConversionException e)
-         {
-            jmsCorrelationID = null;
-         }
+         jmsCorrelationID = MessageUtil.getJMSCorrelationID(message);
       }
 
       return jmsCorrelationID;
@@ -421,7 +382,8 @@ public class HornetQMessage implements javax.jms.Message
    {
       if (replyTo == null)
       {
-         SimpleString repl = message.getSimpleStringProperty(HornetQMessage.REPLYTO_HEADER_NAME);
+
+         SimpleString repl = MessageUtil.getJMSReplyTo(message);
 
          if (repl != null)
          {
@@ -433,10 +395,10 @@ public class HornetQMessage implements javax.jms.Message
 
    public void setJMSReplyTo(final Destination dest) throws JMSException
    {
+
       if (dest == null)
       {
-         message.removeProperty(HornetQMessage.REPLYTO_HEADER_NAME);
-
+         MessageUtil.setJMSReplyTo(message, null);
          replyTo = null;
       }
       else
@@ -448,7 +410,7 @@ public class HornetQMessage implements javax.jms.Message
 
          HornetQDestination jbd = (HornetQDestination)dest;
 
-         message.putStringProperty(HornetQMessage.REPLYTO_HEADER_NAME, jbd.getSimpleAddress());
+         MessageUtil.setJMSReplyTo(message, jbd.getSimpleAddress());
 
          replyTo = jbd;
       }
@@ -520,7 +482,7 @@ public class HornetQMessage implements javax.jms.Message
    {
       if (type != null)
       {
-         message.putStringProperty(HornetQMessage.TYPE_HEADER_NAME, new SimpleString(type));
+         MessageUtil.setJMSType(message, type);
 
          jmsType = type;
       }
@@ -530,12 +492,7 @@ public class HornetQMessage implements javax.jms.Message
    {
       if (jmsType == null)
       {
-         SimpleString ss = message.getSimpleStringProperty(HornetQMessage.TYPE_HEADER_NAME);
-
-         if (ss != null)
-         {
-            jmsType = ss.toString();
-         }
+         jmsType = MessageUtil.getJMSType(message);
       }
       return jmsType;
    }
@@ -564,35 +521,20 @@ public class HornetQMessage implements javax.jms.Message
 
    public void clearProperties() throws JMSException
    {
-      List<SimpleString> toRemove = new ArrayList<SimpleString>();
-
-      for (SimpleString propName : message.getPropertyNames())
-      {
-         if (!propName.startsWith(HornetQMessage.JMS) || propName.startsWith(HornetQMessage.JMSX) ||
-             propName.startsWith(HornetQMessage.JMS_))
-         {
-            toRemove.add(propName);
-         }
-      }
 
-      for (SimpleString propName : toRemove)
-      {
-         message.removeProperty(propName);
-      }
+      MessageUtil.clearProperties(message);
 
       propertiesReadOnly = false;
    }
 
-   public void clearBody()
+   public void clearBody() throws JMSException
    {
       readOnly = false;
    }
 
    public boolean propertyExists(final String name) throws JMSException
    {
-      return message.containsProperty(new SimpleString(name)) || name.equals(HornetQMessage.JMSXDELIVERYCOUNT) ||
-             HornetQMessage.JMSXGROUPID.equals(name) &&
-             message.containsProperty(org.hornetq.api.core.Message.HDR_GROUP_ID);
+      return MessageUtil.propertyExists(message, name);
    }
 
    public boolean getBooleanProperty(final String name) throws JMSException
@@ -633,7 +575,7 @@ public class HornetQMessage implements javax.jms.Message
 
    public int getIntProperty(final String name) throws JMSException
    {
-      if (HornetQMessage.JMSXDELIVERYCOUNT.equals(name))
+      if (MessageUtil.JMSXDELIVERYCOUNT.equals(name))
       {
          return message.getDeliveryCount();
       }
@@ -650,7 +592,7 @@ public class HornetQMessage implements javax.jms.Message
 
    public long getLongProperty(final String name) throws JMSException
    {
-      if (HornetQMessage.JMSXDELIVERYCOUNT.equals(name))
+      if (MessageUtil.JMSXDELIVERYCOUNT.equals(name))
       {
          return message.getDeliveryCount();
       }
@@ -691,14 +633,14 @@ public class HornetQMessage implements javax.jms.Message
 
    public String getStringProperty(final String name) throws JMSException
    {
-      if (HornetQMessage.JMSXDELIVERYCOUNT.equals(name))
+      if (MessageUtil.JMSXDELIVERYCOUNT.equals(name))
       {
          return String.valueOf(message.getDeliveryCount());
       }
 
       try
       {
-         if (HornetQMessage.JMSXGROUPID.equals(name))
+         if (MessageUtil.JMSXGROUPID.equals(name))
          {
             return message.getStringProperty(org.hornetq.api.core.Message.HDR_GROUP_ID);
          }
@@ -715,7 +657,7 @@ public class HornetQMessage implements javax.jms.Message
 
    public Object getObjectProperty(final String name) throws JMSException
    {
-      if (HornetQMessage.JMSXDELIVERYCOUNT.equals(name))
+      if (MessageUtil.JMSXDELIVERYCOUNT.equals(name))
       {
          return String.valueOf(message.getDeliveryCount());
       }
@@ -732,20 +674,7 @@ public class HornetQMessage implements javax.jms.Message
    @Override
    public Enumeration getPropertyNames() throws JMSException
    {
-      HashSet<String> set = new HashSet<String>();
-
-      for (SimpleString propName : message.getPropertyNames())
-      {
-         if ((!propName.startsWith(HornetQMessage.JMS) || propName.startsWith(HornetQMessage.JMSX) ||
-             propName.startsWith(HornetQMessage.JMS_)) && !propName.startsWith(HornetQConnection.CONNECTION_ID_PROPERTY_NAME))
-         {
-            set.add(propName.toString());
-         }
-      }
-
-      set.add(HornetQMessage.JMSXDELIVERYCOUNT);
-
-      return Collections.enumeration(set);
+      return Collections.enumeration(MessageUtil.getPropertyNames(message));
    }
 
    public void setBooleanProperty(final String name, final boolean value) throws JMSException
@@ -795,7 +724,7 @@ public class HornetQMessage implements javax.jms.Message
    {
       checkProperty(name);
 
-      if (HornetQMessage.JMSXGROUPID.equals(name))
+      if (MessageUtil.JMSXGROUPID.equals(name))
       {
          message.putStringProperty(org.hornetq.api.core.Message.HDR_GROUP_ID, SimpleString.toSimpleString(value));
       }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQObjectMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQObjectMessage.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQObjectMessage.java
index 23a49d0..ff1e452 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQObjectMessage.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQObjectMessage.java
@@ -164,7 +164,7 @@ public class HornetQObjectMessage extends HornetQMessage implements ObjectMessag
    }
 
    @Override
-   public void clearBody()
+   public void clearBody() throws JMSException
    {
       super.clearBody();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQQueue.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQQueue.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQQueue.java
index b496dc0..46ec8f0 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQQueue.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQQueue.java
@@ -60,7 +60,7 @@ public class HornetQQueue extends HornetQDestination implements Queue
       super(address, name, temporary, true, session);
    }
 
-   protected HornetQQueue(final String address, final String name)
+   public HornetQQueue(final String address, final String name)
    {
       super(address, name, false, true, null);
    }


[29/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java
new file mode 100644
index 0000000..781a11c
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ClientSASLPlain.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.sasl;
+
+import org.proton.plug.ClientSASL;
+
+/**
+ * This is a simple implementation provided with just user/password
+ * TODO: this interface will probaby change as we are challenged with more SASL cases where there is a communication between client and server to determine the authentication
+ *
+ * @author Clebert Suconic
+ */
+public class ClientSASLPlain implements ClientSASL
+{
+   private String username;
+   private String password;
+
+   public ClientSASLPlain(String user, String password)
+   {
+      this.username = user;
+      this.password = password;
+   }
+
+   public String getName()
+   {
+      return "PLAIN";
+   }
+
+   public byte[] getBytes()
+   {
+
+      if (username == null)
+      {
+         username = "";
+      }
+
+      if (password == null)
+      {
+         password = "";
+      }
+
+      byte[] usernameBytes = username.getBytes();
+      byte[] passwordBytes = password.getBytes();
+      byte[] data = new byte[usernameBytes.length + passwordBytes.length + 2];
+      System.arraycopy(usernameBytes, 0, data, 1, usernameBytes.length);
+      System.arraycopy(passwordBytes, 0, data, 2 + usernameBytes.length, passwordBytes.length);
+      return data;
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java
new file mode 100644
index 0000000..85e9aac
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/PlainSASLResult.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.sasl;
+
+import org.proton.plug.SASLResult;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class PlainSASLResult implements SASLResult
+{
+   private boolean success;
+   private String user;
+   private String password;
+
+   public PlainSASLResult(boolean success, String user, String password)
+   {
+      this.success = success;
+      this.user = user;
+      this.password = password;
+   }
+
+   @Override
+   public String getUser()
+   {
+      return user;
+   }
+
+   public String getPassword()
+   {
+      return password;
+   }
+
+   @Override
+   public boolean isSuccess()
+   {
+      return success;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java
new file mode 100644
index 0000000..490c89c
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/sasl/ServerSASLPlain.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.sasl;
+
+import org.proton.plug.SASLResult;
+import org.proton.plug.ServerSASL;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ServerSASLPlain implements ServerSASL
+{
+   public static final String NAME = "PLAIN";
+
+   @Override
+   public String getName()
+   {
+      return NAME;
+   }
+
+   @Override
+   public SASLResult processSASL(byte[] data)
+   {
+
+      String username = null;
+      String password = null;
+      String bytes = new String(data);
+      String[] credentials = bytes.split(Character.toString((char) 0));
+      int offSet = 0;
+      if (credentials.length > 0)
+      {
+         if (credentials[0].length() == 0)
+         {
+            offSet = 1;
+         }
+
+         if (credentials.length >= offSet)
+         {
+            username = credentials[offSet];
+         }
+         if (credentials.length >= (offSet + 1))
+         {
+            password = credentials[offSet + 1];
+         }
+      }
+
+      boolean success = authenticate(username, password);
+
+      return new PlainSASLResult(success, username, password);
+   }
+
+
+   /**
+    * Hook for subclasses to perform the authentication here
+    *
+    * @param user
+    * @param password
+    */
+   protected boolean authenticate(String user, String password)
+   {
+      return true;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java
new file mode 100644
index 0000000..7d12f31
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ByteUtil.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.UnpooledByteBufAllocator;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ByteUtil
+{
+   public static void debugFrame(String message, ByteBuf byteIn)
+   {
+      int location = byteIn.readerIndex();
+      // debugging
+      byte[] frame = new byte[byteIn.writerIndex()];
+      byteIn.readBytes(frame);
+
+      try
+      {
+         System.out.println(message + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 8, 16));
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+      }
+
+      byteIn.readerIndex(location);
+   }
+
+
+   public static String formatGroup(String str, int groupSize, int lineBreak)
+   {
+      StringBuffer buffer = new StringBuffer();
+
+      int line = 1;
+      buffer.append("/*  1 */ \"");
+      for (int i = 0; i < str.length(); i += groupSize)
+      {
+         buffer.append(str.substring(i, i + Math.min(str.length() - i, groupSize)));
+
+         if ((i + groupSize) % lineBreak == 0)
+         {
+            buffer.append("\" +\n/* ");
+            line++;
+            if (line < 10)
+            {
+               buffer.append(" ");
+            }
+            buffer.append(Integer.toString(line) + " */ \"");
+         }
+         else if ((i + groupSize) % groupSize == 0 && str.length() - i > groupSize)
+         {
+            buffer.append("\" + \"");
+         }
+      }
+
+      buffer.append("\";");
+
+      return buffer.toString();
+
+   }
+
+   protected static final char[] hexArray = "0123456789ABCDEF".toCharArray();
+
+   public static String bytesToHex(byte[] bytes)
+   {
+      char[] hexChars = new char[bytes.length * 2];
+      for (int j = 0; j < bytes.length; j++)
+      {
+         int v = bytes[j] & 0xFF;
+         hexChars[j * 2] = hexArray[v >>> 4];
+         hexChars[j * 2 + 1] = hexArray[v & 0x0F];
+      }
+      return new String(hexChars);
+   }
+
+   public static byte[] hexStringToByteArray(String s)
+   {
+      int len = s.length();
+      byte[] data = new byte[len / 2];
+      for (int i = 0; i < len; i += 2)
+      {
+         data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+            + Character.digit(s.charAt(i + 1), 16));
+      }
+      return data;
+   }
+
+   public static byte[] longToBytes(long x)
+   {
+      ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.heapBuffer(8, 8);
+      buffer.writeLong(x);
+      return buffer.array();
+   }
+
+   public static String maxString(String value, int size)
+   {
+      if (value.length() < size)
+      {
+         return value;
+      }
+      else
+      {
+         return value.substring(0, size / 2) + " ... " + value.substring(value.length() - size / 2);
+      }
+   }
+
+   public static String bytesToHex(byte[] bytes, int groupSize)
+   {
+      char[] hexChars = new char[bytes.length * 2 + numberOfGroups(bytes, groupSize)];
+      int outPos = 0;
+      for (int j = 0; j < bytes.length; j++)
+      {
+         if (j > 0 && j % groupSize == 0)
+         {
+            hexChars[outPos++] = ' ';
+         }
+         int v = bytes[j] & 0xFF;
+         hexChars[outPos++] = hexArray[v >>> 4];
+         hexChars[outPos++] = hexArray[v & 0x0F];
+      }
+      return new String(hexChars);
+   }
+
+   private static int numberOfGroups(byte[] bytes, int groupSize)
+   {
+      int groups = bytes.length / groupSize;
+
+      if (bytes.length % groupSize == 0)
+      {
+         groups--;
+      }
+
+      return groups;
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java
new file mode 100644
index 0000000..bb10c5a
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CodecCache.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+import org.apache.qpid.proton.codec.AMQPDefinedTypes;
+import org.apache.qpid.proton.codec.DecoderImpl;
+import org.apache.qpid.proton.codec.EncoderImpl;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class CodecCache
+{
+
+   private static class EncoderDecoderPair
+   {
+      DecoderImpl decoder = new DecoderImpl();
+      EncoderImpl encoder = new EncoderImpl(decoder);
+
+      {
+         AMQPDefinedTypes.registerAllTypes(decoder, encoder);
+      }
+   }
+
+   private static final ThreadLocal<EncoderDecoderPair> tlsCodec = new ThreadLocal<EncoderDecoderPair>()
+   {
+      @Override
+      protected EncoderDecoderPair initialValue()
+      {
+         return new EncoderDecoderPair();
+      }
+   };
+
+   public static DecoderImpl getDecoder()
+   {
+      return tlsCodec.get().decoder;
+   }
+
+   public static EncoderImpl getEncoder()
+   {
+      return tlsCodec.get().encoder;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java
new file mode 100644
index 0000000..36deee2
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/CreditsSemaphore.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+import java.util.concurrent.locks.AbstractQueuedSynchronizer;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class CreditsSemaphore
+{
+
+   @SuppressWarnings("serial")
+   private static class Sync extends AbstractQueuedSynchronizer
+   {
+      public Sync(int initial)
+      {
+         setState(initial);
+      }
+
+      public int getCredits()
+      {
+         return getState();
+      }
+
+      @Override
+      public int tryAcquireShared(final int numberOfAqcquires)
+      {
+         for (;;)
+         {
+            int actualSize = getState();
+            int newValue = actualSize - numberOfAqcquires;
+
+            if (newValue < 0)
+            {
+               if (actualSize == getState())
+               {
+                  return -1;
+               }
+            }
+            else if (compareAndSetState(actualSize, newValue))
+            {
+               return newValue;
+            }
+         }
+      }
+
+      @Override
+      public boolean tryReleaseShared(final int numberOfReleases)
+      {
+         for (;;)
+         {
+            int actualSize = getState();
+            int newValue = actualSize + numberOfReleases;
+
+            if (compareAndSetState(actualSize, newValue))
+            {
+               return true;
+            }
+
+         }
+      }
+
+      public void setCredits(final int credits)
+      {
+         for (;;)
+         {
+            int actualState = getState();
+            if (compareAndSetState(actualState, credits))
+            {
+               // This is to wake up any pending threads that could be waiting on queued
+               releaseShared(0);
+               return;
+            }
+         }
+      }
+   }
+
+   private final Sync sync;
+
+
+   public CreditsSemaphore(int initialCredits)
+   {
+      sync = new Sync(initialCredits);
+   }
+
+   public void acquire() throws InterruptedException
+   {
+      sync.acquireSharedInterruptibly(1);
+   }
+
+   public boolean tryAcquire()
+   {
+      return sync.tryAcquireShared(1) >= 0;
+   }
+
+   public void release() throws InterruptedException
+   {
+      sync.releaseShared(1);
+   }
+
+   public void release(int credits) throws InterruptedException
+   {
+      sync.releaseShared(credits);
+   }
+
+   public void setCredits(int credits)
+   {
+      sync.setCredits(credits);
+   }
+
+   public int getCredits()
+   {
+      return sync.getCredits();
+   }
+
+   public boolean hasQueuedThreads()
+   {
+      return sync.hasQueuedThreads();
+   }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java
new file mode 100644
index 0000000..6481413
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DebugInfo.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class DebugInfo
+{
+   public static final boolean debug = false;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java
new file mode 100644
index 0000000..7430c44
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/DeliveryUtil.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.message.Message;
+import org.apache.qpid.proton.message.impl.MessageImpl;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class DeliveryUtil
+{
+
+   public static int readDelivery(Receiver receiver, ByteBuf buffer)
+   {
+      int initial = buffer.writerIndex();
+      // optimization by norman
+      int count;
+      while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0)
+      {
+         // Increment the writer index by the number of bytes written into it while calling recv.
+         buffer.writerIndex(buffer.writerIndex() + count);
+      }
+      return buffer.writerIndex() - initial;
+   }
+
+
+   public static MessageImpl decodeMessageImpl(ByteBuf buffer)
+   {
+      MessageImpl message = (MessageImpl) Message.Factory.create();
+      message.decode(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), buffer.readableBytes());
+      return message;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java
new file mode 100644
index 0000000..3a36f7d
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/FutureRunnable.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class FutureRunnable implements Runnable
+{
+   private final ReusableLatch latch;
+
+   public FutureRunnable(final int initialIterations)
+   {
+      latch = new ReusableLatch(initialIterations);
+   }
+
+   public FutureRunnable()
+   {
+      this(0);
+   }
+
+   public void run()
+   {
+      latch.countDown();
+   }
+
+   public void countUp()
+   {
+      latch.countUp();
+   }
+
+   public void countDown()
+   {
+      latch.countDown();
+   }
+
+   public int getCount()
+   {
+      return latch.getCount();
+   }
+
+   public void await() throws InterruptedException
+   {
+      latch.await();
+   }
+
+   public boolean await(long timeWait, TimeUnit timeUnit) throws InterruptedException
+   {
+      return latch.await(timeWait, timeUnit);
+   }
+
+   public boolean await(long milliseconds) throws InterruptedException
+   {
+      return latch.await(milliseconds);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java
new file mode 100644
index 0000000..464bc2c
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/NettyWritable.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+/**
+ * @author Clebert Suconic
+ */
+
+
+import java.nio.ByteBuffer;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.qpid.proton.codec.WritableBuffer;
+
+/**
+ * This is to use NettyBuffer within Proton
+ *
+ * @author Clebert Suconic
+ */
+
+public class NettyWritable implements WritableBuffer
+{
+
+   final ByteBuf nettyBuffer;
+
+   public NettyWritable(ByteBuf nettyBuffer)
+   {
+      this.nettyBuffer = nettyBuffer;
+   }
+
+
+   @Override
+   public void put(byte b)
+   {
+      nettyBuffer.writeByte(b);
+   }
+
+   @Override
+   public void putFloat(float f)
+   {
+      nettyBuffer.writeFloat(f);
+   }
+
+   @Override
+   public void putDouble(double d)
+   {
+      nettyBuffer.writeDouble(d);
+   }
+
+   @Override
+   public void put(byte[] src, int offset, int length)
+   {
+      nettyBuffer.writeBytes(src, offset, length);
+   }
+
+   @Override
+   public void putShort(short s)
+   {
+      nettyBuffer.writeShort(s);
+   }
+
+   @Override
+   public void putInt(int i)
+   {
+      nettyBuffer.writeInt(i);
+   }
+
+   @Override
+   public void putLong(long l)
+   {
+      nettyBuffer.writeLong(l);
+   }
+
+   @Override
+   public boolean hasRemaining()
+   {
+      return nettyBuffer.writerIndex() < nettyBuffer.capacity();
+   }
+
+   @Override
+   public int remaining()
+   {
+      return nettyBuffer.capacity() - nettyBuffer.writerIndex();
+   }
+
+   @Override
+   public int position()
+   {
+      return nettyBuffer.writerIndex();
+   }
+
+   @Override
+   public void position(int position)
+   {
+      nettyBuffer.writerIndex(position);
+   }
+
+   @Override
+   public void put(ByteBuffer payload)
+   {
+      nettyBuffer.writeBytes(payload);
+   }
+
+   @Override
+   public int limit()
+   {
+      return nettyBuffer.capacity();
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java
new file mode 100644
index 0000000..ccebe3f
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ProtonServerMessage.java
@@ -0,0 +1,596 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.util;
+
+import java.nio.ByteBuffer;
+
+import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
+import org.apache.qpid.proton.amqp.messaging.DeliveryAnnotations;
+import org.apache.qpid.proton.amqp.messaging.Footer;
+import org.apache.qpid.proton.amqp.messaging.Header;
+import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
+import org.apache.qpid.proton.amqp.messaging.Properties;
+import org.apache.qpid.proton.amqp.messaging.Section;
+import org.apache.qpid.proton.codec.DecoderImpl;
+import org.apache.qpid.proton.codec.EncoderImpl;
+import org.apache.qpid.proton.codec.WritableBuffer;
+import org.apache.qpid.proton.message.MessageError;
+import org.apache.qpid.proton.message.MessageFormat;
+import org.apache.qpid.proton.message.ProtonJMessage;
+
+/**
+ * This is a serverMessage that won't deal with the body
+ *
+ * @author Clebert Suconic
+ */
+public class ProtonServerMessage implements ProtonJMessage
+{
+   private Header header;
+   private DeliveryAnnotations deliveryAnnotations;
+   private MessageAnnotations messageAnnotations;
+   private Properties properties;
+   private ApplicationProperties applicationProperties;
+
+   // This should include a raw body of both footer and body
+   private byte[] rawBody;
+
+   private Section parsedBody;
+   private Footer parsedFooter;
+
+   private final int EOF = 0;
+
+   // TODO: Enumerations maybe?
+   private static final int HEADER_TYPE = 0x070;
+   private static final int DELIVERY_ANNOTATIONS = 0x071;
+   private static final int MESSAGE_ANNOTATIONS = 0x072;
+   private static final int PROPERTIES = 0x073;
+   private static final int APPLICATION_PROPERTIES = 0x074;
+
+
+   /**
+    * This will decode a ByteBuffer tha represents the entire message.
+    * Set the limits around the parameter.
+    *
+    * @param buffer a limited buffer for the message
+    */
+   public void decode(ByteBuffer buffer)
+   {
+
+      DecoderImpl decoder = CodecCache.getDecoder();
+
+
+      header = null;
+      deliveryAnnotations = null;
+      messageAnnotations = null;
+      properties = null;
+      applicationProperties = null;
+      rawBody = null;
+
+      decoder.setByteBuffer(buffer);
+      try
+      {
+         int type = readType(buffer, decoder);
+         if (type == HEADER_TYPE)
+         {
+            header = (Header) readSection(buffer, decoder);
+            type = readType(buffer, decoder);
+
+         }
+
+         if (type == DELIVERY_ANNOTATIONS)
+         {
+            deliveryAnnotations = (DeliveryAnnotations) readSection(buffer, decoder);
+            type = readType(buffer, decoder);
+
+         }
+
+         if (type == MESSAGE_ANNOTATIONS)
+         {
+            messageAnnotations = (MessageAnnotations) readSection(buffer, decoder);
+            type = readType(buffer, decoder);
+         }
+
+         if (type == PROPERTIES)
+         {
+            properties = (Properties) readSection(buffer, decoder);
+            type = readType(buffer, decoder);
+
+         }
+
+         if (type == APPLICATION_PROPERTIES)
+         {
+            applicationProperties = (ApplicationProperties) readSection(buffer, decoder);
+            type = readType(buffer, decoder);
+         }
+
+         if (type != EOF)
+         {
+            rawBody = new byte[buffer.limit() - buffer.position()];
+            buffer.get(rawBody);
+         }
+      }
+      finally
+      {
+         decoder.setByteBuffer(null);
+      }
+
+   }
+
+
+   public void encode(ByteBuffer buffer)
+   {
+      WritableBuffer writableBuffer = new WritableBuffer.ByteBufferWrapper(buffer);
+      encode(writableBuffer);
+   }
+
+   public int encode(WritableBuffer writableBuffer)
+   {
+      final int firstPosition = writableBuffer.position();
+
+      EncoderImpl encoder = CodecCache.getEncoder();
+      encoder.setByteBuffer(writableBuffer);
+
+      try
+      {
+         if (header != null)
+         {
+            encoder.writeObject(header);
+         }
+         if (deliveryAnnotations != null)
+         {
+            encoder.writeObject(deliveryAnnotations);
+         }
+         if (messageAnnotations != null)
+         {
+            encoder.writeObject(messageAnnotations);
+         }
+         if (properties != null)
+         {
+            encoder.writeObject(properties);
+         }
+         if (applicationProperties != null)
+         {
+            encoder.writeObject(applicationProperties);
+         }
+
+         // It should write either the parsed one or the rawBody
+         if (parsedBody != null)
+         {
+            encoder.writeObject(parsedBody);
+            if (parsedFooter != null)
+            {
+               encoder.writeObject(parsedFooter);
+            }
+         }
+         else if (rawBody != null)
+         {
+            writableBuffer.put(rawBody, 0, rawBody.length);
+         }
+
+         return writableBuffer.position() - firstPosition;
+      }
+      finally
+      {
+         encoder.setByteBuffer((WritableBuffer) null);
+      }
+   }
+
+
+   private int readType(ByteBuffer buffer, DecoderImpl decoder)
+   {
+
+      int pos = buffer.position();
+
+      if (!buffer.hasRemaining())
+      {
+         return EOF;
+      }
+      try
+      {
+         if (buffer.get() != 0)
+         {
+            return EOF;
+         }
+         else
+         {
+            return ((Number) decoder.readObject()).intValue();
+         }
+      }
+      finally
+      {
+         buffer.position(pos);
+      }
+   }
+
+
+   private Section readSection(ByteBuffer buffer, DecoderImpl decoder)
+   {
+      if (buffer.hasRemaining())
+      {
+         return (Section) decoder.readObject();
+      }
+      else
+      {
+         return null;
+      }
+   }
+
+
+   // At the moment we only need encode implemented!!!
+   @Override
+   public boolean isDurable()
+   {
+      return false;
+   }
+
+   @Override
+   public long getDeliveryCount()
+   {
+      return 0;
+   }
+
+   @Override
+   public short getPriority()
+   {
+      return 0;
+   }
+
+   @Override
+   public boolean isFirstAcquirer()
+   {
+      return false;
+   }
+
+   @Override
+   public long getTtl()
+   {
+      return 0;
+   }
+
+   @Override
+   public void setDurable(boolean durable)
+   {
+
+   }
+
+   @Override
+   public void setTtl(long ttl)
+   {
+
+   }
+
+   @Override
+   public void setDeliveryCount(long deliveryCount)
+   {
+
+   }
+
+   @Override
+   public void setFirstAcquirer(boolean firstAcquirer)
+   {
+
+   }
+
+   @Override
+   public void setPriority(short priority)
+   {
+
+   }
+
+   @Override
+   public Object getMessageId()
+   {
+      return null;
+   }
+
+   @Override
+   public long getGroupSequence()
+   {
+      return 0;
+   }
+
+   @Override
+   public String getReplyToGroupId()
+   {
+      return null;
+   }
+
+   @Override
+   public long getCreationTime()
+   {
+      return 0;
+   }
+
+   @Override
+   public String getAddress()
+   {
+      return null;
+   }
+
+   @Override
+   public byte[] getUserId()
+   {
+      return new byte[0];
+   }
+
+   @Override
+   public String getReplyTo()
+   {
+      return null;
+   }
+
+   @Override
+   public String getGroupId()
+   {
+      return null;
+   }
+
+   @Override
+   public String getContentType()
+   {
+      return null;
+   }
+
+   @Override
+   public long getExpiryTime()
+   {
+      return 0;
+   }
+
+   @Override
+   public Object getCorrelationId()
+   {
+      return null;
+   }
+
+   @Override
+   public String getContentEncoding()
+   {
+      return null;
+   }
+
+   @Override
+   public String getSubject()
+   {
+      return null;
+   }
+
+   @Override
+   public void setGroupSequence(long groupSequence)
+   {
+
+   }
+
+   @Override
+   public void setUserId(byte[] userId)
+   {
+
+   }
+
+   @Override
+   public void setCreationTime(long creationTime)
+   {
+
+   }
+
+   @Override
+   public void setSubject(String subject)
+   {
+
+   }
+
+   @Override
+   public void setGroupId(String groupId)
+   {
+
+   }
+
+   @Override
+   public void setAddress(String to)
+   {
+
+   }
+
+   @Override
+   public void setExpiryTime(long absoluteExpiryTime)
+   {
+
+   }
+
+   @Override
+   public void setReplyToGroupId(String replyToGroupId)
+   {
+
+   }
+
+   @Override
+   public void setContentEncoding(String contentEncoding)
+   {
+
+   }
+
+   @Override
+   public void setContentType(String contentType)
+   {
+
+   }
+
+   @Override
+   public void setReplyTo(String replyTo)
+   {
+
+   }
+
+   @Override
+   public void setCorrelationId(Object correlationId)
+   {
+
+   }
+
+   @Override
+   public void setMessageId(Object messageId)
+   {
+
+   }
+
+   @Override
+   public Header getHeader()
+   {
+      return null;
+   }
+
+   @Override
+   public DeliveryAnnotations getDeliveryAnnotations()
+   {
+      return null;
+   }
+
+   @Override
+   public MessageAnnotations getMessageAnnotations()
+   {
+      return null;
+   }
+
+   @Override
+   public Properties getProperties()
+   {
+      return null;
+   }
+
+   @Override
+   public ApplicationProperties getApplicationProperties()
+   {
+      return null;
+   }
+
+   @Override
+   public Section getBody()
+   {
+      return null;
+   }
+
+   @Override
+   public Footer getFooter()
+   {
+      return null;
+   }
+
+   @Override
+   public void setHeader(Header header)
+   {
+
+   }
+
+   @Override
+   public void setDeliveryAnnotations(DeliveryAnnotations deliveryAnnotations)
+   {
+
+   }
+
+   @Override
+   public void setMessageAnnotations(MessageAnnotations messageAnnotations)
+   {
+
+   }
+
+   @Override
+   public void setProperties(Properties properties)
+   {
+
+   }
+
+   @Override
+   public void setApplicationProperties(ApplicationProperties applicationProperties)
+   {
+
+   }
+
+   @Override
+   public void setBody(Section body)
+   {
+
+   }
+
+   @Override
+   public void setFooter(Footer footer)
+   {
+
+   }
+
+   @Override
+   public int decode(byte[] data, int offset, int length)
+   {
+      return 0;
+   }
+
+   @Override
+   public int encode(byte[] data, int offset, int length)
+   {
+      return 0;
+   }
+
+   @Override
+   public void load(Object data)
+   {
+
+   }
+
+   @Override
+   public Object save()
+   {
+      return null;
+   }
+
+   @Override
+   public String toAMQPFormat(Object value)
+   {
+      return null;
+   }
+
+   @Override
+   public Object parseAMQPFormat(String value)
+   {
+      return null;
+   }
+
+   @Override
+   public void setMessageFormat(MessageFormat format)
+   {
+
+   }
+
+   @Override
+   public MessageFormat getMessageFormat()
+   {
+      return null;
+   }
+
+   @Override
+   public void clear()
+   {
+
+   }
+
+   @Override
+   public MessageError getError()
+   {
+      return null;
+   }
+
+   @Override
+   public int encode2(byte[] data, int offset, int length)
+   {
+      return 0;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java
new file mode 100644
index 0000000..4f1f01e
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/util/ReusableLatch.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.proton.plug.util;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.AbstractQueuedSynchronizer;
+
+/**
+ * <p>This class will use the framework provided to by AbstractQueuedSynchronizer.</p>
+ * <p>AbstractQueuedSynchronizer is the framework for any sort of concurrent synchronization, such as Semaphores, events, etc, based on AtomicIntegers.</p>
+ * <p/>
+ * <p>This class works just like CountDownLatch, with the difference you can also increase the counter</p>
+ * <p/>
+ * <p>It could be used for sync points when one process is feeding the latch while another will wait when everything is done. (e.g. waiting IO completions to finish)</p>
+ * <p/>
+ * <p>On HornetQ we have the requirement of increment and decrement a counter until the user fires a ready handler (commit). At that point we just act as a regular countDown.</p>
+ * <p/>
+ * <p>Note: This latch is reusable. Once it reaches zero, you can call up again, and reuse it on further waits.</p>
+ * <p/>
+ * <p>For example: prepareTransaction will wait for the current completions, and further adds will be called on the latch. Later on when commit is called you can reuse the same latch.</p>
+ *
+ * @author Clebert Suconic
+ */
+public class ReusableLatch
+{
+   /**
+    * Look at the doc and examples provided by AbstractQueuedSynchronizer for more information
+    *
+    * @see AbstractQueuedSynchronizer
+    */
+   @SuppressWarnings("serial")
+   private static class CountSync extends AbstractQueuedSynchronizer
+   {
+      public CountSync(int count)
+      {
+         setState(count);
+      }
+
+      public int getCount()
+      {
+         return getState();
+      }
+
+      public void setCount(final int count)
+      {
+         setState(count);
+      }
+
+      @Override
+      public int tryAcquireShared(final int numberOfAqcquires)
+      {
+         return getState() == 0 ? 1 : -1;
+      }
+
+      public void add()
+      {
+         for (;;)
+         {
+            int actualState = getState();
+            int newState = actualState + 1;
+            if (compareAndSetState(actualState, newState))
+            {
+               return;
+            }
+         }
+      }
+
+      @Override
+      public boolean tryReleaseShared(final int numberOfReleases)
+      {
+         for (;;)
+         {
+            int actualState = getState();
+            if (actualState == 0)
+            {
+               return true;
+            }
+
+            int newState = actualState - numberOfReleases;
+
+            if (newState < 0)
+            {
+               newState = 0;
+            }
+
+            if (compareAndSetState(actualState, newState))
+            {
+               return newState == 0;
+            }
+         }
+      }
+   }
+
+   private final CountSync control;
+
+   public ReusableLatch()
+   {
+      this(0);
+   }
+
+   public ReusableLatch(final int count)
+   {
+      control = new CountSync(count);
+   }
+
+   public int getCount()
+   {
+      return control.getCount();
+   }
+
+   public void setCount(final int count)
+   {
+      control.setCount(count);
+   }
+
+   public void countUp()
+   {
+      control.add();
+   }
+
+   public void countDown()
+   {
+      control.releaseShared(1);
+   }
+
+
+   public void countDown(final int count)
+   {
+      control.releaseShared(count);
+   }
+
+   public void await() throws InterruptedException
+   {
+      control.acquireSharedInterruptibly(1);
+   }
+
+   public boolean await(final long milliseconds) throws InterruptedException
+   {
+      return control.tryAcquireSharedNanos(1, TimeUnit.MILLISECONDS.toNanos(milliseconds));
+   }
+
+   public boolean await(final long timeWait, TimeUnit timeUnit) throws InterruptedException
+   {
+      return control.tryAcquireSharedNanos(1, timeUnit.toNanos(timeWait));
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java
new file mode 100644
index 0000000..23c158f
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/AbstractJMSTest.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.ExceptionListener;
+import javax.jms.JMSException;
+import javax.jms.Queue;
+
+import java.lang.ref.WeakReference;
+
+//import io.hawtjms.jms.JmsConnectionFactory;
+//import io.hawtjms.jms.JmsQueue;
+import org.apache.qpid.amqp_1_0.jms.impl.ConnectionFactoryImpl;
+import org.apache.qpid.amqp_1_0.jms.impl.QueueImpl;
+import org.proton.plug.test.minimalserver.DumbServer;
+import org.proton.plug.test.minimalserver.MinimalServer;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class AbstractJMSTest
+{
+   protected final boolean useHawtJMS;
+   protected final boolean useSASL;
+
+   protected String address = "exampleQueue";
+   protected MinimalServer server = new MinimalServer();
+
+   public AbstractJMSTest(boolean useHawtJMS, boolean useSASL)
+   {
+      this.useHawtJMS = useHawtJMS;
+      this.useSASL = useSASL;
+   }
+
+   public void tearDown() throws Exception
+   {
+      server.stop();
+      DumbServer.clear();
+   }
+
+   public static void forceGC()
+   {
+      System.out.println("#test forceGC");
+      WeakReference<Object> dumbReference = new WeakReference<Object>(new Object());
+      // A loop that will wait GC, using the minimalserver time as possible
+      while (dumbReference.get() != null)
+      {
+         System.gc();
+         try
+         {
+            Thread.sleep(100);
+         }
+         catch (InterruptedException e)
+         {
+         }
+      }
+      System.out.println("#test forceGC Done");
+   }
+
+
+   protected Connection createConnection() throws JMSException
+   {
+      final ConnectionFactory factory = createConnectionFactory();
+      final Connection connection = factory.createConnection();
+      connection.setExceptionListener(new ExceptionListener()
+      {
+         @Override
+         public void onException(JMSException exception)
+         {
+            exception.printStackTrace();
+         }
+      });
+      connection.start();
+      return connection;
+   }
+
+
+   protected ConnectionFactory createConnectionFactory()
+   {
+      if (useSASL)
+      {
+         if (useHawtJMS)
+         {
+//            return new JmsConnectionFactory("aaaaaaaa", "aaaaaaa", "amqp://localhost:" + Constants.PORT);
+            return null;
+         }
+         else
+         {
+            return new ConnectionFactoryImpl("localhost", Constants.PORT, "aaaaaaaa", "aaaaaaa");
+         }
+      }
+      else
+      {
+         if (useHawtJMS)
+         {
+//            return new JmsConnectionFactory("amqp://localhost:" + Constants.PORT);
+            return null;
+         }
+         else
+         {
+            return new ConnectionFactoryImpl("localhost", Constants.PORT, null, null);
+         }
+
+      }
+   }
+
+   protected Queue createQueue()
+   {
+      if (useHawtJMS)
+      {
+//         return new JmsQueue(address);
+         return null;
+      }
+      else
+      {
+         return new QueueImpl(address);
+      }
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/Constants.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/Constants.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/Constants.java
new file mode 100644
index 0000000..27ffea4
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/Constants.java
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class Constants
+{
+   public static final int PORT = 5672;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java
new file mode 100644
index 0000000..cd2638f
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/ProtonTest.java
@@ -0,0 +1,372 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.proton.plug.test;
+
+import javax.jms.BytesMessage;
+import javax.jms.Connection;
+import javax.jms.DeliveryMode;
+import javax.jms.JMSException;
+import javax.jms.MapMessage;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.qpid.amqp_1_0.jms.impl.QueueImpl;
+import org.apache.qpid.proton.amqp.messaging.AmqpValue;
+import org.apache.qpid.proton.amqp.messaging.Properties;
+import org.apache.qpid.proton.message.Message;
+import org.apache.qpid.proton.message.impl.MessageImpl;
+import org.proton.plug.AMQPClientConnectionContext;
+import org.proton.plug.AMQPClientSenderContext;
+import org.proton.plug.AMQPClientSessionContext;
+import org.proton.plug.sasl.ClientSASLPlain;
+import org.proton.plug.test.minimalclient.SimpleAMQPConnector;
+import org.proton.plug.test.minimalserver.DumbServer;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.proton.plug.util.ByteUtil;
+
+/**
+ * This is simulating a JMS client against a simple server
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ * @author Clebert Suconic
+ */
+@RunWith(Parameterized.class)
+public class ProtonTest extends AbstractJMSTest
+{
+
+   protected Connection connection;
+
+   @Parameterized.Parameters(name = "useHawt={0} sasl={1}")
+   public static Collection<Object[]> data()
+   {
+      List<Object[]> list = Arrays.asList(new Object[][]{
+         {Boolean.FALSE, Boolean.TRUE},
+         {Boolean.FALSE, Boolean.FALSE}});
+
+      System.out.println("Size = " + list.size());
+      return list;
+   }
+
+   public ProtonTest(boolean useHawtJMS, boolean useSASL)
+   {
+      super(useHawtJMS, useSASL);
+   }
+
+
+   @Before
+   public void setUp() throws Exception
+   {
+      DumbServer.clear();
+      AbstractJMSTest.forceGC();
+      server.start("127.0.0.1", Constants.PORT, true);
+      connection = createConnection();
+
+   }
+
+   @After
+   public void tearDown() throws Exception
+   {
+      if (connection != null)
+      {
+         connection.close();
+      }
+
+      super.tearDown();
+   }
+
+   @Test
+   public void testMessagesReceivedInParallel() throws Throwable
+   {
+      final int numMessages = getNumberOfMessages();
+      long time = System.currentTimeMillis();
+      final Queue queue = createQueue();
+
+      final ArrayList<Throwable> exceptions = new ArrayList<>();
+
+      Thread t = new Thread(new Runnable()
+      {
+         @Override
+         public void run()
+         {
+            Connection connectionConsumer = null;
+            try
+            {
+               connectionConsumer = createConnection();
+//               connectionConsumer = connection;
+               connectionConsumer.start();
+               Session sessionConsumer = connectionConsumer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+               final MessageConsumer consumer = sessionConsumer.createConsumer(queue);
+
+               int count = numMessages;
+               while (count > 0)
+               {
+                  try
+                  {
+                     BytesMessage m = (BytesMessage) consumer.receive(1000);
+                     if (count % 1000 == 0)
+                     {
+                        System.out.println("Count = " + count + ", property=" + m.getStringProperty("XX"));
+                     }
+                     Assert.assertNotNull("Could not receive message count=" + count + " on consumer", m);
+                     count--;
+                  }
+                  catch (JMSException e)
+                  {
+                     break;
+                  }
+               }
+            }
+            catch (Throwable e)
+            {
+               exceptions.add(e);
+               e.printStackTrace();
+            }
+            finally
+            {
+               try
+               {
+                  // if the createconnecion wasn't commented out
+                  if (connectionConsumer != connection)
+                  {
+                     connectionConsumer.close();
+                  }
+               }
+               catch (Throwable ignored)
+               {
+                  // NO OP
+               }
+            }
+         }
+      });
+
+      Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
+
+      t.start();
+
+      MessageProducer p = session.createProducer(queue);
+      p.setDeliveryMode(DeliveryMode.PERSISTENT);
+      for (int i = 0; i < numMessages; i++)
+      {
+         BytesMessage message = session.createBytesMessage();
+         // TODO: this will break stuff if I use a large number
+         message.writeBytes(new byte[5]);
+         message.setIntProperty("count", i);
+         message.setStringProperty("XX", "count" + i);
+         p.send(message);
+      }
+
+      long taken = (System.currentTimeMillis() - time);
+      System.out.println("taken on send = " + taken + " usehawt = " + useHawtJMS + " sasl = " + useSASL);
+      t.join();
+
+      for (Throwable e : exceptions)
+      {
+         throw e;
+      }
+      taken = (System.currentTimeMillis() - time);
+      System.out.println("taken = " + taken + " usehawt = " + useHawtJMS + " sasl = " + useSASL);
+
+      connection.close();
+//      assertEquals(0, q.getMessageCount());
+   }
+
+
+   @Test
+   public void testSimpleCreateSessionAndClose() throws Throwable
+   {
+      final QueueImpl queue = new QueueImpl(address);
+
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      Thread.sleep(1000);
+      session.close();
+      connection.close();
+   }
+
+   @Test
+   public void testSimpleBinary() throws Throwable
+   {
+      final int numMessages = 5;
+      long time = System.currentTimeMillis();
+      final QueueImpl queue = new QueueImpl(address);
+
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+      byte[] bytes = new byte[0xf + 1];
+      for (int i = 0; i <= 0xf; i++)
+      {
+         bytes[i] = (byte) i;
+      }
+
+
+      MessageProducer p = session.createProducer(queue);
+      for (int i = 0; i < numMessages; i++)
+      {
+         BytesMessage message = session.createBytesMessage();
+
+         message.writeBytes(bytes);
+         message.setIntProperty("count", i);
+         p.send(message);
+      }
+
+
+      session.close();
+
+
+      Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      final MessageConsumer consumer = sessionConsumer.createConsumer(queue);
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         BytesMessage m = (BytesMessage) consumer.receive(5000);
+
+         System.out.println("length " + m.getBodyLength());
+         Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m);
+
+         m.reset();
+
+         long size = m.getBodyLength();
+         byte[] bytesReceived = new byte[(int) size];
+         m.readBytes(bytesReceived);
+
+
+         System.out.println("Received " + ByteUtil.bytesToHex(bytesReceived, 1));
+
+         Assert.assertArrayEquals(bytes, bytesReceived);
+      }
+
+//      assertEquals(0, q.getMessageCount());
+      long taken = (System.currentTimeMillis() - time) / 1000;
+      System.out.println("taken = " + taken);
+   }
+
+   @Test
+   public void testMapMessage() throws Exception
+   {
+      Queue queue = createQueue();
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      MessageProducer p = session.createProducer(queue);
+      for (int i = 0; i < 10; i++)
+      {
+         MapMessage message = session.createMapMessage();
+         message.setInt("x", i);
+         message.setString("str", "str" + i);
+         p.send(message);
+      }
+      MessageConsumer messageConsumer = session.createConsumer(queue);
+      for (int i = 0; i < 10; i++)
+      {
+         MapMessage m = (MapMessage) messageConsumer.receive(5000);
+         Assert.assertNotNull(m);
+         Assert.assertEquals(i, m.getInt("x"));
+         Assert.assertEquals("str" + i, m.getString("str"));
+      }
+
+      Assert.assertNull(messageConsumer.receiveNoWait());
+   }
+
+   @Test
+   public void testProperties() throws Exception
+   {
+      Queue queue = createQueue();
+      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      MessageProducer p = session.createProducer(queue);
+      TextMessage message = session.createTextMessage();
+      message.setText("msg:0");
+      message.setBooleanProperty("true", true);
+      message.setBooleanProperty("false", false);
+      message.setStringProperty("foo", "bar");
+      message.setDoubleProperty("double", 66.6);
+      message.setFloatProperty("float", 56.789f);
+      message.setIntProperty("int", 8);
+      message.setByteProperty("byte", (byte) 10);
+      p.send(message);
+      p.send(message);
+      connection.start();
+      MessageConsumer messageConsumer = session.createConsumer(queue);
+      TextMessage m = (TextMessage) messageConsumer.receive(5000);
+      Assert.assertNotNull(m);
+      Assert.assertEquals("msg:0", m.getText());
+      Assert.assertEquals(m.getBooleanProperty("true"), true);
+      Assert.assertEquals(m.getBooleanProperty("false"), false);
+      Assert.assertEquals(m.getStringProperty("foo"), "bar");
+      Assert.assertEquals(m.getDoubleProperty("double"), 66.6, 0.0001);
+      Assert.assertEquals(m.getFloatProperty("float"), 56.789f, 0.0001);
+      Assert.assertEquals(m.getIntProperty("int"), 8);
+      Assert.assertEquals(m.getByteProperty("byte"), (byte) 10);
+      m = (TextMessage) messageConsumer.receive(5000);
+      Assert.assertNotNull(m);
+      connection.close();
+   }
+
+   //   @Test
+   public void testSendWithSimpleClient() throws Exception
+   {
+      SimpleAMQPConnector connector = new SimpleAMQPConnector();
+      connector.start();
+      AMQPClientConnectionContext clientConnection = connector.connect("127.0.0.1", Constants.PORT);
+
+      clientConnection.clientOpen(new ClientSASLPlain("aa", "aa"));
+
+      AMQPClientSessionContext session = clientConnection.createClientSession();
+      AMQPClientSenderContext clientSender = session.createSender(address, true);
+
+
+      Properties props = new Properties();
+      for (int i = 0; i < 1; i++)
+      {
+         MessageImpl message = (MessageImpl) Message.Factory.create();
+
+         HashMap map = new HashMap();
+
+         map.put("i", i);
+         AmqpValue value = new AmqpValue(map);
+         message.setBody(value);
+         message.setProperties(props);
+         clientSender.send(message);
+      }
+
+      Session clientSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      connection.start();
+
+      MessageConsumer consumer = clientSession.createConsumer(createQueue());
+      for (int i = 0; i < 1; i++)
+      {
+         MapMessage msg = (MapMessage) consumer.receive(5000);
+         System.out.println("Msg " + msg);
+         Assert.assertNotNull(msg);
+
+         System.out.println("Receive message " + i);
+
+         Assert.assertEquals(0, msg.getInt("i"));
+      }
+   }
+
+
+   protected int getNumberOfMessages()
+   {
+      return 10000;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java
new file mode 100644
index 0000000..90ecee3
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/InVMTestConnector.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.invm;
+
+import org.proton.plug.AMQPClientConnectionContext;
+import org.proton.plug.context.client.ProtonClientConnectionContext;
+import org.proton.plug.test.minimalclient.Connector;
+
+/**
+ * This is used for testing, where we bypass Netty or any networking for test conditions only
+ *
+ * @author Clebert Suconic
+ */
+public class InVMTestConnector implements Connector
+{
+   @Override
+   public void start()
+   {
+
+   }
+
+   @Override
+   public AMQPClientConnectionContext connect(String host, int port) throws Exception
+   {
+      return new ProtonClientConnectionContext(new ProtonINVMSPI());
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java
new file mode 100644
index 0000000..45c0703
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/invm/ProtonINVMSPI.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.invm;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import io.netty.buffer.ByteBuf;
+import org.proton.plug.AMQPConnectionContext;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.ServerSASL;
+import org.proton.plug.context.server.ProtonServerConnectionContext;
+import org.proton.plug.sasl.AnonymousServerSASL;
+import org.proton.plug.sasl.ServerSASLPlain;
+import org.proton.plug.test.minimalserver.MinimalSessionSPI;
+import org.proton.plug.util.ByteUtil;
+import org.proton.plug.util.DebugInfo;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonINVMSPI implements AMQPConnectionCallback
+{
+
+   AMQPConnectionContext returningConnection;
+
+   ProtonServerConnectionContext serverConnection = new ProtonServerConnectionContext(new ReturnSPI());
+
+   final ExecutorService mainExecutor = Executors.newSingleThreadExecutor();
+
+   final ExecutorService returningExecutor = Executors.newSingleThreadExecutor();
+
+   public ProtonINVMSPI()
+   {
+      mainExecutor.execute(new Runnable()
+      {
+         public void run()
+         {
+            Thread.currentThread().setName("MainExecutor-INVM");
+         }
+      });
+      returningExecutor.execute(new Runnable()
+      {
+         public void run()
+         {
+            Thread.currentThread().setName("ReturningExecutor-INVM");
+         }
+      });
+   }
+
+   @Override
+   public void close()
+   {
+      mainExecutor.shutdown();
+   }
+
+   @Override
+   public ServerSASL[] getSASLMechnisms()
+   {
+      return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()};
+   }
+
+
+   @Override
+   public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection)
+   {
+      if (DebugInfo.debug)
+      {
+         ByteUtil.debugFrame("InVM->", bytes);
+      }
+      final int size = bytes.writerIndex();
+
+      bytes.retain();
+      mainExecutor.execute(new Runnable()
+      {
+         public void run()
+         {
+            try
+            {
+               if (DebugInfo.debug)
+               {
+                  ByteUtil.debugFrame("InVMDone->", bytes);
+               }
+               serverConnection.inputBuffer(bytes);
+               try
+               {
+                  connection.outputDone(size);
+               }
+               catch (Exception e)
+               {
+                  e.printStackTrace();
+               }
+            }
+            finally
+            {
+               bytes.release();
+            }
+         }
+      });
+   }
+
+   @Override
+   public void setConnection(AMQPConnectionContext connection)
+   {
+      returningConnection = connection;
+   }
+
+   @Override
+   public AMQPConnectionContext getConnection()
+   {
+      return returningConnection;
+   }
+
+   @Override
+   public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection)
+   {
+      return null;
+   }
+
+   class ReturnSPI implements AMQPConnectionCallback
+   {
+      @Override
+      public void close()
+      {
+
+      }
+
+      @Override
+      public ServerSASL[] getSASLMechnisms()
+      {
+         return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()};
+      }
+
+
+      @Override
+      public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection)
+      {
+
+         final int size = bytes.writerIndex();
+         if (DebugInfo.debug)
+         {
+            ByteUtil.debugFrame("InVM<-", bytes);
+         }
+
+
+         bytes.retain();
+         returningExecutor.execute(new Runnable()
+         {
+            public void run()
+            {
+               try
+               {
+
+                  if (DebugInfo.debug)
+                  {
+                     ByteUtil.debugFrame("InVM done<-", bytes);
+                  }
+
+                  returningConnection.inputBuffer(bytes);
+                  try
+                  {
+                     connection.outputDone(size);
+                  }
+                  catch (Exception e)
+                  {
+                     e.printStackTrace();
+                  }
+
+               }
+               finally
+               {
+                  bytes.release();
+               }
+            }
+         });
+      }
+
+      @Override
+      public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection)
+      {
+         return new MinimalSessionSPI();
+      }
+
+      @Override
+      public void setConnection(AMQPConnectionContext connection)
+      {
+
+      }
+
+      @Override
+      public AMQPConnectionContext getConnection()
+      {
+         return null;
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java
new file mode 100644
index 0000000..c577fb0
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/AMQPClientSPI.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.minimalclient;
+
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import org.proton.plug.AMQPConnectionContext;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.ServerSASL;
+import org.proton.plug.sasl.AnonymousServerSASL;
+import org.proton.plug.sasl.ServerSASLPlain;
+import org.proton.plug.util.ByteUtil;
+import org.proton.plug.util.DebugInfo;
+import org.proton.plug.util.ReusableLatch;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class AMQPClientSPI implements AMQPConnectionCallback
+{
+
+   final Channel channel;
+   protected AMQPConnectionContext connection;
+
+   public AMQPClientSPI(Channel channel)
+   {
+      this.channel = channel;
+   }
+
+   public void setConnection(AMQPConnectionContext connection)
+   {
+      this.connection = connection;
+   }
+
+   public AMQPConnectionContext getConnection()
+   {
+      return connection;
+   }
+
+   @Override
+   public void close()
+   {
+
+   }
+
+   @Override
+   public ServerSASL[] getSASLMechnisms()
+   {
+      return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()};
+   }
+
+
+   final ReusableLatch latch = new ReusableLatch(0);
+
+   @Override
+   public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection)
+   {
+      if (DebugInfo.debug)
+      {
+         ByteUtil.debugFrame("Bytes leaving client", bytes);
+      }
+
+      final int bufferSize = bytes.writerIndex();
+
+
+      latch.countUp();
+
+      channel.writeAndFlush(bytes).addListener(new ChannelFutureListener()
+      {
+         @Override
+         public void operationComplete(ChannelFuture future) throws Exception
+         {
+              //
+//            connection.outputDone(bufferSize);
+            latch.countDown();
+         }
+      });
+
+      if (connection.isSyncOnFlush())
+      {
+         try
+         {
+            if (!latch.await(5, TimeUnit.SECONDS))
+            {
+               // TODO logs
+               System.err.println("Flush took longer than 5 seconds!!!");
+            }
+         }
+         catch (Throwable e)
+         {
+            e.printStackTrace();
+         }
+      }
+
+      connection.outputDone(bufferSize);
+
+   }
+
+   @Override
+   public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection)
+   {
+      return null;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java
new file mode 100644
index 0000000..e653b37
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/Connector.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.minimalclient;
+
+import org.proton.plug.AMQPClientConnectionContext;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface Connector
+{
+   void start();
+
+   AMQPClientConnectionContext connect(String host, int port) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java
new file mode 100644
index 0000000..0d69f3d
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalclient/SimpleAMQPConnector.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.minimalclient;
+
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelDuplexHandler;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.nio.NioSocketChannel;
+import org.proton.plug.AMQPClientConnectionContext;
+import org.proton.plug.context.client.ProtonClientConnectionContextFactory;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class SimpleAMQPConnector implements Connector
+{
+   private Bootstrap bootstrap;
+
+   public void start()
+   {
+
+      bootstrap = new Bootstrap();
+      bootstrap.channel(NioSocketChannel.class);
+      bootstrap.group(new NioEventLoopGroup(10));
+
+      bootstrap.handler(
+         new ChannelInitializer<Channel>()
+         {
+            public void initChannel(Channel channel) throws Exception
+            {
+            }
+         }
+      );
+   }
+
+   public AMQPClientConnectionContext connect(String host, int port) throws Exception
+   {
+      SocketAddress remoteDestination = new InetSocketAddress(host, port);
+
+      ChannelFuture future = bootstrap.connect(remoteDestination);
+
+      future.awaitUninterruptibly();
+
+      AMQPClientSPI clientConnectionSPI = new AMQPClientSPI(future.channel());
+
+      final AMQPClientConnectionContext connection = (AMQPClientConnectionContext) ProtonClientConnectionContextFactory.getFactory().createConnection(clientConnectionSPI);
+
+      future.channel().pipeline().addLast(
+         new ChannelDuplexHandler()
+         {
+
+            @Override
+            public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception
+            {
+               ByteBuf buffer = (ByteBuf) msg;
+               connection.inputBuffer(buffer);
+            }
+         }
+      );
+
+
+      return connection;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java
new file mode 100644
index 0000000..d5c2d4f
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/DumbServer.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.minimalserver;
+
+import java.util.concurrent.BlockingDeque;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.LinkedBlockingDeque;
+
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class DumbServer
+{
+   static ConcurrentHashMap<String, BlockingDeque<Object>> maps = new ConcurrentHashMap<>();
+
+   public static BlockingDeque getQueue(String name)
+   {
+      BlockingDeque q = maps.get(name);
+      if (q == null)
+      {
+         q = new LinkedBlockingDeque();
+         BlockingDeque oldValue = maps.putIfAbsent(name, q);
+         if (oldValue != null)
+         {
+            q = oldValue;
+         }
+      }
+      return q;
+   }
+
+   public static void clear()
+   {
+      for (BlockingDeque<Object> queue : maps.values())
+      {
+         // We clear the queues just in case there is a component holding it
+         queue.clear();
+      }
+      maps.clear();
+   }
+
+   public static void put(String queue, Object message)
+   {
+      getQueue(queue).add(message);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java
new file mode 100644
index 0000000..9a6563d
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/test/java/org/proton/plug/test/minimalserver/MinimalConnectionSPI.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.test.minimalserver;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import org.proton.plug.AMQPConnectionContext;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.ServerSASL;
+import org.proton.plug.sasl.AnonymousServerSASL;
+import org.proton.plug.sasl.ServerSASLPlain;
+import org.proton.plug.util.ByteUtil;
+import org.proton.plug.util.DebugInfo;
+import org.proton.plug.util.ReusableLatch;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class MinimalConnectionSPI implements AMQPConnectionCallback
+{
+   Channel channel;
+
+   private AMQPConnectionContext connection;
+
+   public MinimalConnectionSPI(Channel channel)
+   {
+      this.channel = channel;
+   }
+
+   ExecutorService executorService = Executors.newSingleThreadExecutor();
+
+   @Override
+   public void close()
+   {
+      executorService.shutdown();
+   }
+
+   public void setConnection(AMQPConnectionContext connection)
+   {
+      this.connection = connection;
+   }
+
+   public AMQPConnectionContext getConnection()
+   {
+      return connection;
+   }
+
+   final ReusableLatch latch = new ReusableLatch(0);
+
+   @Override
+   public ServerSASL[] getSASLMechnisms()
+   {
+      return new ServerSASL[]{new AnonymousServerSASL(), new ServerSASLPlain()};
+   }
+
+   @Override
+   public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection)
+   {
+      final int bufferSize = bytes.writerIndex();
+
+      if (DebugInfo.debug)
+      {
+         // some debug
+         byte[] frame = new byte[bytes.writerIndex()];
+         int readerOriginalPos = bytes.readerIndex();
+
+         bytes.getBytes(0, frame);
+
+         try
+         {
+            System.err.println("Buffer Outgoing: " + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 4, 16));
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+         }
+
+         bytes.readerIndex(readerOriginalPos);
+      }
+
+
+      latch.countUp();
+      // ^^ debug
+
+      channel.writeAndFlush(bytes).addListener(new ChannelFutureListener()
+      {
+         @Override
+         public void operationComplete(ChannelFuture future) throws Exception
+         {
+            latch.countDown();
+
+            //   https://issues.apache.org/jira/browse/PROTON-645
+//            connection.outputDone(bufferSize);
+//            if (connection.capacity() > 0)
+//            {
+//               channel.read();
+//            }
+         }
+      });
+
+      channel.flush();
+
+      if (connection.isSyncOnFlush())
+      {
+         try
+         {
+            if (!latch.await(5, TimeUnit.SECONDS))
+            {
+               // TODO logs
+               System.err.println("Flush took longer than 5 seconds!!!");
+            }
+         }
+         catch (Throwable e)
+         {
+            e.printStackTrace();
+         }
+      }
+      connection.outputDone(bufferSize);
+
+
+//      if (connection.capacity() > 0)
+//      {
+//         channel.read();
+//      }
+   }
+
+   @Override
+   public AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection)
+   {
+      return new MinimalSessionSPI();
+   }
+}


[08/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTestBase.java
index 9b9d99d..b73d2e0 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTestBase.java
@@ -32,10 +32,13 @@ import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
 import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.remoting.impl.invm.InVMConnector;
 import org.hornetq.core.remoting.impl.invm.InVMRegistry;
 import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.server.cluster.ha.ReplicatedPolicy;
 import org.hornetq.core.server.impl.HornetQServerImpl;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.tests.integration.cluster.util.SameProcessHornetQServer;
@@ -110,7 +113,8 @@ public abstract class FailoverTestBase extends ServiceTestBase
 
    protected void setBackupIdentity()
    {
-      backupServer.setIdentity(this.getClass().getSimpleName() + "/backupServers");
+      backupServer.setIdentity(this.getClass()
+                                  .getSimpleName() + "/backupServers");
    }
 
    protected void setLiveIdentity()
@@ -120,7 +124,9 @@ public abstract class FailoverTestBase extends ServiceTestBase
 
    protected TestableServer createTestableServer(Configuration config)
    {
-      return new SameProcessHornetQServer(createInVMFailoverServer(true, config, nodeManager, config.getHAPolicy().isBackup() ? 2 : 1));
+      boolean isBackup = config.getHAPolicyConfiguration() instanceof ReplicaPolicyConfiguration ||
+         config.getHAPolicyConfiguration() instanceof SharedStoreSlavePolicyConfiguration;
+      return new SameProcessHornetQServer(createInVMFailoverServer(true, config, nodeManager, isBackup ? 2 : 1));
    }
 
    protected TestableServer createColocatedTestableServer(Configuration config, NodeManager liveNodeManager,NodeManager backupNodeManager, int id)
@@ -166,34 +172,33 @@ public abstract class FailoverTestBase extends ServiceTestBase
    protected void createConfigs() throws Exception
    {
       nodeManager = new InVMNodeManager(false);
-
-      backupConfig = super.createDefaultConfig();
-      backupConfig.getAcceptorConfigurations().clear();
-      backupConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(false));
-      backupConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      backupConfig.getHAPolicy().setFailbackDelay(1000);
-
       TransportConfiguration liveConnector = getConnectorTransportConfiguration(true);
       TransportConfiguration backupConnector = getConnectorTransportConfiguration(false);
-      backupConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      backupConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-      basicClusterConnectionConfig(backupConfig, backupConnector.getName(), liveConnector.getName());
+
+      backupConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(false))
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()
+                                      .setFailbackDelay(1000))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+         .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName()));
+
       backupServer = createTestableServer(backupConfig);
 
-      liveConfig = super.createDefaultConfig();
-      liveConfig.getAcceptorConfigurations().clear();
-      liveConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true));
-      liveConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfig.getHAPolicy().setFailbackDelay(1000);
+      liveConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true))
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()
+                                      .setFailbackDelay(1000))
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName()))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector);
 
-      basicClusterConnectionConfig(liveConfig, liveConnector.getName());
-      liveConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
       liveServer = createTestableServer(liveConfig);
    }
 
    protected void createReplicatedConfigs() throws Exception
    {
-
       final TransportConfiguration liveConnector = getConnectorTransportConfiguration(true);
       final TransportConfiguration backupConnector = getConnectorTransportConfiguration(false);
       final TransportConfiguration backupAcceptor = getAcceptorTransportConfiguration(false);
@@ -201,29 +206,39 @@ public abstract class FailoverTestBase extends ServiceTestBase
       backupConfig = createDefaultConfig();
       liveConfig = createDefaultConfig();
 
-      ReplicatedBackupUtils.configureReplicationPair(backupConfig, backupConnector, backupAcceptor, liveConfig,
-                                                     liveConnector);
+      ReplicatedBackupUtils.configureReplicationPair(backupConfig, backupConnector, backupAcceptor, liveConfig, liveConnector);
 
       final String suffix = "_backup";
-      backupConfig.setBindingsDirectory(backupConfig.getBindingsDirectory() + suffix);
-      backupConfig.setJournalDirectory(backupConfig.getJournalDirectory() + suffix);
-      backupConfig.setPagingDirectory(backupConfig.getPagingDirectory() + suffix);
-      backupConfig.setLargeMessagesDirectory(backupConfig.getLargeMessagesDirectory() + suffix);
-      backupConfig.setSecurityEnabled(false);
-      backupConfig.setMaxSavedReplicatedJournalSize(0);
+      backupConfig.setBindingsDirectory(backupConfig.getBindingsDirectory() + suffix)
+         .setJournalDirectory(backupConfig.getJournalDirectory() + suffix)
+         .setPagingDirectory(backupConfig.getPagingDirectory() + suffix)
+         .setLargeMessagesDirectory(backupConfig.getLargeMessagesDirectory() + suffix)
+         .setSecurityEnabled(false);
+
+      setupHAPolicyConfiguration();
       nodeManager = new InVMNodeManager(true, backupConfig.getJournalDirectory());
 
       backupServer = createTestableServer(backupConfig);
-      liveConfig.getAcceptorConfigurations().clear();
-      liveConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true));
+
+      liveConfig.clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true));
 
       liveServer = createTestableServer(liveConfig);
    }
 
-   protected final void adaptLiveConfigForReplicatedFailBack(Configuration configuration)
+   protected void setupHAPolicyConfiguration()
+   {
+      ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration())
+         .setMaxSavedReplicatedJournalsSize(0)
+         .setAllowFailBack(true)
+         .setFailbackDelay(5000);
+   }
+
+   protected final void adaptLiveConfigForReplicatedFailBack(TestableServer server)
    {
+      Configuration configuration = server.getServer().getConfiguration();
       final TransportConfiguration backupConnector = getConnectorTransportConfiguration(false);
-      if (configuration.getHAPolicy().isSharedStore())
+      if (server.getServer().getHAPolicy().isSharedStore())
       {
          ClusterConnectionConfiguration cc = configuration.getClusterConfigurations().get(0);
          assertNotNull("cluster connection configuration", cc);
@@ -233,7 +248,8 @@ public abstract class FailoverTestBase extends ServiceTestBase
          configuration.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
          return;
       }
-      configuration.setCheckForLiveServer(true);
+      ReplicatedPolicy haPolicy = (ReplicatedPolicy) server.getServer().getHAPolicy();
+      haPolicy.setCheckForLiveServer(true);
    }
 
    @Override
@@ -297,7 +313,7 @@ public abstract class FailoverTestBase extends ServiceTestBase
    protected void waitForBackup(ClientSessionFactoryInternal sessionFactory, int seconds) throws Exception
    {
       final HornetQServerImpl actualServer = (HornetQServerImpl) backupServer.getServer();
-      if (actualServer.getConfiguration().getHAPolicy().isSharedStore())
+      if (actualServer.getHAPolicy().isSharedStore())
       {
          waitForServer(actualServer);
       }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/GroupingFailoverTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/GroupingFailoverTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/GroupingFailoverTestBase.java
index 27352d2..f9f2ed0 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/GroupingFailoverTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/GroupingFailoverTestBase.java
@@ -13,13 +13,17 @@
 package org.hornetq.tests.integration.cluster.failover;
 
 import java.util.Collection;
+import java.util.concurrent.TimeUnit;
 
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.TopologyMemberImpl;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
 import org.hornetq.core.server.group.impl.GroupingHandlerConfiguration;
+import org.hornetq.core.server.impl.SharedNothingBackupActivation;
 import org.hornetq.tests.integration.cluster.distribution.ClusterTestBase;
 import org.hornetq.tests.util.ServiceTestBase;
 import org.junit.Test;
@@ -36,9 +40,9 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase
    {
       setupBackupServer(2, 0, isFileStorage(), isSharedStore(), isNetty());
 
-      setupLiveServer(0, isFileStorage(), isSharedStore(), isNetty());
+      setupLiveServer(0, isFileStorage(), isSharedStore(), isNetty(), false);
 
-      setupLiveServer(1, isFileStorage(), isSharedStore(), isNetty());
+      setupLiveServer(1, isFileStorage(), isSharedStore(), isNetty(), false);
 
       setupClusterConnection("cluster0", "queues", false, 1, isNetty(), 0, 1);
 
@@ -51,10 +55,12 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase
       setUpGroupHandler(GroupingHandlerConfiguration.TYPE.REMOTE, 1);
 
       setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 2);
-
-      servers[0].getConfiguration().getHAPolicy().setBackupGroupName("group1");
-      servers[1].getConfiguration().getHAPolicy().setBackupGroupName("group2");
-      servers[2].getConfiguration().getHAPolicy().setBackupGroupName("group1");
+      if (!isSharedStore())
+      {
+         ((ReplicatedPolicyConfiguration)servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1");
+         ((ReplicatedPolicyConfiguration)servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2");
+         ((ReplicaPolicyConfiguration)servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1");
+      }
 
       startServers(0, 1, 2);
       setupSessionFactory(0, isNetty());
@@ -133,9 +139,9 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase
    {
       setupBackupServer(2, 0, isFileStorage(), isSharedStore(), isNetty());
 
-      setupLiveServer(0, isFileStorage(), isSharedStore(), isNetty());
+      setupLiveServer(0, isFileStorage(), isSharedStore(), isNetty(), false);
 
-      setupLiveServer(1, isFileStorage(), isSharedStore(), isNetty());
+      setupLiveServer(1, isFileStorage(), isSharedStore(), isNetty(), false);
 
       setupClusterConnection("cluster0", "queues", false, 1, isNetty(), 0, 1);
 
@@ -149,9 +155,12 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase
 
       setUpGroupHandler(GroupingHandlerConfiguration.TYPE.LOCAL, 2);
 
-      servers[0].getConfiguration().getHAPolicy().setBackupGroupName("group1");
-      servers[1].getConfiguration().getHAPolicy().setBackupGroupName("group2");
-      servers[2].getConfiguration().getHAPolicy().setBackupGroupName("group1");
+      if (!isSharedStore())
+      {
+         ((ReplicatedPolicyConfiguration)servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1");
+         ((ReplicatedPolicyConfiguration)servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2");
+         ((ReplicaPolicyConfiguration)servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1");
+      }
 
       startServers(0, 1, 2);
 
@@ -189,7 +198,8 @@ public abstract class GroupingFailoverTestBase extends ClusterTestBase
 
       if (!isSharedStore())
       {
-         waitForBackupTopologyAnnouncement(sfs[0]);
+         SharedNothingBackupActivation backupActivation =  (SharedNothingBackupActivation) servers[2].getActivation();
+         assertTrue(backupActivation.waitForBackupSync(10, TimeUnit.SECONDS));
       }
 
       closeSessionFactory(0);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/LiveToLiveFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/LiveToLiveFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/LiveToLiveFailoverTest.java
index 5028901..5d49d45 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/LiveToLiveFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/LiveToLiveFailoverTest.java
@@ -18,9 +18,11 @@ import org.hornetq.api.core.client.ClientProducer;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
-import org.hornetq.core.config.BackupStrategy;
+import org.hornetq.core.config.ScaleDownConfiguration;
+import org.hornetq.core.config.ha.ColocatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.tests.util.TransportConfigurationUtils;
 import org.junit.Assert;
@@ -47,38 +49,39 @@ public class LiveToLiveFailoverTest extends FailoverTest
    {
       nodeManager0 = new InVMNodeManager(false);
       nodeManager1 = new InVMNodeManager(false);
-
-      backupConfig = super.createDefaultConfig(1);
-      backupConfig.getAcceptorConfigurations().clear();
-      backupConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true, 1));
-      backupConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE);
-      backupConfig.getHAPolicy().setFailbackDelay(1000);
-
       TransportConfiguration liveConnector0 = getConnectorTransportConfiguration(true, 0);
       TransportConfiguration liveConnector1 = getConnectorTransportConfiguration(true, 1);
 
-      backupConfig.getConnectorConfigurations().put(liveConnector0.getName(), liveConnector0);
-      backupConfig.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      backupConfig.getHAPolicy().setBackupStrategy(BackupStrategy.SCALE_DOWN);
-      backupConfig.getHAPolicy().getScaleDownConnectors().add(liveConnector1.getName());
-      backupConfig.getHAPolicy().setRequestBackup(true);
-      backupConfig.getHAPolicy().setBackupRequestRetryInterval(1000);
-      basicClusterConnectionConfig(backupConfig, liveConnector1.getName(), liveConnector0.getName());
-      backupServer =  createColocatedTestableServer(backupConfig, nodeManager1, nodeManager0, 1);
-
-      liveConfig = super.createDefaultConfig(0);
-      liveConfig.getAcceptorConfigurations().clear();
-      liveConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true, 0));
-      liveConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE);
-      liveConfig.getHAPolicy().setFailbackDelay(1000);
-
-      basicClusterConnectionConfig(liveConfig, liveConnector0.getName(), liveConnector1.getName());
-      liveConfig.getConnectorConfigurations().put(liveConnector0.getName(), liveConnector0);
-      liveConfig.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfig.getHAPolicy().setBackupStrategy(BackupStrategy.SCALE_DOWN);
-      liveConfig.getHAPolicy().setScaleDownClustername(liveConnector0.getName());
-      liveConfig.getHAPolicy().setRequestBackup(true);
-      liveConfig.getHAPolicy().setBackupRequestRetryInterval(1000);
+      backupConfig = super.createDefaultConfig(1)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true, 1))
+         .setHAPolicyConfiguration(new ColocatedPolicyConfiguration()
+                                      .setRequestBackup(true)
+                                      .setLiveConfig(new SharedStoreMasterPolicyConfiguration())
+                                      .setBackupConfig(new SharedStoreSlavePolicyConfiguration()
+                                                          .setFailbackDelay(1000)
+                                                          .setScaleDownConfiguration(new ScaleDownConfiguration()
+                                                                                        .addConnector(liveConnector1.getName()))))
+         .addConnectorConfiguration(liveConnector0.getName(), liveConnector0)
+         .addConnectorConfiguration(liveConnector1.getName(), liveConnector1)
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector1.getName(), liveConnector0.getName()));
+
+      backupServer = createColocatedTestableServer(backupConfig, nodeManager1, nodeManager0, 1);
+
+      liveConfig = super.createDefaultConfig(0)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true, 0))
+         .setHAPolicyConfiguration(new ColocatedPolicyConfiguration()
+                                      .setRequestBackup(true)
+                                      .setBackupRequestRetryInterval(1000)
+                                      .setLiveConfig(new SharedStoreMasterPolicyConfiguration())
+                                      .setBackupConfig(new SharedStoreSlavePolicyConfiguration()
+                                                          .setFailbackDelay(1000)
+                                                          .setScaleDownConfiguration(new ScaleDownConfiguration())))
+         .addConnectorConfiguration(liveConnector0.getName(), liveConnector0)
+         .addConnectorConfiguration(liveConnector1.getName(), liveConnector1)
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector0.getName(), liveConnector1.getName()));
+
       liveServer = createColocatedTestableServer(liveConfig, nodeManager0, nodeManager1, 0);
    }
 
@@ -334,6 +337,12 @@ public class LiveToLiveFailoverTest extends FailoverTest
    }
 
    @Override
+   public void testFailoverMultipleSessionsWithConsumers() throws Exception
+   {
+      //
+   }
+
+   @Override
    public void testTimeoutOnFailover() throws Exception
    {
    }
@@ -388,6 +397,11 @@ public class LiveToLiveFailoverTest extends FailoverTest
    {
    }
 
+   @Override
+   public void testCommitOccurredUnblockedAndResendNoDuplicates() throws Exception
+   {
+   }
+
    /*@Override
    public void testCommitDidNotOccurUnblockedAndResend() throws Exception
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java
index 614e273..a6da777 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleLivesMultipleBackupsFailoverTest.java
@@ -17,14 +17,18 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
+import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.tests.integration.cluster.util.SameProcessHornetQServer;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
@@ -151,87 +155,62 @@ public class MultipleLivesMultipleBackupsFailoverTest extends MultipleBackupsFai
                                      int[] otherBackupNodes,
                                      int... otherClusterNodes) throws Exception
    {
-      Configuration config1 = super.createDefaultConfig();
-      config1.getAcceptorConfigurations().clear();
-      config1.getAcceptorConfigurations().add(createTransportConfiguration(isNetty(),
-                                                                           true,
-                                                                           generateParams(nodeid, isNetty())));
-      config1.setSecurityEnabled(false);
-
-      if (sharedStore)
-         config1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      else
-         config1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
+      Configuration config1 = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(nodeid, isNetty())))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration())
+         .setBindingsDirectory(HornetQDefaultConfiguration.getDefaultBindingsDirectory() + "_" + liveNode)
+         .setJournalDirectory(HornetQDefaultConfiguration.getDefaultJournalDir() + "_" + liveNode)
+         .setPagingDirectory(HornetQDefaultConfiguration.getDefaultPagingDir() + "_" + liveNode)
+         .setLargeMessagesDirectory(HornetQDefaultConfiguration.getDefaultLargeMessagesDir() + "_" + liveNode);
 
-      List<String> staticConnectors = new ArrayList<String>();
       for (int node : otherBackupNodes)
       {
-         TransportConfiguration liveConnector = createTransportConfiguration(isNetty(),
-                                                                             false,
-                                                                             generateParams(node, isNetty()));
-         config1.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-         staticConnectors.add(liveConnector.getName());
+         TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false, generateParams(node, isNetty()));
+         config1.addConnectorConfiguration(liveConnector.getName(), liveConnector);
       }
-      TransportConfiguration backupConnector = createTransportConfiguration(isNetty(),
-                                                                            false,
-                                                                            generateParams(nodeid, isNetty()));
-      config1.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
+
+      TransportConfiguration backupConnector = createTransportConfiguration(isNetty(), false, generateParams(nodeid, isNetty()));
+      config1.addConnectorConfiguration(backupConnector.getName(), backupConnector);
 
       List<String> clusterNodes = new ArrayList<String>();
       for (int node : otherClusterNodes)
       {
-         TransportConfiguration connector = createTransportConfiguration(isNetty(),
-                                                                         false,
-                                                                         generateParams(node, isNetty()));
-         config1.getConnectorConfigurations().put(connector.getName(), connector);
+         TransportConfiguration connector = createTransportConfiguration(isNetty(), false, generateParams(node, isNetty()));
+         config1.addConnectorConfiguration(connector.getName(), connector);
          clusterNodes.add(connector.getName());
       }
-      basicClusterConnectionConfig(config1, backupConnector.getName(), clusterNodes);
-      config1.setBindingsDirectory(config1.getBindingsDirectory() + "_" + liveNode);
-      config1.setJournalDirectory(config1.getJournalDirectory() + "_" + liveNode);
-      config1.setPagingDirectory(config1.getPagingDirectory() + "_" + liveNode);
-      config1.setLargeMessagesDirectory(config1.getLargeMessagesDirectory() + "_" + liveNode);
+      config1.addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), clusterNodes));
 
       servers.put(nodeid, new SameProcessHornetQServer(createInVMFailoverServer(true, config1, nodeManager, liveNode)));
    }
 
    protected void createLiveConfig(NodeManager nodeManager, int liveNode, int... otherLiveNodes) throws Exception
    {
-      TransportConfiguration liveConnector = createTransportConfiguration(isNetty(),
-                                                                          false,
-                                                                          generateParams(liveNode, isNetty()));
-      Configuration config0 = super.createDefaultConfig();
-      config0.getAcceptorConfigurations().clear();
-      config0.getAcceptorConfigurations().add(createTransportConfiguration(isNetty(),
-                                                                           true,
-                                                                           generateParams(liveNode, isNetty())));
-      config0.setSecurityEnabled(false);
-
-      if (sharedStore)
-         config0.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      else
-         config0.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
+      TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false,generateParams(liveNode, isNetty()));
+
+      Configuration config0 = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(liveNode, isNetty())))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration())
+         .setBindingsDirectory(HornetQDefaultConfiguration.getDefaultBindingsDirectory() + "_" + liveNode)
+         .setJournalDirectory(HornetQDefaultConfiguration.getDefaultJournalDir() + "_" + liveNode)
+         .setPagingDirectory(HornetQDefaultConfiguration.getDefaultPagingDir() + "_" + liveNode)
+         .setLargeMessagesDirectory(HornetQDefaultConfiguration.getDefaultLargeMessagesDir() + "_" + liveNode)
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector);
 
       List<String> pairs = new ArrayList<String>();
       for (int node : otherLiveNodes)
       {
-         TransportConfiguration otherLiveConnector = createTransportConfiguration(isNetty(),
-                                                                                  false,
-                                                                                  generateParams(node, isNetty()));
-         config0.getConnectorConfigurations().put(otherLiveConnector.getName(), otherLiveConnector);
+         TransportConfiguration otherLiveConnector = createTransportConfiguration(isNetty(), false, generateParams(node, isNetty()));
+         config0.addConnectorConfiguration(otherLiveConnector.getName(), otherLiveConnector);
          pairs.add(otherLiveConnector.getName());
-
       }
-      basicClusterConnectionConfig(config0, liveConnector.getName(), pairs);
-      config0.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-
-      config0.setBindingsDirectory(config0.getBindingsDirectory() + "_" + liveNode);
-      config0.setJournalDirectory(config0.getJournalDirectory() + "_" + liveNode);
-      config0.setPagingDirectory(config0.getPagingDirectory() + "_" + liveNode);
-      config0.setLargeMessagesDirectory(config0.getLargeMessagesDirectory() + "_" + liveNode);
+      config0.addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), pairs));
 
-      servers.put(liveNode,
-                  new SameProcessHornetQServer(createInVMFailoverServer(true, config0, nodeManager, liveNode)));
+      servers.put(liveNode, new SameProcessHornetQServer(createInVMFailoverServer(true, config0, nodeManager, liveNode)));
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java
index c538faa..05f593e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/MultipleServerFailoverTestBase.java
@@ -24,11 +24,15 @@ import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.NodeManager;
 import org.hornetq.core.server.Queue;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.tests.integration.cluster.util.SameProcessHornetQServer;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
 import org.hornetq.tests.util.ServiceTestBase;
@@ -66,10 +70,6 @@ public abstract class MultipleServerFailoverTestBase extends ServiceTestBase
 
    public abstract boolean isSharedStore();
 
-   public abstract void createLiveClusterConfiguration(int server, Configuration configuration, int servers);
-
-   public abstract void createBackupClusterConfiguration(int server, Configuration configuration, int servers);
-
    public abstract String getNodeGroupName();
 
    @Override
@@ -81,16 +81,29 @@ public abstract class MultipleServerFailoverTestBase extends ServiceTestBase
       backupServers = new ArrayList<TestableServer>();
       backupConfigs = new ArrayList<Configuration>();
       liveConfigs = new ArrayList<Configuration>();
+
       for (int i = 0; i < getLiveServerCount(); i++)
       {
-         Configuration configuration = createDefaultConfig(useNetty());
-         configuration.getAcceptorConfigurations().clear();
-         configuration.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true, i));
+         HAPolicyConfiguration haPolicyConfiguration = null;
 
          if (isSharedStore())
-            configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
+         {
+            haPolicyConfiguration = new SharedStoreMasterPolicyConfiguration();
+            ((SharedStoreMasterPolicyConfiguration)haPolicyConfiguration).setFailbackDelay(1000);
+         }
          else
-            configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
+         {
+            haPolicyConfiguration = new ReplicatedPolicyConfiguration();
+            if (getNodeGroupName() != null)
+            {
+               ((ReplicatedPolicyConfiguration)haPolicyConfiguration).setGroupName(getNodeGroupName() + "-" + i);
+            }
+         }
+
+         Configuration configuration = createDefaultConfig(useNetty())
+            .clearAcceptorConfigurations()
+            .addAcceptorConfiguration(getAcceptorTransportConfiguration(true, i))
+            .setHAPolicyConfiguration(haPolicyConfiguration);
 
          if (!isSharedStore())
          {
@@ -103,12 +116,21 @@ public abstract class MultipleServerFailoverTestBase extends ServiceTestBase
          {
             //todo
          }
-         configuration.getHAPolicy().setFailbackDelay(1000);
-         if (getNodeGroupName() != null)
+
+         TransportConfiguration livetc = getConnectorTransportConfiguration(true, i);
+         configuration.addConnectorConfiguration(livetc.getName(), livetc);
+         List<String> connectors = new ArrayList<String>();
+         for (int j = 0; j < getLiveServerCount(); j++)
          {
-            configuration.getHAPolicy().setBackupGroupName(getNodeGroupName() + "-" + i);
+            if (j != i)
+            {
+               TransportConfiguration staticTc = getConnectorTransportConfiguration(true, j);
+               configuration.getConnectorConfigurations().put(staticTc.getName(), staticTc);
+               connectors.add(staticTc.getName());
+            }
          }
-         createLiveClusterConfiguration(i, configuration, getLiveServerCount());
+
+         configuration.addClusterConfiguration(basicClusterConnectionConfig(livetc.getName(), connectors));
          liveConfigs.add(configuration);
          HornetQServer server = createServer(true, configuration);
          TestableServer hornetQServer = new SameProcessHornetQServer(server);
@@ -117,14 +139,27 @@ public abstract class MultipleServerFailoverTestBase extends ServiceTestBase
       }
       for (int i = 0; i < getBackupServerCount(); i++)
       {
-         Configuration configuration = createDefaultConfig(useNetty());
-         configuration.getAcceptorConfigurations().clear();
-         configuration.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(false, i));
+         HAPolicyConfiguration haPolicyConfiguration = null;
 
          if (isSharedStore())
-            configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
+         {
+            haPolicyConfiguration = new SharedStoreSlavePolicyConfiguration();
+            ((SharedStoreSlavePolicyConfiguration)haPolicyConfiguration).setFailbackDelay(1000);
+         }
          else
-            configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
+         {
+            haPolicyConfiguration = new ReplicaPolicyConfiguration();
+            ((ReplicaPolicyConfiguration)haPolicyConfiguration).setFailbackDelay(1000);
+            if (getNodeGroupName() != null)
+            {
+               ((ReplicaPolicyConfiguration)haPolicyConfiguration).setGroupName(getNodeGroupName() + "-" + i);
+            }
+         }
+
+         Configuration configuration = createDefaultConfig(useNetty())
+            .clearAcceptorConfigurations()
+            .addAcceptorConfiguration(getAcceptorTransportConfiguration(false, i))
+            .setHAPolicyConfiguration(haPolicyConfiguration);
 
          if (!isSharedStore())
          {
@@ -138,12 +173,25 @@ public abstract class MultipleServerFailoverTestBase extends ServiceTestBase
             //todo
          }
 
-         configuration.getHAPolicy().setFailbackDelay(1000);
-         if (getNodeGroupName() != null)
+         TransportConfiguration backuptc = getConnectorTransportConfiguration(false, i);
+         configuration.addConnectorConfiguration(backuptc.getName(), backuptc);
+         List<String> connectors = new ArrayList<String>();
+         for (int j = 0; j < getBackupServerCount(); j++)
+         {
+            TransportConfiguration staticTc = getConnectorTransportConfiguration(true, j);
+            configuration.addConnectorConfiguration(staticTc.getName(), staticTc);
+            connectors.add(staticTc.getName());
+         }
+         for (int j = 0; j < getBackupServerCount(); j++)
          {
-            configuration.getHAPolicy().setBackupGroupName(getNodeGroupName() + "-" + i);
+            if (j != i)
+            {
+               TransportConfiguration staticTc = getConnectorTransportConfiguration(false, j);
+               configuration.getConnectorConfigurations().put(staticTc.getName(), staticTc);
+               connectors.add(staticTc.getName());
+            }
          }
-         createBackupClusterConfiguration(i, configuration, getBackupServerCount());
+         configuration.addClusterConfiguration(basicClusterConnectionConfig(backuptc.getName(), connectors));
          backupConfigs.add(configuration);
          HornetQServer server = createServer(true, configuration);
          TestableServer testableServer = new SameProcessHornetQServer(server);
@@ -276,7 +324,7 @@ public abstract class MultipleServerFailoverTestBase extends ServiceTestBase
       do
       {
 
-         if (q.getMessageCount() >= messageCount)
+         if (getMessageCount(q) >= messageCount)
          {
             return;
          }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/PagingFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/PagingFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/PagingFailoverTest.java
index 354b9d8..a7d6941 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/PagingFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/PagingFailoverTest.java
@@ -131,7 +131,7 @@ public class PagingFailoverTest extends FailoverTestBase
       if (failBeforeConsume)
       {
          crash(session);
-         waitForBackup(null, 30);
+         waitForBackup(null, 5);
       }
 
       session.close();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumFailOverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumFailOverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumFailOverTest.java
index c8b5a0c..d9c1f6b 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumFailOverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumFailOverTest.java
@@ -20,6 +20,8 @@ import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClusterTopologyListener;
 import org.hornetq.api.core.client.TopologyMember;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
 import org.hornetq.core.protocol.core.impl.PacketImpl;
 import org.hornetq.tests.integration.cluster.util.BackupSyncDelay;
 import org.junit.Test;
@@ -31,12 +33,12 @@ public class QuorumFailOverTest extends StaticClusterWithBackupFailoverTest
    {
       super.setupServers();
       //we need to know who is connected to who
-      servers[0].getConfiguration().getHAPolicy().setBackupGroupName("group0");
-      servers[1].getConfiguration().getHAPolicy().setBackupGroupName("group1");
-      servers[2].getConfiguration().getHAPolicy().setBackupGroupName("group2");
-      servers[3].getConfiguration().getHAPolicy().setBackupGroupName("group0");
-      servers[4].getConfiguration().getHAPolicy().setBackupGroupName("group1");
-      servers[5].getConfiguration().getHAPolicy().setBackupGroupName("group2");
+      ((ReplicatedPolicyConfiguration)servers[0].getConfiguration().getHAPolicyConfiguration()).setGroupName("group0");
+      ((ReplicatedPolicyConfiguration)servers[1].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1");
+      ((ReplicatedPolicyConfiguration)servers[2].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2");
+      ((ReplicaPolicyConfiguration)servers[3].getConfiguration().getHAPolicyConfiguration()).setGroupName("group0");
+      ((ReplicaPolicyConfiguration)servers[4].getConfiguration().getHAPolicyConfiguration()).setGroupName("group1");
+      ((ReplicaPolicyConfiguration)servers[5].getConfiguration().getHAPolicyConfiguration()).setGroupName("group2");
    }
 
    @Test
@@ -75,8 +77,8 @@ public class QuorumFailOverTest extends StaticClusterWithBackupFailoverTest
 
       locators[0].addClusterTopologyListener(liveTopologyListener);
 
-      assertTrue("we assume 3 is a backup", servers[3].getConfiguration().getHAPolicy().isBackup());
-      assertFalse("no shared storage", servers[3].getConfiguration().getHAPolicy().isSharedStore());
+      assertTrue("we assume 3 is a backup", servers[3].getHAPolicy().isBackup());
+      assertFalse("no shared storage", servers[3].getHAPolicy().isSharedStore());
 
       failNode(0);
 
@@ -86,10 +88,10 @@ public class QuorumFailOverTest extends StaticClusterWithBackupFailoverTest
       waitForBindings(3, QUEUES_TESTADDRESS, 1, 1, true);
 
       assertTrue(servers[3].waitForActivation(2, TimeUnit.SECONDS));
-      assertFalse("3 should have failed over ", servers[3].getConfiguration().getHAPolicy().isBackup());
+      assertFalse("3 should have failed over ", servers[3].getHAPolicy().isBackup());
 
       failNode(1);
-      assertFalse("4 should have failed over ", servers[4].getConfiguration().getHAPolicy().isBackup());
+      assertFalse("4 should have failed over ", servers[4].getHAPolicy().isBackup());
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java
index 4255707..f75ce79 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/QuorumVoteServerConnectTest.java
@@ -31,7 +31,7 @@ public class QuorumVoteServerConnectTest extends UnitTestCase
    private final int size;
    private final int trueVotes;
 
-   @Parameterized.Parameters
+   @Parameterized.Parameters(name = "size={0} trueVotes={1}")
    public static Collection primeNumbers()
    {
       return Arrays.asList(new Object[][]

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedDistributionTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedDistributionTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedDistributionTest.java
index 5acae76..f1b394d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedDistributionTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedDistributionTest.java
@@ -190,8 +190,8 @@ public class ReplicatedDistributionTest extends ClusterTestBase
    {
       super.setUp();
 
-      setupLiveServer(1, true, isSharedStore(), true);
-      setupLiveServer(3, true, isSharedStore(), true);
+      setupLiveServer(1, true, isSharedStore(), true, false);
+      setupLiveServer(3, true, isSharedStore(), true, false);
       setupBackupServer(2, 3, true, isSharedStore(), true);
 
       final String address = ReplicatedDistributionTest.ADDRESS.toString();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverTest.java
index d50d3ed..88c087d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverTest.java
@@ -13,11 +13,32 @@
 package org.hornetq.tests.integration.cluster.failover;
 
 import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.server.cluster.ha.ReplicatedPolicy;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
 
 public class ReplicatedFailoverTest extends FailoverTest
 {
+   boolean isReplicatedFailbackTest = false;
+   @Rule
+   public TestRule watcher = new TestWatcher()
+   {
+      @Override
+      protected void starting(Description description)
+      {
+         isReplicatedFailbackTest = description.getMethodName().equals("testReplicatedFailback");
+      }
 
+   };
+
+   protected void beforeWaitForRemoteBackupSynchronization()
+   {
+   }
    @Test
    /*
    * default maxSavedReplicatedJournalsSize is 2, this means the backup will fall back to replicated only twice, after this
@@ -28,8 +49,10 @@ public class ReplicatedFailoverTest extends FailoverTest
    {
       try
       {
-         backupServer.getServer().getConfiguration().getHAPolicy().setFailbackDelay(2000);
-         backupServer.getServer().getConfiguration().setMaxSavedReplicatedJournalSize(2);
+         beforeWaitForRemoteBackupSynchronization();
+
+         waitForRemoteBackupSynchronization(backupServer.getServer());
+
          createSessionFactory();
 
          ClientSession session = createSession(sf, true, true);
@@ -38,7 +61,9 @@ public class ReplicatedFailoverTest extends FailoverTest
 
          crash(session);
 
-         liveServer.getServer().getConfiguration().setCheckForLiveServer(true);
+         ReplicatedPolicy haPolicy = (ReplicatedPolicy) liveServer.getServer().getHAPolicy();
+
+         haPolicy.setCheckForLiveServer(true);
 
          liveServer.start();
 
@@ -80,11 +105,14 @@ public class ReplicatedFailoverTest extends FailoverTest
          assertFalse(backupServer.getServer().isStarted());
 
          //the server wouldnt have reset to backup
-         assertFalse(backupServer.getServer().getConfiguration().getHAPolicy().isBackup());
+         assertFalse(backupServer.getServer().getHAPolicy().isBackup());
       }
       finally
       {
-         sf.close();
+         if (sf != null)
+         {
+            sf.close();
+         }
       }
    }
 
@@ -95,6 +123,24 @@ public class ReplicatedFailoverTest extends FailoverTest
    }
 
    @Override
+   protected void setupHAPolicyConfiguration()
+   {
+      if (isReplicatedFailbackTest)
+      {
+         ((ReplicatedPolicyConfiguration) liveConfig.getHAPolicyConfiguration())
+            .setCheckForLiveServer(true);
+         ((ReplicaPolicyConfiguration) backupConfig.getHAPolicyConfiguration())
+            .setMaxSavedReplicatedJournalsSize(2)
+            .setAllowFailBack(true)
+            .setFailbackDelay(2000);
+      }
+      else
+      {
+         super.setupHAPolicyConfiguration();
+      }
+   }
+
+   @Override
    protected void crash(boolean waitFailure, ClientSession... sessions) throws Exception
    {
       if (sessions.length > 0)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java
index bb7ce39..11a6577 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedFailoverUsingNodeGroupNameTest.java
@@ -12,13 +12,24 @@
  */
 package org.hornetq.tests.integration.cluster.failover;
 
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+
 public class ReplicatedFailoverUsingNodeGroupNameTest extends ReplicatedFailoverTest
 {
    @Override
    protected void createReplicatedConfigs() throws Exception
    {
       super.createReplicatedConfigs();
-      liveConfig.getHAPolicy().setBackupGroupName("liveNodeGroup1");
-      backupConfig.getHAPolicy().setBackupGroupName("liveNodeGroup1");
+      ((ReplicatedPolicyConfiguration)liveConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1");
+      ((ReplicaPolicyConfiguration)backupConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1");
+   }
+
+   @Override
+   protected void setupHAPolicyConfiguration()
+   {
+      super.setupHAPolicyConfiguration();
+      ((ReplicatedPolicyConfiguration)liveConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1");
+      ((ReplicaPolicyConfiguration)backupConfig.getHAPolicyConfiguration()).setGroupName("liveNodeGroup1");
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java
index 711a8aa..edb40e8 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverExtraBackupsTest.java
@@ -22,6 +22,7 @@ import org.hornetq.api.core.client.ClientProducer;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
 import org.junit.Assert;
 import org.junit.Test;
@@ -35,12 +36,13 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated
    @Test
    public void testStartLiveFirst() throws Exception
    {
-      backupServers.get(2).getServer().getConfiguration().getHAPolicy().setBackupGroupName(getNodeGroupName() + "-0");
-      backupServers.get(3).getServer().getConfiguration().getHAPolicy().setBackupGroupName(getNodeGroupName() + "-1");
+      ((ReplicaPolicyConfiguration)backupServers.get(2).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-0");
+      ((ReplicaPolicyConfiguration)backupServers.get(3).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-1");
 
       startServers(liveServers);
       startServers(backupServers);
-      waitForBackups();
+      waitForRemoteBackupSynchronization(backupServers.get(0).getServer());
+      waitForRemoteBackupSynchronization(backupServers.get(1).getServer());
 
       sendCrashReceive();
       waitForTopology(backupServers.get(0).getServer(), liveServers.size(), 2);
@@ -67,8 +69,8 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated
    @Test
    public void testStartBackupFirst() throws Exception
    {
-      backupServers.get(2).getServer().getConfiguration().getHAPolicy().setBackupGroupName(getNodeGroupName() + "-0");
-      backupServers.get(3).getServer().getConfiguration().getHAPolicy().setBackupGroupName(getNodeGroupName() + "-1");
+      ((ReplicaPolicyConfiguration)backupServers.get(2).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-0");
+      ((ReplicaPolicyConfiguration)backupServers.get(3).getServer().getConfiguration().getHAPolicyConfiguration()).setGroupName(getNodeGroupName() + "-1");
 
       startServers(backupServers);
       startServers(liveServers);
@@ -110,7 +112,7 @@ public class ReplicatedMultipleServerFailoverExtraBackupsTest extends Replicated
       List<TestableServer> toCrash = new ArrayList<TestableServer>();
       for (TestableServer backupServer : backupServers)
       {
-         if (!backupServer.getServer().getConfiguration().getHAPolicy().isBackup())
+         if (!backupServer.getServer().getHAPolicy().isBackup())
          {
             toCrash.add(backupServer);
          }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java
index 790880b..dcecced 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedMultipleServerFailoverTest.java
@@ -13,17 +13,12 @@
 
 package org.hornetq.tests.integration.cluster.failover;
 
-import java.util.ArrayList;
-import java.util.List;
-
-import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientConsumer;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientProducer;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
-import org.hornetq.core.config.Configuration;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
 import org.junit.Assert;
 import org.junit.Test;
@@ -185,53 +180,4 @@ public class ReplicatedMultipleServerFailoverTest extends MultipleServerFailover
    {
       return "nodeGroup";
    }
-
-   @Override
-   /*
-   * for this test the 2 live connect to each other
-   * */
-   public void createLiveClusterConfiguration(int server, Configuration configuration, int servers)
-   {
-      TransportConfiguration livetc = getConnectorTransportConfiguration(true, server);
-      configuration.getConnectorConfigurations().put(livetc.getName(), livetc);
-      List<String> connectors = new ArrayList<String>();
-      for (int i = 0; i < servers; i++)
-      {
-         if (i != server)
-         {
-            TransportConfiguration staticTc = getConnectorTransportConfiguration(true, i);
-            configuration.getConnectorConfigurations().put(staticTc.getName(), staticTc);
-            connectors.add(staticTc.getName());
-         }
-      }
-      basicClusterConnectionConfig(configuration, livetc.getName(), connectors);
-
-   }
-
-   @Override
-   /*
-   * for this test the backups will connect to their own live server
-   * */
-   public void createBackupClusterConfiguration(int server, Configuration configuration, int servers)
-   {
-      TransportConfiguration backuptc = getConnectorTransportConfiguration(false, server);
-      configuration.getConnectorConfigurations().put(backuptc.getName(), backuptc);
-      List<String> connectors = new ArrayList<String>();
-      for (int i = 0; i < servers; i++)
-      {
-         TransportConfiguration staticTc = getConnectorTransportConfiguration(true, i);
-         configuration.getConnectorConfigurations().put(staticTc.getName(), staticTc);
-         connectors.add(staticTc.getName());
-      }
-      for (int i = 0; i < servers; i++)
-      {
-         if (i != server)
-         {
-            TransportConfiguration staticTc = getConnectorTransportConfiguration(false, i);
-            configuration.getConnectorConfigurations().put(staticTc.getName(), staticTc);
-            connectors.add(staticTc.getName());
-         }
-      }
-      basicClusterConnectionConfig(configuration, backuptc.getName(), connectors);
-   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java
index 7150f08..2096fb9 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ReplicatedWithDelayFailoverTest.java
@@ -36,6 +36,12 @@ public class ReplicatedWithDelayFailoverTest extends ReplicatedFailoverTest
    }
 
    @Override
+   protected void beforeWaitForRemoteBackupSynchronization()
+   {
+      syncDelay.deliverUpToDateMsg();
+   }
+
+   @Override
    protected void crash(ClientSession... sessions) throws Exception
    {
       syncDelay.deliverUpToDateMsg();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SecurityFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SecurityFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SecurityFailoverTest.java
index 2d45524..b9374f6 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SecurityFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SecurityFailoverTest.java
@@ -18,8 +18,9 @@ import java.util.Set;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.security.Role;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.spi.core.security.HornetQSecurityManager;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
@@ -93,34 +94,32 @@ public class SecurityFailoverTest extends FailoverTest
    protected void createConfigs() throws Exception
    {
       nodeManager = new InVMNodeManager(false);
-
-      backupConfig = super.createDefaultConfig();
-      backupConfig.getAcceptorConfigurations().clear();
-      backupConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(false));
-      backupConfig.setSecurityEnabled(true);
-      backupConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      backupConfig.getHAPolicy().setFailbackDelay(1000);
-
       TransportConfiguration liveConnector = getConnectorTransportConfiguration(true);
       TransportConfiguration backupConnector = getConnectorTransportConfiguration(false);
-      backupConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      backupConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-      basicClusterConnectionConfig(backupConfig, backupConnector.getName(), liveConnector.getName());
-      backupServer = createTestableServer(backupConfig);
 
-      HornetQSecurityManager securityManager = installSecurity(backupServer);
+      backupConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(false))
+         .setSecurityEnabled(true)
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()
+                                      .setFailbackDelay(1000))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+         .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName()));
 
+      backupServer = createTestableServer(backupConfig);
+      HornetQSecurityManager securityManager = installSecurity(backupServer);
       securityManager.setDefaultUser(null);
 
-      liveConfig = super.createDefaultConfig();
-      liveConfig.getAcceptorConfigurations().clear();
-      liveConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true));
-      liveConfig.setSecurityEnabled(true);
-      liveConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      basicClusterConnectionConfig(liveConfig, liveConnector.getName());
-      liveConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      liveServer = createTestableServer(liveConfig);
+      liveConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true))
+         .setSecurityEnabled(true)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration())
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName()))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector);
 
+      liveServer = createTestableServer(liveConfig);
       installSecurity(liveServer);
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java
index d5f5b8a..8bedcca 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/SingleLiveMultipleBackupsFailoverTest.java
@@ -17,14 +17,17 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
+import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorImpl;
 import org.hornetq.core.client.impl.Topology;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.tests.integration.IntegrationTestLogger;
 import org.hornetq.tests.integration.cluster.util.SameProcessHornetQServer;
@@ -127,61 +130,47 @@ public class SingleLiveMultipleBackupsFailoverTest extends MultipleBackupsFailov
 
    protected void createBackupConfig(int liveNode, int nodeid, int... nodes) throws Exception
    {
-      Configuration config1 = super.createDefaultConfig();
-      config1.getAcceptorConfigurations().clear();
-      config1.getAcceptorConfigurations().add(createTransportConfiguration(isNetty(), true,
-                                                                           generateParams(nodeid, isNetty())));
-      config1.setSecurityEnabled(false);
-
-      if (sharedStore)
-         config1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      else
-         config1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
+      TransportConfiguration backupConnector = createTransportConfiguration(isNetty(), false, generateParams(nodeid, isNetty()));
+
+      Configuration config1 = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(nodeid, isNetty())))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(sharedStore ? new SharedStoreSlavePolicyConfiguration() : new ReplicatedPolicyConfiguration())
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+         .setBindingsDirectory(HornetQDefaultConfiguration.getDefaultBindingsDirectory() + "_" + liveNode)
+         .setJournalDirectory(HornetQDefaultConfiguration.getDefaultJournalDir() + "_" + liveNode)
+         .setPagingDirectory(HornetQDefaultConfiguration.getDefaultPagingDir() + "_" + liveNode)
+         .setLargeMessagesDirectory(HornetQDefaultConfiguration.getDefaultLargeMessagesDir() + "_" + liveNode);
 
       List<String> staticConnectors = new ArrayList<String>();
 
       for (int node : nodes)
       {
-         TransportConfiguration liveConnector =
-            createTransportConfiguration(isNetty(), false, generateParams(node, isNetty()));
-         config1.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
+         TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false, generateParams(node, isNetty()));
+         config1.addConnectorConfiguration(liveConnector.getName(), liveConnector);
          staticConnectors.add(liveConnector.getName());
       }
-      TransportConfiguration backupConnector =
-         createTransportConfiguration(isNetty(), false, generateParams(nodeid, isNetty()));
-      basicClusterConnectionConfig(config1, backupConnector.getName(), staticConnectors);
-      config1.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-
-      config1.setBindingsDirectory(config1.getBindingsDirectory() + "_" + liveNode);
-      config1.setJournalDirectory(config1.getJournalDirectory() + "_" + liveNode);
-      config1.setPagingDirectory(config1.getPagingDirectory() + "_" + liveNode);
-      config1.setLargeMessagesDirectory(config1.getLargeMessagesDirectory() + "_" + liveNode);
+      config1.addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), staticConnectors));
 
       servers.put(nodeid, new SameProcessHornetQServer(createInVMFailoverServer(true, config1, nodeManager, nodeid)));
    }
 
    protected void createLiveConfig(int liveNode) throws Exception
    {
-      TransportConfiguration liveConnector =
-         createTransportConfiguration(isNetty(), false, generateParams(liveNode, isNetty()));
-      Configuration config0 = super.createDefaultConfig();
-      config0.getAcceptorConfigurations().clear();
-      config0.getAcceptorConfigurations().add(createTransportConfiguration(isNetty(), true,
-                                                                           generateParams(liveNode, isNetty())));
-      config0.setSecurityEnabled(false);
-
-      if (sharedStore)
-         config0.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      else
-         config0.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-
-      basicClusterConnectionConfig(config0, liveConnector.getName());
-      config0.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-
-      config0.setBindingsDirectory(config0.getBindingsDirectory() + "_" + liveNode);
-      config0.setJournalDirectory(config0.getJournalDirectory() + "_" + liveNode);
-      config0.setPagingDirectory(config0.getPagingDirectory() + "_" + liveNode);
-      config0.setLargeMessagesDirectory(config0.getLargeMessagesDirectory() + "_" + liveNode);
+      TransportConfiguration liveConnector = createTransportConfiguration(isNetty(), false, generateParams(liveNode, isNetty()));
+
+      Configuration config0 = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(createTransportConfiguration(isNetty(), true, generateParams(liveNode, isNetty())))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(sharedStore ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration())
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName()))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .setBindingsDirectory(HornetQDefaultConfiguration.getDefaultBindingsDirectory() + "_" + liveNode)
+         .setJournalDirectory(HornetQDefaultConfiguration.getDefaultJournalDir() + "_" + liveNode)
+         .setPagingDirectory(HornetQDefaultConfiguration.getDefaultPagingDir() + "_" + liveNode)
+         .setLargeMessagesDirectory(HornetQDefaultConfiguration.getDefaultLargeMessagesDir() + "_" + liveNode);
 
       servers.put(liveNode, new SameProcessHornetQServer(createInVMFailoverServer(true, config0, nodeManager, liveNode)));
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java
index 6e3f7f2..3b9a0b4 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/StaticClusterWithBackupFailoverTest.java
@@ -86,8 +86,8 @@ public class StaticClusterWithBackupFailoverTest extends ClusterWithBackupFailov
       setupBackupServer(5, 2, isFileStorage(), isSharedStorage(), isNetty());
 
       // The lives
-      setupLiveServer(0, isFileStorage(), isSharedStorage(), isNetty());
-      setupLiveServer(1, isFileStorage(), isSharedStorage(), isNetty());
-      setupLiveServer(2, isFileStorage(), isSharedStorage(), isNetty());
+      setupLiveServer(0, isFileStorage(), isSharedStorage(), isNetty(), false);
+      setupLiveServer(1, isFileStorage(), isSharedStorage(), isNetty(), false);
+      setupLiveServer(2, isFileStorage(), isSharedStorage(), isNetty(), false);
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java
index 4d582d8..bb805a8 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ha/HAAutomaticBackupSharedStore.java
@@ -12,8 +12,11 @@
  */
 package org.hornetq.tests.integration.cluster.ha;
 
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ha.ColocatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.cluster.ha.HAPolicyTemplate;
 import org.hornetq.tests.integration.cluster.distribution.ClusterTestBase;
 import org.junit.Before;
 import org.junit.Test;
@@ -53,16 +56,22 @@ public class HAAutomaticBackupSharedStore extends ClusterTestBase
    protected void setupServers() throws Exception
    {
       // The lives
-      setupLiveServer(0, isFileStorage(), true, isNetty());
-      setupLiveServer(1, isFileStorage(), true, isNetty());
-      setupLiveServer(2, isFileStorage(), true, isNetty());
+      setupLiveServer(0, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(1, isFileStorage(), true, isNetty(), false);
+      setupLiveServer(2, isFileStorage(), true, isNetty(), false);
 
    }
 
    private void setUpHAPolicy(int node)
    {
       HornetQServer server = getServer(node);
-      server.getConfiguration().setHAPolicy(HAPolicyTemplate.COLOCATED_SHARED_STORE.getHaPolicy());
+      ColocatedPolicyConfiguration haPolicyConfiguration = new ColocatedPolicyConfiguration();
+      HAPolicyConfiguration liveConfiguration = new SharedStoreMasterPolicyConfiguration();
+      haPolicyConfiguration.setLiveConfig(liveConfiguration);
+
+      HAPolicyConfiguration backupConfiguration = new SharedStoreSlavePolicyConfiguration();
+      haPolicyConfiguration.setBackupConfig(backupConfiguration);
+      server.getConfiguration().setHAPolicyConfiguration(haPolicyConfiguration);
    }
 
    public boolean isNetty()

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java
index dc372f8..de7006f 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/MultiThreadRandomReattachTest.java
@@ -29,9 +29,9 @@ public class MultiThreadRandomReattachTest extends MultiThreadRandomReattachTest
    @Override
    protected void start() throws Exception
    {
-      Configuration liveConf = createDefaultConfig();
-      liveConf.setSecurityEnabled(false);
-      liveConf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration liveConf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       liveServer = createServer(false, liveConf);
       liveServer.start();
       waitForServer(liveServer);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java
index e3df2de..c83743f 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/NettyMultiThreadRandomReattachTest.java
@@ -30,11 +30,11 @@ public class NettyMultiThreadRandomReattachTest extends MultiThreadRandomReattac
    @Override
    protected void start() throws Exception
    {
-      Configuration liveConf = createDefaultConfig();
-      liveConf.setJMXManagementEnabled(false);
-      liveConf.setSecurityEnabled(false);
-      liveConf.getAcceptorConfigurations().clear();
-      liveConf.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
+      Configuration liveConf = createDefaultConfig()
+         .setJMXManagementEnabled(false)
+         .setSecurityEnabled(false)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
       liveServer = createServer(false, liveConf);
       liveServer.start();
       waitForServer(liveServer);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/RandomReattachTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/RandomReattachTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/RandomReattachTest.java
index 743c3d4..099b04c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/RandomReattachTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/reattach/RandomReattachTest.java
@@ -1495,10 +1495,9 @@ public class RandomReattachTest extends UnitTestCase
 
    private void start() throws Exception
    {
-      Configuration liveConf = createDefaultConfig();
-      liveConf.setSecurityEnabled(false);
-      liveConf.getAcceptorConfigurations()
-         .add(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
+      Configuration liveConf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration("org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory"));
       liveService = HornetQServers.newHornetQServer(liveConf, false);
       liveService.start();
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java
index 8b03c25..36dd7d6 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/HAClientTopologyWithDiscoveryTest.java
@@ -60,9 +60,10 @@ public class HAClientTopologyWithDiscoveryTest extends TopologyClusterTestBase
    @Override
    protected ServerLocator createHAServerLocator()
    {
-      ServerLocator locator = HornetQClient.createServerLocatorWithHA(
-                  new DiscoveryGroupConfiguration(HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT,
-                  new UDPBroadcastGroupConfiguration(groupAddress, groupPort, null, -1)));
+      ServerLocator locator = HornetQClient.createServerLocatorWithHA(new DiscoveryGroupConfiguration()
+         .setBroadcastEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(groupAddress)
+            .setGroupPort(groupPort)));
       locator.setBlockOnNonDurableSend(true);
       locator.setBlockOnDurableSend(true);
       addServerLocator(locator);


[34/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireConnection.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireConnection.java
new file mode 100644
index 0000000..78aae2f
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireConnection.java
@@ -0,0 +1,1765 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import javax.jms.JMSSecurityException;
+import javax.jms.ResourceAllocationException;
+
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ActiveMQMessage;
+import org.apache.activemq.command.BrokerInfo;
+import org.apache.activemq.command.Command;
+import org.apache.activemq.command.ConnectionControl;
+import org.apache.activemq.command.ConnectionError;
+import org.apache.activemq.command.ConnectionId;
+import org.apache.activemq.command.ConnectionInfo;
+import org.apache.activemq.command.ConsumerControl;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.ConsumerInfo;
+import org.apache.activemq.command.ControlCommand;
+import org.apache.activemq.command.DataArrayResponse;
+import org.apache.activemq.command.DestinationInfo;
+import org.apache.activemq.command.ExceptionResponse;
+import org.apache.activemq.command.FlushCommand;
+import org.apache.activemq.command.KeepAliveInfo;
+import org.apache.activemq.command.Message;
+import org.apache.activemq.command.MessageAck;
+import org.apache.activemq.command.MessageDispatch;
+import org.apache.activemq.command.MessageDispatchNotification;
+import org.apache.activemq.command.MessagePull;
+import org.apache.activemq.command.ProducerAck;
+import org.apache.activemq.command.ProducerId;
+import org.apache.activemq.command.ProducerInfo;
+import org.apache.activemq.command.RemoveInfo;
+import org.apache.activemq.command.RemoveSubscriptionInfo;
+import org.apache.activemq.command.Response;
+import org.apache.activemq.command.SessionId;
+import org.apache.activemq.command.SessionInfo;
+import org.apache.activemq.command.ShutdownInfo;
+import org.apache.activemq.command.TransactionId;
+import org.apache.activemq.command.TransactionInfo;
+import org.apache.activemq.command.WireFormatInfo;
+import org.apache.activemq.openwire.OpenWireFormat;
+import org.apache.activemq.state.CommandVisitor;
+import org.apache.activemq.state.ConnectionState;
+import org.apache.activemq.state.ConsumerState;
+import org.apache.activemq.state.ProducerState;
+import org.apache.activemq.state.SessionState;
+import org.apache.activemq.thread.TaskRunner;
+import org.apache.activemq.thread.TaskRunnerFactory;
+import org.apache.activemq.transport.TransmitCallback;
+import org.apache.activemq.util.ByteSequence;
+import org.apache.activemq.wireformat.WireFormat;
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.HornetQBuffers;
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.HornetQSecurityException;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.protocol.openwire.amq.AMQBrokerStoppedException;
+import org.hornetq.core.protocol.openwire.amq.AMQConnectionContext;
+import org.hornetq.core.protocol.openwire.amq.AMQConsumerBrokerExchange;
+import org.hornetq.core.protocol.openwire.amq.AMQMapTransportConnectionStateRegister;
+import org.hornetq.core.protocol.openwire.amq.AMQMessageAuthorizationPolicy;
+import org.hornetq.core.protocol.openwire.amq.AMQProducerBrokerExchange;
+import org.hornetq.core.protocol.openwire.amq.AMQSession;
+import org.hornetq.core.protocol.openwire.amq.AMQSingleTransportConnectionStateRegister;
+import org.hornetq.core.protocol.openwire.amq.AMQTransaction;
+import org.hornetq.core.protocol.openwire.amq.AMQTransportConnectionState;
+import org.hornetq.core.protocol.openwire.amq.AMQTransportConnectionStateRegister;
+import org.hornetq.core.remoting.CloseListener;
+import org.hornetq.core.remoting.FailureListener;
+import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.spi.core.remoting.Acceptor;
+import org.hornetq.spi.core.remoting.Connection;
+import org.hornetq.utils.ConcurrentHashSet;
+
+/**
+ * Represents an activemq connection.
+ * @author howard
+ *
+ */
+public class OpenWireConnection implements RemotingConnection, CommandVisitor
+{
+   private final OpenWireProtocolManager protocolManager;
+
+   private final Connection transportConnection;
+
+   private final AMQConnectorImpl acceptorUsed;
+
+   private final long creationTime;
+
+   private final List<FailureListener> failureListeners = new CopyOnWriteArrayList<FailureListener>();
+
+   private final List<CloseListener> closeListeners = new CopyOnWriteArrayList<CloseListener>();
+
+   private boolean destroyed = false;
+
+   private final Object sendLock = new Object();
+
+   private boolean dataReceived;
+
+   private OpenWireFormat wireFormat;
+
+   private AMQTransportConnectionStateRegister connectionStateRegister = new AMQSingleTransportConnectionStateRegister();
+
+   private boolean faultTolerantConnection;
+
+   private AMQConnectionContext context;
+
+   private AMQMessageAuthorizationPolicy messageAuthorizationPolicy;
+
+   private boolean networkConnection;
+
+   private boolean manageable;
+
+   private boolean pendingStop;
+
+   private Throwable stopError = null;
+
+   // should come from hornetq server
+   private final TaskRunnerFactory stopTaskRunnerFactory = null;
+
+   private boolean starting;
+
+   private final AtomicBoolean stopping = new AtomicBoolean(false);
+
+   private final ReentrantReadWriteLock serviceLock = new ReentrantReadWriteLock();
+
+   private final CountDownLatch stopped = new CountDownLatch(1);
+
+   protected TaskRunner taskRunner;
+
+   private boolean active;
+
+   protected final List<Command> dispatchQueue = new LinkedList<Command>();
+
+   private boolean markedCandidate;
+
+   private boolean blockedCandidate;
+
+   private long timeStamp;
+
+   private boolean inServiceException;
+
+   private final AtomicBoolean asyncException = new AtomicBoolean(false);
+
+   private final Map<ConsumerId, AMQConsumerBrokerExchange> consumerExchanges = new HashMap<ConsumerId, AMQConsumerBrokerExchange>();
+   private final Map<ProducerId, AMQProducerBrokerExchange> producerExchanges = new HashMap<ProducerId, AMQProducerBrokerExchange>();
+
+   private AMQTransportConnectionState state;
+
+   private final Set<String> tempQueues = new ConcurrentHashSet<String>();
+
+   protected final Map<ConnectionId, ConnectionState> brokerConnectionStates;
+
+   private DataInputWrapper dataInput = new DataInputWrapper();
+
+   private Map<TransactionId, TransactionInfo> txMap = new ConcurrentHashMap<TransactionId, TransactionInfo>();
+
+   private volatile AMQSession advisorySession;
+
+   public OpenWireConnection(Acceptor acceptorUsed, Connection connection,
+         OpenWireProtocolManager openWireProtocolManager, OpenWireFormat wf)
+   {
+      this.protocolManager = openWireProtocolManager;
+      this.transportConnection = connection;
+      this.acceptorUsed = new AMQConnectorImpl(acceptorUsed);
+      this.wireFormat = wf;
+      brokerConnectionStates = protocolManager.getConnectionStates();
+      this.creationTime = System.currentTimeMillis();
+   }
+
+   @Override
+   public void bufferReceived(Object connectionID, HornetQBuffer buffer)
+   {
+      try
+      {
+         dataInput.receiveData(buffer);
+      }
+      catch (Throwable t)
+      {
+         HornetQServerLogger.LOGGER.error("decoding error", t);
+         return;
+      }
+
+      // this.setDataReceived();
+      while (dataInput.readable())
+      {
+         try
+         {
+            Object object = null;
+            try
+            {
+               object = wireFormat.unmarshal(dataInput);
+               dataInput.mark();
+            }
+            catch (NotEnoughBytesException e)
+            {
+               //meaning the dataInput hasn't enough bytes for a command.
+               //in that case we just return and waiting for the next
+               //call of bufferReceived()
+               return;
+            }
+
+            Command command = (Command) object;
+            boolean responseRequired = command.isResponseRequired();
+            int commandId = command.getCommandId();
+            // the connection handles pings, negotiations directly.
+            // and delegate all other commands to manager.
+            if (command.getClass() == KeepAliveInfo.class)
+            {
+               KeepAliveInfo info = (KeepAliveInfo) command;
+               if (info.isResponseRequired())
+               {
+                  info.setResponseRequired(false);
+                  protocolManager.sendReply(this, info);
+               }
+            }
+            else if (command.getClass() == WireFormatInfo.class)
+            {
+               // amq here starts a read/write monitor thread (detect ttl?)
+               negotiate((WireFormatInfo) command);
+            }
+            else if (command.getClass() == ConnectionInfo.class
+                  || command.getClass() == ConsumerInfo.class
+                  || command.getClass() == RemoveInfo.class
+                  || command.getClass() == SessionInfo.class
+                  || command.getClass() == ProducerInfo.class
+                  || ActiveMQMessage.class.isAssignableFrom(command.getClass())
+                  || command.getClass() == MessageAck.class
+                  || command.getClass() == TransactionInfo.class
+                  || command.getClass() == DestinationInfo.class
+                  || command.getClass() == ShutdownInfo.class)
+            {
+               Response response = null;
+
+               if (pendingStop)
+               {
+                  response = new ExceptionResponse(this.stopError);
+               }
+               else
+               {
+                  response = ((Command) command).visit(this);
+
+                  if (response instanceof ExceptionResponse)
+                  {
+                     if (!responseRequired)
+                     {
+                        Throwable cause = ((ExceptionResponse)response).getException();
+                        serviceException(cause);
+                        response = null;
+                     }
+                  }
+               }
+
+               if (responseRequired)
+               {
+                  if (response == null)
+                  {
+                     response = new Response();
+                  }
+               }
+
+               // The context may have been flagged so that the response is not
+               // sent.
+               if (context != null)
+               {
+                  if (context.isDontSendReponse())
+                  {
+                     context.setDontSendReponse(false);
+                     response = null;
+                  }
+                  context = null;
+               }
+
+               if (response != null && !protocolManager.isStopping())
+               {
+                  response.setCorrelationId(commandId);
+                  dispatchSync(response);
+               }
+
+            }
+            else
+            {
+               // note!!! wait for negotiation (e.g. use a countdown latch)
+               // before handling any other commands
+               this.protocolManager.handleCommand(this, command);
+            }
+         }
+         catch (IOException e)
+         {
+            HornetQServerLogger.LOGGER.error("error decoding", e);
+         }
+         catch (Throwable t)
+         {
+            HornetQServerLogger.LOGGER.error("error decoding", t);
+         }
+      }
+   }
+
+   private void negotiate(WireFormatInfo command) throws IOException
+   {
+      this.wireFormat.renegotiateWireFormat(command);
+   }
+
+   @Override
+   public Object getID()
+   {
+      return transportConnection.getID();
+   }
+
+   @Override
+   public long getCreationTime()
+   {
+      return creationTime;
+   }
+
+   @Override
+   public String getRemoteAddress()
+   {
+      return transportConnection.getRemoteAddress();
+   }
+
+   @Override
+   public void addFailureListener(FailureListener listener)
+   {
+      if (listener == null)
+      {
+         throw new IllegalStateException("FailureListener cannot be null");
+      }
+
+      failureListeners.add(listener);
+   }
+
+   @Override
+   public boolean removeFailureListener(FailureListener listener)
+   {
+      if (listener == null)
+      {
+         throw new IllegalStateException("FailureListener cannot be null");
+      }
+
+      return failureListeners.remove(listener);
+   }
+
+   @Override
+   public void addCloseListener(CloseListener listener)
+   {
+      if (listener == null)
+      {
+         throw new IllegalStateException("CloseListener cannot be null");
+      }
+
+      closeListeners.add(listener);
+   }
+
+   @Override
+   public boolean removeCloseListener(CloseListener listener)
+   {
+      if (listener == null)
+      {
+         throw new IllegalStateException("CloseListener cannot be null");
+      }
+
+      return closeListeners.remove(listener);
+   }
+
+   @Override
+   public List<CloseListener> removeCloseListeners()
+   {
+      List<CloseListener> ret = new ArrayList<CloseListener>(closeListeners);
+
+      closeListeners.clear();
+
+      return ret;
+   }
+
+   @Override
+   public void setCloseListeners(List<CloseListener> listeners)
+   {
+      closeListeners.clear();
+
+      closeListeners.addAll(listeners);
+   }
+
+   @Override
+   public List<FailureListener> getFailureListeners()
+   {
+      // we do not return the listeners otherwise the remoting service
+      // would NOT destroy the connection.
+      return Collections.emptyList();
+   }
+
+   @Override
+   public List<FailureListener> removeFailureListeners()
+   {
+      List<FailureListener> ret = new ArrayList<FailureListener>(
+            failureListeners);
+
+      failureListeners.clear();
+
+      return ret;
+   }
+
+   @Override
+   public void setFailureListeners(List<FailureListener> listeners)
+   {
+      failureListeners.clear();
+
+      failureListeners.addAll(listeners);
+   }
+
+   @Override
+   public HornetQBuffer createBuffer(int size)
+   {
+      return HornetQBuffers.dynamicBuffer(size);
+   }
+
+   @Override
+   public void fail(HornetQException me)
+   {
+      HornetQServerLogger.LOGGER.connectionFailureDetected(me.getMessage(),
+            me.getType());
+      // Then call the listeners
+      callFailureListeners(me);
+
+      callClosingListeners();
+
+      destroyed = true;
+
+      transportConnection.close();
+   }
+
+   @Override
+   public void destroy()
+   {
+      destroyed = true;
+
+      transportConnection.close();
+
+      try
+      {
+         deleteTempQueues();
+      }
+      catch (Exception e)
+      {
+         //log warning
+      }
+
+      synchronized (sendLock)
+      {
+         callClosingListeners();
+      }
+   }
+
+   private void deleteTempQueues() throws Exception
+   {
+      Iterator<String> queueNames = tempQueues.iterator();
+      while (queueNames.hasNext())
+      {
+         String q = queueNames.next();
+         protocolManager.deleteQueue(q);
+      }
+   }
+
+   @Override
+   public Connection getTransportConnection()
+   {
+      return this.transportConnection;
+   }
+
+   @Override
+   public boolean isClient()
+   {
+      return false;
+   }
+
+   @Override
+   public boolean isDestroyed()
+   {
+      return destroyed;
+   }
+
+   @Override
+   public void disconnect(boolean criticalError)
+   {
+      fail(null);
+   }
+
+   @Override
+   public boolean checkDataReceived()
+   {
+      boolean res = dataReceived;
+
+      dataReceived = false;
+
+      return res;
+   }
+
+   @Override
+   public void flush()
+   {
+   }
+
+   private void callFailureListeners(final HornetQException me)
+   {
+      final List<FailureListener> listenersClone = new ArrayList<FailureListener>(
+            failureListeners);
+
+      for (final FailureListener listener : listenersClone)
+      {
+         try
+         {
+            listener.connectionFailed(me, false);
+         }
+         catch (final Throwable t)
+         {
+            // Failure of one listener to execute shouldn't prevent others
+            // from
+            // executing
+            HornetQServerLogger.LOGGER.errorCallingFailureListener(t);
+         }
+      }
+   }
+
+   private void callClosingListeners()
+   {
+      final List<CloseListener> listenersClone = new ArrayList<CloseListener>(
+            closeListeners);
+
+      for (final CloseListener listener : listenersClone)
+      {
+         try
+         {
+            listener.connectionClosed();
+         }
+         catch (final Throwable t)
+         {
+            // Failure of one listener to execute shouldn't prevent others
+            // from
+            // executing
+            HornetQServerLogger.LOGGER.errorCallingFailureListener(t);
+         }
+      }
+   }
+
+   // throw a WireFormatInfo to the peer
+   public void init()
+   {
+      WireFormatInfo info = wireFormat.getPreferedWireFormatInfo();
+      protocolManager.send(this, info);
+   }
+
+   public ConnectionState getState()
+   {
+      return state;
+   }
+
+   public void physicalSend(Command command) throws IOException
+   {
+      try
+      {
+         ByteSequence bytes = wireFormat.marshal(command);
+         HornetQBuffer buffer = OpenWireUtil.toHornetQBuffer(bytes);
+         synchronized (sendLock)
+         {
+            getTransportConnection().write(buffer, false, false);
+         }
+      }
+      catch (IOException e)
+      {
+         throw e;
+      }
+      catch (Throwable t)
+      {
+         HornetQServerLogger.LOGGER.error("error sending", t);
+      }
+
+   }
+
+   @Override
+   public Response processAddConnection(ConnectionInfo info) throws Exception
+   {
+      WireFormatInfo wireFormatInfo = wireFormat.getPreferedWireFormatInfo();
+      // Older clients should have been defaulting this field to true.. but
+      // they were not.
+      if (wireFormatInfo != null && wireFormatInfo.getVersion() <= 2)
+      {
+         info.setClientMaster(true);
+      }
+
+      // Make sure 2 concurrent connections by the same ID only generate 1
+      // TransportConnectionState object.
+      synchronized (brokerConnectionStates)
+      {
+         state = (AMQTransportConnectionState) brokerConnectionStates.get(info
+               .getConnectionId());
+         if (state == null)
+         {
+            state = new AMQTransportConnectionState(info, this);
+            brokerConnectionStates.put(info.getConnectionId(), state);
+         }
+         state.incrementReference();
+      }
+      // If there are 2 concurrent connections for the same connection id,
+      // then last one in wins, we need to sync here
+      // to figure out the winner.
+      synchronized (state.getConnectionMutex())
+      {
+         if (state.getConnection() != this)
+         {
+            state.getConnection().disconnect(true);
+            state.setConnection(this);
+            state.reset(info);
+         }
+      }
+
+      registerConnectionState(info.getConnectionId(), state);
+
+      this.faultTolerantConnection = info.isFaultTolerant();
+      // Setup the context.
+      String clientId = info.getClientId();
+      context = new AMQConnectionContext();
+      context.setBroker(protocolManager);
+      context.setClientId(clientId);
+      context.setClientMaster(info.isClientMaster());
+      context.setConnection(this);
+      context.setConnectionId(info.getConnectionId());
+      // for now we pass the manager as the connector and see what happens
+      // it should be related to hornetq's Acceptor
+      context.setConnector(this.acceptorUsed);
+      context.setMessageAuthorizationPolicy(getMessageAuthorizationPolicy());
+      context.setNetworkConnection(networkConnection);
+      context.setFaultTolerant(faultTolerantConnection);
+      context
+            .setTransactions(new ConcurrentHashMap<TransactionId, AMQTransaction>());
+      context.setUserName(info.getUserName());
+      context.setWireFormatInfo(wireFormatInfo);
+      context.setReconnect(info.isFailoverReconnect());
+      this.manageable = info.isManageable();
+      context.setConnectionState(state);
+      state.setContext(context);
+      state.setConnection(this);
+      if (info.getClientIp() == null)
+      {
+         info.setClientIp(getRemoteAddress());
+      }
+
+      try
+      {
+         protocolManager.addConnection(context, info);
+      }
+      catch (Exception e)
+      {
+         synchronized (brokerConnectionStates)
+         {
+            brokerConnectionStates.remove(info.getConnectionId());
+         }
+         unregisterConnectionState(info.getConnectionId());
+
+         if (e instanceof SecurityException)
+         {
+            // close this down - in case the peer of this transport doesn't play
+            // nice
+            delayedStop(2000,
+                  "Failed with SecurityException: " + e.getLocalizedMessage(),
+                  e);
+         }
+         Response resp = new ExceptionResponse(e);
+         return resp;
+      }
+      if (info.isManageable())
+      {
+         // send ConnectionCommand
+         ConnectionControl command = this.acceptorUsed.getConnectionControl();
+         command.setFaultTolerant(protocolManager
+               .isFaultTolerantConfiguration());
+         if (info.isFailoverReconnect())
+         {
+            command.setRebalanceConnection(false);
+         }
+         dispatchAsync(command);
+      }
+      return null;
+   }
+
+   public void dispatchAsync(Command message)
+   {
+      if (!stopping.get())
+      {
+         if (taskRunner == null)
+         {
+            dispatchSync(message);
+         }
+         else
+         {
+            synchronized (dispatchQueue)
+            {
+               dispatchQueue.add(message);
+            }
+            try
+            {
+               taskRunner.wakeup();
+            }
+            catch (InterruptedException e)
+            {
+               Thread.currentThread().interrupt();
+            }
+         }
+      }
+      else
+      {
+         if (message.isMessageDispatch())
+         {
+            MessageDispatch md = (MessageDispatch) message;
+            TransmitCallback sub = md.getTransmitCallback();
+            protocolManager.postProcessDispatch(md);
+            if (sub != null)
+            {
+               sub.onFailure();
+            }
+         }
+      }
+   }
+
+   public void dispatchSync(Command message)
+   {
+      try
+      {
+         processDispatch(message);
+      }
+      catch (IOException e)
+      {
+         serviceExceptionAsync(e);
+      }
+   }
+
+   public void serviceExceptionAsync(final IOException e)
+   {
+      if (asyncException.compareAndSet(false, true))
+      {
+         new Thread("Async Exception Handler")
+         {
+            @Override
+            public void run()
+            {
+               serviceException(e);
+            }
+         }.start();
+      }
+   }
+
+   public void serviceException(Throwable e)
+   {
+      // are we a transport exception such as not being able to dispatch
+      // synchronously to a transport
+      if (e instanceof IOException)
+      {
+         serviceTransportException((IOException) e);
+      }
+      else if (e.getClass() == AMQBrokerStoppedException.class)
+      {
+         // Handle the case where the broker is stopped
+         // But the client is still connected.
+         if (!stopping.get())
+         {
+            ConnectionError ce = new ConnectionError();
+            ce.setException(e);
+            dispatchSync(ce);
+            // Record the error that caused the transport to stop
+            this.stopError = e;
+            // Wait a little bit to try to get the output buffer to flush
+            // the exception notification to the client.
+            try
+            {
+               Thread.sleep(500);
+            }
+            catch (InterruptedException ie)
+            {
+               Thread.currentThread().interrupt();
+            }
+            // Worst case is we just kill the connection before the
+            // notification gets to him.
+            stopAsync();
+         }
+      }
+      else if (!stopping.get() && !inServiceException)
+      {
+         inServiceException = true;
+         try
+         {
+            ConnectionError ce = new ConnectionError();
+            ce.setException(e);
+            if (pendingStop)
+            {
+               dispatchSync(ce);
+            }
+            else
+            {
+               dispatchAsync(ce);
+            }
+         }
+         finally
+         {
+            inServiceException = false;
+         }
+      }
+   }
+
+   public void serviceTransportException(IOException e)
+   {
+      /*
+       * deal with it later BrokerService bService =
+       * connector.getBrokerService(); if (bService.isShutdownOnSlaveFailure())
+       * { if (brokerInfo != null) { if (brokerInfo.isSlaveBroker()) {
+       * LOG.error("Slave has exception: {} shutting down master now.",
+       * e.getMessage(), e); try { doStop(); bService.stop(); } catch (Exception
+       * ex) { LOG.warn("Failed to stop the master", ex); } } } } if
+       * (!stopping.get() && !pendingStop) { transportException.set(e); if
+       * (TRANSPORTLOG.isDebugEnabled()) { TRANSPORTLOG.debug(this + " failed: "
+       * + e, e); } else if (TRANSPORTLOG.isWarnEnabled() && !expected(e)) {
+       * TRANSPORTLOG.warn(this + " failed: " + e); } stopAsync(); }
+       */
+   }
+
+   public void setMarkedCandidate(boolean markedCandidate)
+   {
+      this.markedCandidate = markedCandidate;
+      if (!markedCandidate)
+      {
+         timeStamp = 0;
+         blockedCandidate = false;
+      }
+   }
+
+   protected void dispatch(Command command) throws IOException
+   {
+      try
+      {
+         setMarkedCandidate(true);
+         this.physicalSend(command);
+      }
+      finally
+      {
+         setMarkedCandidate(false);
+      }
+   }
+
+   protected void processDispatch(Command command) throws IOException
+   {
+      MessageDispatch messageDispatch = (MessageDispatch) (command
+            .isMessageDispatch() ? command : null);
+      try
+      {
+         if (!stopping.get())
+         {
+            if (messageDispatch != null)
+            {
+               protocolManager.preProcessDispatch(messageDispatch);
+            }
+            dispatch(command);
+         }
+      }
+      catch (IOException e)
+      {
+         if (messageDispatch != null)
+         {
+            TransmitCallback sub = messageDispatch.getTransmitCallback();
+            protocolManager.postProcessDispatch(messageDispatch);
+            if (sub != null)
+            {
+               sub.onFailure();
+            }
+            messageDispatch = null;
+            throw e;
+         }
+      }
+      finally
+      {
+         if (messageDispatch != null)
+         {
+            TransmitCallback sub = messageDispatch.getTransmitCallback();
+            protocolManager.postProcessDispatch(messageDispatch);
+            if (sub != null)
+            {
+               sub.onSuccess();
+            }
+         }
+      }
+   }
+
+   private AMQMessageAuthorizationPolicy getMessageAuthorizationPolicy()
+   {
+      return this.messageAuthorizationPolicy;
+   }
+
+   protected synchronized AMQTransportConnectionState unregisterConnectionState(
+         ConnectionId connectionId)
+   {
+      return connectionStateRegister.unregisterConnectionState(connectionId);
+   }
+
+   protected synchronized AMQTransportConnectionState registerConnectionState(
+         ConnectionId connectionId, AMQTransportConnectionState state)
+   {
+      AMQTransportConnectionState cs = null;
+      if (!connectionStateRegister.isEmpty()
+            && !connectionStateRegister.doesHandleMultipleConnectionStates())
+      {
+         // swap implementations
+         AMQTransportConnectionStateRegister newRegister = new AMQMapTransportConnectionStateRegister();
+         newRegister.intialize(connectionStateRegister);
+         connectionStateRegister = newRegister;
+      }
+      cs = connectionStateRegister.registerConnectionState(connectionId, state);
+      return cs;
+   }
+
+   public void delayedStop(final int waitTime, final String reason,
+         Throwable cause)
+   {
+      if (waitTime > 0)
+      {
+         synchronized (this)
+         {
+            pendingStop = true;
+            stopError = cause;
+         }
+         try
+         {
+            stopTaskRunnerFactory.execute(new Runnable()
+            {
+               @Override
+               public void run()
+               {
+                  try
+                  {
+                     Thread.sleep(waitTime);
+                     stopAsync();
+                  }
+                  catch (InterruptedException e)
+                  {
+                  }
+               }
+            });
+         }
+         catch (Throwable t)
+         {
+            // log error
+         }
+      }
+   }
+
+   public void stopAsync()
+   {
+      // If we're in the middle of starting then go no further... for now.
+      synchronized (this)
+      {
+         pendingStop = true;
+         if (starting)
+         {
+            // log
+            return;
+         }
+      }
+      if (stopping.compareAndSet(false, true))
+      {
+         // Let all the connection contexts know we are shutting down
+         // so that in progress operations can notice and unblock.
+         List<AMQTransportConnectionState> connectionStates = listConnectionStates();
+         for (AMQTransportConnectionState cs : connectionStates)
+         {
+            AMQConnectionContext connectionContext = cs.getContext();
+            if (connectionContext != null)
+            {
+               connectionContext.getStopping().set(true);
+            }
+         }
+         try
+         {
+            stopTaskRunnerFactory.execute(new Runnable()
+            {
+               @Override
+               public void run()
+               {
+                  serviceLock.writeLock().lock();
+                  try
+                  {
+                     doStop();
+                  }
+                  catch (Throwable e)
+                  {
+                     // LOG
+                  }
+                  finally
+                  {
+                     stopped.countDown();
+                     serviceLock.writeLock().unlock();
+                  }
+               }
+            });
+         }
+         catch (Throwable t)
+         {
+            // LOG
+            stopped.countDown();
+         }
+      }
+   }
+
+   protected synchronized List<AMQTransportConnectionState> listConnectionStates()
+   {
+      return connectionStateRegister.listConnectionStates();
+   }
+
+   protected void doStop() throws Exception
+   {
+      this.acceptorUsed.onStopped(this);
+      /*
+       * What's a duplex bridge? try { synchronized (this) { if (duplexBridge !=
+       * null) { duplexBridge.stop(); } } } catch (Exception ignore) {
+       * LOG.trace("Exception caught stopping. This exception is ignored.",
+       * ignore); }
+       */
+      try
+      {
+         getTransportConnection().close();
+      }
+      catch (Exception e)
+      {
+         // log
+      }
+
+      if (taskRunner != null)
+      {
+         taskRunner.shutdown(1);
+         taskRunner = null;
+      }
+
+      active = false;
+      // Run the MessageDispatch callbacks so that message references get
+      // cleaned up.
+      synchronized (dispatchQueue)
+      {
+         for (Iterator<Command> iter = dispatchQueue.iterator(); iter.hasNext();)
+         {
+            Command command = iter.next();
+            if (command.isMessageDispatch())
+            {
+               MessageDispatch md = (MessageDispatch) command;
+               TransmitCallback sub = md.getTransmitCallback();
+               protocolManager.postProcessDispatch(md);
+               if (sub != null)
+               {
+                  sub.onFailure();
+               }
+            }
+         }
+         dispatchQueue.clear();
+      }
+      //
+      // Remove all logical connection associated with this connection
+      // from the broker.
+      if (!protocolManager.isStopped())
+      {
+         List<AMQTransportConnectionState> connectionStates = listConnectionStates();
+         connectionStates = listConnectionStates();
+         for (AMQTransportConnectionState cs : connectionStates)
+         {
+            cs.getContext().getStopping().set(true);
+            try
+            {
+               processRemoveConnection(cs.getInfo().getConnectionId(), 0L);
+            }
+            catch (Throwable ignore)
+            {
+               ignore.printStackTrace();
+            }
+         }
+      }
+   }
+
+   @Override
+   public Response processAddConsumer(ConsumerInfo info)
+   {
+      Response resp = null;
+      try
+      {
+         protocolManager.addConsumer(this, info);
+      }
+      catch (Exception e)
+      {
+         if (e instanceof HornetQSecurityException)
+         {
+            resp = new ExceptionResponse(new JMSSecurityException(e.getMessage()));
+         }
+         else
+         {
+            resp = new ExceptionResponse(e);
+         }
+      }
+      return resp;
+   }
+
+   AMQConsumerBrokerExchange addConsumerBrokerExchange(ConsumerId id)
+   {
+      AMQConsumerBrokerExchange result = consumerExchanges.get(id);
+      if (result == null)
+      {
+         synchronized (consumerExchanges)
+         {
+            result = new AMQConsumerBrokerExchange();
+            AMQTransportConnectionState state = lookupConnectionState(id);
+            context = state.getContext();
+            result.setConnectionContext(context);
+            SessionState ss = state.getSessionState(id.getParentId());
+            if (ss != null)
+            {
+               ConsumerState cs = ss.getConsumerState(id);
+               if (cs != null)
+               {
+                  ConsumerInfo info = cs.getInfo();
+                  if (info != null)
+                  {
+                     if (info.getDestination() != null
+                           && info.getDestination().isPattern())
+                     {
+                        result.setWildcard(true);
+                     }
+                  }
+               }
+            }
+            consumerExchanges.put(id, result);
+         }
+      }
+      return result;
+   }
+
+   protected synchronized AMQTransportConnectionState lookupConnectionState(
+         ConsumerId id)
+   {
+      return connectionStateRegister.lookupConnectionState(id);
+   }
+
+   protected synchronized AMQTransportConnectionState lookupConnectionState(
+         ProducerId id)
+   {
+      return connectionStateRegister.lookupConnectionState(id);
+   }
+
+   public int getConsumerCount(ConnectionId connectionId)
+   {
+      int result = 0;
+      AMQTransportConnectionState cs = lookupConnectionState(connectionId);
+      if (cs != null)
+      {
+         for (SessionId sessionId : cs.getSessionIds())
+         {
+            SessionState sessionState = cs.getSessionState(sessionId);
+            if (sessionState != null)
+            {
+               result += sessionState.getConsumerIds().size();
+            }
+         }
+      }
+      return result;
+   }
+
+   public int getProducerCount(ConnectionId connectionId)
+   {
+      int result = 0;
+      AMQTransportConnectionState cs = lookupConnectionState(connectionId);
+      if (cs != null)
+      {
+         for (SessionId sessionId : cs.getSessionIds())
+         {
+            SessionState sessionState = cs.getSessionState(sessionId);
+            if (sessionState != null)
+            {
+               result += sessionState.getProducerIds().size();
+            }
+         }
+      }
+      return result;
+   }
+
+   public synchronized AMQTransportConnectionState lookupConnectionState(
+         ConnectionId connectionId)
+   {
+      return connectionStateRegister.lookupConnectionState(connectionId);
+   }
+
+   @Override
+   public Response processAddDestination(DestinationInfo dest) throws Exception
+   {
+      Response resp = null;
+      try
+      {
+         protocolManager.addDestination(this, dest);
+      }
+      catch (Exception e)
+      {
+         if (e instanceof HornetQSecurityException)
+         {
+            resp = new ExceptionResponse(new JMSSecurityException(e.getMessage()));
+         }
+         else
+         {
+            resp = new ExceptionResponse(e);
+         }
+      }
+      return resp;
+   }
+
+   @Override
+   public Response processAddProducer(ProducerInfo info) throws Exception
+   {
+      protocolManager.addProducer(this, info);
+      return null;
+   }
+
+   @Override
+   public Response processAddSession(SessionInfo info) throws Exception
+   {
+      ConnectionId connectionId = info.getSessionId().getParentId();
+      AMQTransportConnectionState cs = lookupConnectionState(connectionId);
+      // Avoid replaying dup commands
+      if (cs != null && !cs.getSessionIds().contains(info.getSessionId()))
+      {
+         protocolManager.addSession(this, info);
+         try
+         {
+            cs.addSession(info);
+         }
+         catch (IllegalStateException e)
+         {
+            e.printStackTrace();
+            protocolManager.removeSession(cs.getContext(), info);
+         }
+      }
+      return null;
+   }
+
+   @Override
+   public Response processBeginTransaction(TransactionInfo info) throws Exception
+   {
+      TransactionId txId = info.getTransactionId();
+
+      if (!txMap.containsKey(txId))
+      {
+         txMap.put(txId, info);
+      }
+      return null;
+   }
+
+   @Override
+   public Response processBrokerInfo(BrokerInfo arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception
+   {
+      protocolManager.commitTransactionOnePhase(info);
+      TransactionId txId = info.getTransactionId();
+      txMap.remove(txId);
+
+      return null;
+   }
+
+   @Override
+   public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception
+   {
+      protocolManager.commitTransactionTwoPhase(info);
+      TransactionId txId = info.getTransactionId();
+      txMap.remove(txId);
+
+      return null;
+   }
+
+   @Override
+   public Response processConnectionControl(ConnectionControl arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processConnectionError(ConnectionError arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processConsumerControl(ConsumerControl arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processControlCommand(ControlCommand arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processEndTransaction(TransactionInfo info) throws Exception
+   {
+      TransactionId txId = info.getTransactionId();
+
+      if (!txMap.containsKey(txId))
+      {
+         txMap.put(txId, info);
+      }
+      return null;
+   }
+
+   @Override
+   public Response processFlush(FlushCommand arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processForgetTransaction(TransactionInfo info) throws Exception
+   {
+      TransactionId txId = info.getTransactionId();
+      txMap.remove(txId);
+
+      protocolManager.forgetTransaction(info.getTransactionId());
+      return null;
+   }
+
+   @Override
+   public Response processKeepAlive(KeepAliveInfo arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processMessage(Message messageSend)
+   {
+      Response resp = null;
+      try
+      {
+         ProducerId producerId = messageSend.getProducerId();
+         AMQProducerBrokerExchange producerExchange = getProducerBrokerExchange(producerId);
+         final AMQConnectionContext pcontext = producerExchange.getConnectionContext();
+         final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo();
+         boolean sendProducerAck = !messageSend.isResponseRequired() && producerInfo.getWindowSize() > 0
+               && !pcontext.isInRecoveryMode();
+
+         AMQSession session = protocolManager.getSession(producerId.getParentId());
+
+         if (producerExchange.canDispatch(messageSend))
+         {
+            SendingResult result = session.send(producerExchange, messageSend, sendProducerAck);
+            if (result.isBlockNextSend())
+            {
+               if (!context.isNetworkConnection() && result.isSendFailIfNoSpace())
+               {
+                  throw new ResourceAllocationException("Usage Manager Memory Limit reached. Stopping producer ("
+                     + producerId + ") to prevent flooding "
+                     + result.getBlockingAddress() + "."
+                     + " See http://activemq.apache.org/producer-flow-control.html for more info");
+               }
+
+               if (producerInfo.getWindowSize() > 0 || messageSend.isResponseRequired())
+               {
+                  //in that case don't send the response
+                  //this will force the client to wait until
+                  //the response is got.
+                  if (context == null)
+                  {
+                     this.context = new AMQConnectionContext();
+                  }
+                  context.setDontSendReponse(true);
+               }
+               else
+               {
+                  //hang the connection until the space is available
+                  session.blockingWaitForSpace(producerExchange, result);
+               }
+            }
+            else if (sendProducerAck)
+            {
+               ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), messageSend.getSize());
+               this.dispatchAsync(ack);
+            }
+         }
+      }
+      catch (Exception e)
+      {
+         if (e instanceof HornetQSecurityException)
+         {
+            resp = new ExceptionResponse(new JMSSecurityException(e.getMessage()));
+         }
+         else
+         {
+            resp = new ExceptionResponse(e);
+         }
+      }
+      return resp;
+   }
+
+   private AMQProducerBrokerExchange getProducerBrokerExchange(ProducerId id) throws IOException
+   {
+      AMQProducerBrokerExchange result = producerExchanges.get(id);
+      if (result == null)
+      {
+         synchronized (producerExchanges)
+         {
+            result = new AMQProducerBrokerExchange();
+            AMQTransportConnectionState state = lookupConnectionState(id);
+            context = state.getContext();
+            result.setConnectionContext(context);
+            if (context.isReconnect()
+                  || (context.isNetworkConnection() && this.acceptorUsed
+                        .isAuditNetworkProducers()))
+            {
+               result.setLastStoredSequenceId(protocolManager
+                     .getPersistenceAdapter().getLastProducerSequenceId(id));
+            }
+            SessionState ss = state.getSessionState(id.getParentId());
+            if (ss != null)
+            {
+               result.setProducerState(ss.getProducerState(id));
+               ProducerState producerState = ss.getProducerState(id);
+               if (producerState != null && producerState.getInfo() != null)
+               {
+                  ProducerInfo info = producerState.getInfo();
+                  result.setMutable(info.getDestination() == null
+                        || info.getDestination().isComposite());
+               }
+            }
+            producerExchanges.put(id, result);
+         }
+      }
+      else
+      {
+         context = result.getConnectionContext();
+      }
+      return result;
+   }
+
+   @Override
+   public Response processMessageAck(MessageAck ack) throws Exception
+   {
+      ConsumerId consumerId = ack.getConsumerId();
+      SessionId sessionId = consumerId.getParentId();
+      AMQSession session = protocolManager.getSession(sessionId);
+      session.acknowledge(ack);
+      return null;
+   }
+
+   @Override
+   public Response processMessageDispatch(MessageDispatch arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processMessageDispatchNotification(
+         MessageDispatchNotification arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processMessagePull(MessagePull arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processPrepareTransaction(TransactionInfo info) throws Exception
+   {
+      protocolManager.prepareTransaction(info);
+      return null;
+   }
+
+   @Override
+   public Response processProducerAck(ProducerAck arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processRecoverTransactions(TransactionInfo info) throws Exception
+   {
+      AMQTransportConnectionState cs = lookupConnectionState(info.getConnectionId());
+      Set<SessionId> sIds = cs.getSessionIds();
+      TransactionId[] recovered = protocolManager.recoverTransactions(sIds);
+      return new DataArrayResponse(recovered);
+   }
+
+   @Override
+   public Response processRemoveConnection(ConnectionId id,
+         long lastDeliveredSequenceId) throws Exception
+   {
+      AMQTransportConnectionState cs = lookupConnectionState(id);
+      if (cs != null)
+      {
+         // Don't allow things to be added to the connection state while we
+         // are shutting down.
+         cs.shutdown();
+         // Cascade the connection stop to the sessions.
+         for (SessionId sessionId : cs.getSessionIds())
+         {
+            try
+            {
+               processRemoveSession(sessionId, lastDeliveredSequenceId);
+            }
+            catch (Throwable e)
+            {
+               // LOG
+            }
+         }
+
+         try
+         {
+            protocolManager.removeConnection(cs.getContext(), cs.getInfo(),
+                  null);
+         }
+         catch (Throwable e)
+         {
+            // log
+         }
+         AMQTransportConnectionState state = unregisterConnectionState(id);
+         if (state != null)
+         {
+            synchronized (brokerConnectionStates)
+            {
+               // If we are the last reference, we should remove the state
+               // from the broker.
+               if (state.decrementReference() == 0)
+               {
+                  brokerConnectionStates.remove(id);
+               }
+            }
+         }
+      }
+      return null;
+   }
+
+   @Override
+   public Response processRemoveConsumer(ConsumerId id,
+         long lastDeliveredSequenceId) throws Exception
+   {
+      SessionId sessionId = id.getParentId();
+      ConnectionId connectionId = sessionId.getParentId();
+      AMQTransportConnectionState cs = lookupConnectionState(connectionId);
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot remove a consumer from a connection that had not been registered: "
+                     + connectionId);
+      }
+      SessionState ss = cs.getSessionState(sessionId);
+      if (ss == null)
+      {
+         throw new IllegalStateException(
+               "Cannot remove a consumer from a session that had not been registered: "
+                     + sessionId);
+      }
+      ConsumerState consumerState = ss.removeConsumer(id);
+      if (consumerState == null)
+      {
+         throw new IllegalStateException(
+               "Cannot remove a consumer that had not been registered: " + id);
+      }
+      ConsumerInfo info = consumerState.getInfo();
+      info.setLastDeliveredSequenceId(lastDeliveredSequenceId);
+      protocolManager.removeConsumer(cs.getContext(), consumerState.getInfo());
+      removeConsumerBrokerExchange(id);
+      return null;
+   }
+
+   private void removeConsumerBrokerExchange(ConsumerId id)
+   {
+      synchronized (consumerExchanges)
+      {
+         consumerExchanges.remove(id);
+      }
+   }
+
+   @Override
+   public Response processRemoveDestination(DestinationInfo info) throws Exception
+   {
+      ActiveMQDestination dest = info.getDestination();
+      if (dest.isQueue())
+      {
+         String qName = "jms.queue." + dest.getPhysicalName();
+         protocolManager.deleteQueue(qName);
+      }
+      return null;
+   }
+
+   @Override
+   public Response processRemoveProducer(ProducerId id) throws Exception
+   {
+      protocolManager.removeProducer(id);
+      return null;
+   }
+
+   @Override
+   public Response processRemoveSession(SessionId id,
+         long lastDeliveredSequenceId) throws Exception
+   {
+      ConnectionId connectionId = id.getParentId();
+      AMQTransportConnectionState cs = lookupConnectionState(connectionId);
+      if (cs == null)
+      {
+         throw new IllegalStateException(
+               "Cannot remove session from connection that had not been registered: "
+                     + connectionId);
+      }
+      SessionState session = cs.getSessionState(id);
+      if (session == null)
+      {
+         throw new IllegalStateException(
+               "Cannot remove session that had not been registered: " + id);
+      }
+      // Don't let new consumers or producers get added while we are closing
+      // this down.
+      session.shutdown();
+      // Cascade the connection stop to the consumers and producers.
+      for (ConsumerId consumerId : session.getConsumerIds())
+      {
+         try
+         {
+            processRemoveConsumer(consumerId, lastDeliveredSequenceId);
+         }
+         catch (Throwable e)
+         {
+            // LOG.warn("Failed to remove consumer: {}", consumerId, e);
+         }
+      }
+      for (ProducerId producerId : session.getProducerIds())
+      {
+         try
+         {
+            processRemoveProducer(producerId);
+         }
+         catch (Throwable e)
+         {
+            // LOG.warn("Failed to remove producer: {}", producerId, e);
+         }
+      }
+      cs.removeSession(id);
+      protocolManager.removeSession(cs.getContext(), session.getInfo());
+      return null;
+   }
+
+   @Override
+   public Response processRemoveSubscription(RemoveSubscriptionInfo arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   @Override
+   public Response processRollbackTransaction(TransactionInfo info) throws Exception
+   {
+      protocolManager.rollbackTransaction(info);
+      TransactionId txId = info.getTransactionId();
+      txMap.remove(txId);
+      return null;
+   }
+
+   @Override
+   public Response processShutdown(ShutdownInfo info) throws Exception
+   {
+      return null;
+   }
+
+   @Override
+   public Response processWireFormat(WireFormatInfo arg0) throws Exception
+   {
+      throw new IllegalStateException("not implemented! ");
+   }
+
+   public int getMaximumConsumersAllowedPerConnection()
+   {
+      return this.acceptorUsed.getMaximumConsumersAllowedPerConnection();
+   }
+
+   public int getMaximumProducersAllowedPerConnection()
+   {
+      return this.acceptorUsed.getMaximumProducersAllowedPerConnection();
+   }
+
+   public void deliverMessage(MessageDispatch dispatch)
+   {
+      Message m = dispatch.getMessage();
+      if (m != null)
+      {
+         long endTime = System.currentTimeMillis();
+         m.setBrokerOutTime(endTime);
+      }
+
+      protocolManager.send(this, dispatch);
+   }
+
+   public WireFormat getMarshaller()
+   {
+      return this.wireFormat;
+   }
+
+   public void registerTempQueue(SimpleString qName)
+   {
+      tempQueues.add(qName.toString());
+   }
+
+   @Override
+   public void disconnect(String reason, boolean fail)
+   {
+      destroy();
+   }
+
+   @Override
+   public void fail(HornetQException e, String message)
+   {
+      destroy();
+   }
+
+   public void setAdvisorySession(AMQSession amqSession)
+   {
+      this.advisorySession = amqSession;
+   }
+
+   public AMQSession getAdvisorySession()
+   {
+      return this.advisorySession;
+   }
+
+   public AMQConnectionContext getConext()
+   {
+      return this.state.getContext();
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireMessageConverter.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireMessageConverter.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireMessageConverter.java
new file mode 100644
index 0000000..1024622
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/OpenWireMessageConverter.java
@@ -0,0 +1,787 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.Map.Entry;
+
+import javax.jms.JMSException;
+
+import org.apache.activemq.command.ActiveMQBytesMessage;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ActiveMQMapMessage;
+import org.apache.activemq.command.ActiveMQMessage;
+import org.apache.activemq.command.ActiveMQObjectMessage;
+import org.apache.activemq.command.ActiveMQStreamMessage;
+import org.apache.activemq.command.ActiveMQTextMessage;
+import org.apache.activemq.command.BrokerId;
+import org.apache.activemq.command.CommandTypes;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.DataStructure;
+import org.apache.activemq.command.Message;
+import org.apache.activemq.command.MessageDispatch;
+import org.apache.activemq.command.MessageId;
+import org.apache.activemq.command.ProducerId;
+import org.apache.activemq.command.TransactionId;
+import org.apache.activemq.util.ByteArrayInputStream;
+import org.apache.activemq.util.ByteSequence;
+import org.apache.activemq.util.MarshallingSupport;
+import org.apache.activemq.wireformat.WireFormat;
+import org.fusesource.hawtbuf.UTF8Buffer;
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.HornetQPropertyConversionException;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.protocol.openwire.amq.AMQConsumer;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.impl.ServerMessageImpl;
+import org.hornetq.spi.core.protocol.MessageConverter;
+import org.hornetq.utils.DataConstants;
+import org.hornetq.utils.TypedProperties;
+import org.hornetq.utils.UUIDGenerator;
+
+public class OpenWireMessageConverter implements MessageConverter
+{
+   public static final String AMQ_PREFIX = "__HDR_";
+   public static final String AMQ_MSG_DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY = AMQ_PREFIX + "dlqDeliveryFailureCause";
+
+   private static final String AMQ_MSG_ARRIVAL = AMQ_PREFIX + "ARRIVAL";
+   private static final String AMQ_MSG_BROKER_IN_TIME = AMQ_PREFIX + "BROKER_IN_TIME";
+
+   private static final String AMQ_MSG_BROKER_PATH = AMQ_PREFIX + "BROKER_PATH";
+   private static final String AMQ_MSG_CLUSTER = AMQ_PREFIX + "CLUSTER";
+   private static final String AMQ_MSG_COMMAND_ID = AMQ_PREFIX + "COMMAND_ID";
+   private static final String AMQ_MSG_DATASTRUCTURE = AMQ_PREFIX + "DATASTRUCTURE";
+   private static final String AMQ_MSG_DESTINATION = AMQ_PREFIX + "DESTINATION";
+   private static final String AMQ_MSG_GROUP_ID = AMQ_PREFIX + "GROUP_ID";
+   private static final String AMQ_MSG_GROUP_SEQUENCE = AMQ_PREFIX + "GROUP_SEQUENCE";
+   private static final String AMQ_MSG_MESSAGE_ID = AMQ_PREFIX + "MESSAGE_ID";
+   private static final String AMQ_MSG_ORIG_DESTINATION = AMQ_PREFIX + "ORIG_DESTINATION";
+   private static final String AMQ_MSG_ORIG_TXID = AMQ_PREFIX + "ORIG_TXID";
+   private static final String AMQ_MSG_PRODUCER_ID = AMQ_PREFIX + "PRODUCER_ID";
+   private static final String AMQ_MSG_MARSHALL_PROP = AMQ_PREFIX + "MARSHALL_PROP";
+   private static final String AMQ_MSG_REDELIVER_COUNTER = AMQ_PREFIX + "REDELIVER_COUNTER";
+   private static final String AMQ_MSG_REPLY_TO = AMQ_PREFIX + "REPLY_TO";
+
+   private static final String AMQ_MSG_CONSUMER_ID = AMQ_PREFIX + "CONSUMER_ID";
+   private static final String AMQ_MSG_TX_ID = AMQ_PREFIX + "TX_ID";
+   private static final String AMQ_MSG_USER_ID = AMQ_PREFIX + "USER_ID";
+
+   private static final String AMQ_MSG_COMPRESSED = AMQ_PREFIX + "COMPRESSED";
+   private static final String AMQ_MSG_DROPPABLE = AMQ_PREFIX + "DROPPABLE";
+
+   @Override
+   public ServerMessage inbound(Object message)
+   {
+      // TODO: implement this
+      return null;
+   }
+
+   public Object outbound(ServerMessage message, int deliveryCount)
+   {
+      // TODO: implement this
+      return null;
+   }
+
+   //convert an ActiveMQ message to coreMessage
+   public static void toCoreMessage(ServerMessageImpl coreMessage, Message messageSend, WireFormat marshaller) throws IOException
+   {
+      String type = messageSend.getType();
+      if (type != null)
+      {
+         coreMessage.putStringProperty(new SimpleString("JMSType"), new SimpleString(type));
+      }
+      coreMessage.setDurable(messageSend.isPersistent());
+      coreMessage.setExpiration(messageSend.getExpiration());
+      coreMessage.setPriority(messageSend.getPriority());
+      coreMessage.setTimestamp(messageSend.getTimestamp());
+
+      byte coreType = toCoreType(messageSend.getDataStructureType());
+      coreMessage.setType(coreType);
+
+      ByteSequence contents = messageSend.getContent();
+      if (contents != null)
+      {
+         HornetQBuffer body = coreMessage.getBodyBuffer();
+         switch (coreType)
+         {
+            case org.hornetq.api.core.Message.TEXT_TYPE:
+               ByteArrayInputStream tis = new ByteArrayInputStream(contents);
+               DataInputStream tdataIn = new DataInputStream(tis);
+               String text = MarshallingSupport.readUTF8(tdataIn);
+               tdataIn.close();
+               body.writeNullableSimpleString(new SimpleString(text));
+               break;
+            case org.hornetq.api.core.Message.MAP_TYPE:
+               InputStream mis = new ByteArrayInputStream(contents);
+               DataInputStream mdataIn = new DataInputStream(mis);
+               Map<String, Object> map = MarshallingSupport.unmarshalPrimitiveMap(mdataIn);
+               mdataIn.close();
+               TypedProperties props = new TypedProperties();
+               loadMapIntoProperties(props, map);
+               props.encode(body);
+               break;
+            case org.hornetq.api.core.Message.OBJECT_TYPE:
+               body.writeInt(contents.length);
+               body.writeBytes(contents.data, contents.offset, contents.length);
+               break;
+            case org.hornetq.api.core.Message.STREAM_TYPE:
+               InputStream sis = new ByteArrayInputStream(contents);
+               DataInputStream sdis = new DataInputStream(sis);
+               int stype = sdis.read();
+               while (stype != -1)
+               {
+                  switch (stype)
+                  {
+                     case MarshallingSupport.BOOLEAN_TYPE:
+                        body.writeByte(DataConstants.BOOLEAN);
+                        body.writeBoolean(sdis.readBoolean());
+                        break;
+                     case MarshallingSupport.BYTE_TYPE:
+                        body.writeByte(DataConstants.BYTE);
+                        body.writeByte(sdis.readByte());
+                        break;
+                     case MarshallingSupport.BYTE_ARRAY_TYPE:
+                        body.writeByte(DataConstants.BYTES);
+                        int slen = sdis.readInt();
+                        byte[] sbytes = new byte[slen];
+                        sdis.read(sbytes);
+                        body.writeInt(slen);
+                        body.writeBytes(sbytes);
+                        break;
+                     case MarshallingSupport.CHAR_TYPE:
+                        body.writeByte(DataConstants.CHAR);
+                        char schar = sdis.readChar();
+                        body.writeShort((short)schar);
+                        break;
+                     case MarshallingSupport.DOUBLE_TYPE:
+                        body.writeByte(DataConstants.DOUBLE);
+                        double sdouble = sdis.readDouble();
+                        body.writeLong(Double.doubleToLongBits(sdouble));
+                        break;
+                     case MarshallingSupport.FLOAT_TYPE:
+                        body.writeByte(DataConstants.FLOAT);
+                        float sfloat = sdis.readFloat();
+                        body.writeInt(Float.floatToIntBits(sfloat));
+                        break;
+                     case MarshallingSupport.INTEGER_TYPE:
+                        body.writeByte(DataConstants.INT);
+                        body.writeInt(sdis.readInt());
+                        break;
+                     case MarshallingSupport.LONG_TYPE:
+                        body.writeByte(DataConstants.LONG);
+                        body.writeLong(sdis.readLong());
+                        break;
+                     case MarshallingSupport.SHORT_TYPE:
+                        body.writeByte(DataConstants.SHORT);
+                        body.writeShort(sdis.readShort());
+                        break;
+                     case MarshallingSupport.STRING_TYPE:
+                        body.writeByte(DataConstants.STRING);
+                        String sstring = sdis.readUTF();
+                        body.writeNullableString(sstring);
+                        break;
+                     case MarshallingSupport.BIG_STRING_TYPE:
+                        body.writeByte(DataConstants.STRING);
+                        String sbigString = MarshallingSupport.readUTF8(sdis);
+                        body.writeNullableString(sbigString);
+                        break;
+                     case MarshallingSupport.NULL:
+                        body.writeByte(DataConstants.STRING);
+                        body.writeNullableString(null);
+                        break;
+                     default:
+                        //something we don't know, ignore
+                        break;
+                  }
+                  stype = sdis.read();
+               }
+               sdis.close();
+               break;
+            default:
+               body.writeBytes(contents.data, contents.offset, contents.length);
+               break;
+         }
+      }
+      //amq specific
+      coreMessage.putLongProperty(AMQ_MSG_ARRIVAL, messageSend.getArrival());
+      coreMessage.putLongProperty(AMQ_MSG_BROKER_IN_TIME, messageSend.getBrokerInTime());
+      BrokerId[] brokers = messageSend.getBrokerPath();
+      if (brokers != null)
+      {
+         StringBuilder builder = new StringBuilder();
+         for (int i = 0; i < brokers.length; i++)
+         {
+            builder.append(brokers[i].getValue());
+            if (i != (brokers.length - 1))
+            {
+               builder.append(","); //is this separator safe?
+            }
+         }
+         coreMessage.putStringProperty(AMQ_MSG_BROKER_PATH, builder.toString());
+      }
+      BrokerId[] cluster = messageSend.getCluster();
+      if (cluster != null)
+      {
+         StringBuilder builder = new StringBuilder();
+         for (int i = 0; i < cluster.length; i++)
+         {
+            builder.append(cluster[i].getValue());
+            if (i != (cluster.length - 1))
+            {
+               builder.append(","); //is this separator safe?
+            }
+         }
+         coreMessage.putStringProperty(AMQ_MSG_CLUSTER, builder.toString());
+      }
+
+      coreMessage.putIntProperty(AMQ_MSG_COMMAND_ID, messageSend.getCommandId());
+      String corrId = messageSend.getCorrelationId();
+      if (corrId != null)
+      {
+         coreMessage.putStringProperty("JMSCorrelationID", corrId);
+      }
+      DataStructure ds = messageSend.getDataStructure();
+      if (ds != null)
+      {
+         ByteSequence dsBytes = marshaller.marshal(ds);
+         dsBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_DATASTRUCTURE, dsBytes.data);
+      }
+      ActiveMQDestination dest = messageSend.getDestination();
+      ByteSequence destBytes = marshaller.marshal(dest);
+      destBytes.compact();
+      coreMessage.putBytesProperty(AMQ_MSG_DESTINATION, destBytes.data);
+      String groupId = messageSend.getGroupID();
+      if (groupId != null)
+      {
+         coreMessage.putStringProperty(AMQ_MSG_GROUP_ID, groupId);
+      }
+      coreMessage.putIntProperty(AMQ_MSG_GROUP_SEQUENCE, messageSend.getGroupSequence());
+
+      MessageId messageId = messageSend.getMessageId();
+
+      ByteSequence midBytes = marshaller.marshal(messageId);
+      midBytes.compact();
+      coreMessage.putBytesProperty(AMQ_MSG_MESSAGE_ID, midBytes.data);
+
+      ActiveMQDestination origDest = messageSend.getOriginalDestination();
+      if (origDest != null)
+      {
+         ByteSequence origDestBytes = marshaller.marshal(origDest);
+         origDestBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_ORIG_DESTINATION, origDestBytes.data);
+      }
+      TransactionId origTxId = messageSend.getOriginalTransactionId();
+      if (origTxId != null)
+      {
+         ByteSequence origTxBytes = marshaller.marshal(origTxId);
+         origTxBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_ORIG_TXID, origTxBytes.data);
+      }
+      ProducerId producerId = messageSend.getProducerId();
+      if (producerId != null)
+      {
+         ByteSequence producerIdBytes = marshaller.marshal(producerId);
+         producerIdBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_PRODUCER_ID, producerIdBytes.data);
+      }
+      ByteSequence propBytes = messageSend.getMarshalledProperties();
+      if (propBytes != null)
+      {
+         propBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_MARSHALL_PROP, propBytes.data);
+         //unmarshall properties to core so selector will work
+         Map<String, Object> props = messageSend.getProperties();
+         //Map<String, Object> props = MarshallingSupport.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(propBytes)));
+         Iterator<Entry<String, Object>> iterEntries = props.entrySet().iterator();
+         while (iterEntries.hasNext())
+         {
+            Entry<String, Object> ent = iterEntries.next();
+
+            Object value = ent.getValue();
+            try
+            {
+               coreMessage.putObjectProperty(ent.getKey(), value);
+            }
+            catch (HornetQPropertyConversionException e)
+            {
+               coreMessage.putStringProperty(ent.getKey(), value.toString());
+            }
+         }
+      }
+
+      coreMessage.putIntProperty(AMQ_MSG_REDELIVER_COUNTER, messageSend.getRedeliveryCounter());
+      ActiveMQDestination replyTo = messageSend.getReplyTo();
+      if (replyTo != null)
+      {
+         ByteSequence replyToBytes = marshaller.marshal(replyTo);
+         replyToBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_REPLY_TO, replyToBytes.data);
+      }
+
+      ConsumerId consumerId = messageSend.getTargetConsumerId();
+
+      if (consumerId != null)
+      {
+         ByteSequence consumerIdBytes = marshaller.marshal(consumerId);
+         consumerIdBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_CONSUMER_ID, consumerIdBytes.data);
+      }
+      TransactionId txId = messageSend.getTransactionId();
+      if (txId != null)
+      {
+         ByteSequence txIdBytes = marshaller.marshal(txId);
+         txIdBytes.compact();
+         coreMessage.putBytesProperty(AMQ_MSG_TX_ID, txIdBytes.data);
+      }
+
+      String userId = messageSend.getUserID();
+      if (userId != null)
+      {
+         coreMessage.putStringProperty(AMQ_MSG_USER_ID, userId);
+      }
+      coreMessage.putBooleanProperty(AMQ_MSG_COMPRESSED, messageSend.isCompressed());
+      coreMessage.putBooleanProperty(AMQ_MSG_DROPPABLE, messageSend.isDroppable());
+   }
+
+   private static void loadMapIntoProperties(TypedProperties props, Map<String, Object> map)
+   {
+      Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
+      while (iter.hasNext())
+      {
+         Entry<String, Object> entry = iter.next();
+         SimpleString key = new SimpleString(entry.getKey());
+         Object value = entry.getValue();
+         if (value instanceof UTF8Buffer)
+         {
+            value = ((UTF8Buffer)value).toString();
+         }
+         TypedProperties.setObjectProperty(key, value, props);
+      }
+   }
+
+   public static byte toCoreType(byte amqType)
+   {
+      switch (amqType)
+      {
+         case CommandTypes.ACTIVEMQ_BLOB_MESSAGE:
+            throw new IllegalStateException("We don't support BLOB type yet!");
+         case CommandTypes.ACTIVEMQ_BYTES_MESSAGE:
+            return org.hornetq.api.core.Message.BYTES_TYPE;
+         case CommandTypes.ACTIVEMQ_MAP_MESSAGE:
+            return org.hornetq.api.core.Message.MAP_TYPE;
+         case CommandTypes.ACTIVEMQ_OBJECT_MESSAGE:
+            return org.hornetq.api.core.Message.OBJECT_TYPE;
+         case CommandTypes.ACTIVEMQ_STREAM_MESSAGE:
+            return org.hornetq.api.core.Message.STREAM_TYPE;
+         case CommandTypes.ACTIVEMQ_TEXT_MESSAGE:
+            return org.hornetq.api.core.Message.TEXT_TYPE;
+         case CommandTypes.ACTIVEMQ_MESSAGE:
+            return org.hornetq.api.core.Message.DEFAULT_TYPE;
+         default:
+            throw new IllegalStateException("Unknown ActiveMQ message type: " + amqType);
+      }
+   }
+
+   public static MessageDispatch createMessageDispatch(ServerMessage message,
+         int deliveryCount, AMQConsumer consumer) throws IOException
+   {
+      ActiveMQMessage amqMessage = toAMQMessage(message, consumer.getMarshaller());
+
+      MessageDispatch md = new MessageDispatch();
+      md.setConsumerId(consumer.getId());
+      md.setMessage(amqMessage);
+      md.setRedeliveryCounter(deliveryCount);
+      ActiveMQDestination destination = amqMessage.getDestination();
+      md.setDestination(destination);
+
+      return md;
+   }
+
+   private static ActiveMQMessage toAMQMessage(ServerMessage coreMessage, WireFormat marshaller) throws IOException
+   {
+      ActiveMQMessage amqMsg = null;
+      byte coreType = coreMessage.getType();
+      switch (coreType)
+      {
+         case org.hornetq.api.core.Message.BYTES_TYPE:
+            amqMsg = new ActiveMQBytesMessage();
+            break;
+         case org.hornetq.api.core.Message.MAP_TYPE:
+            amqMsg = new ActiveMQMapMessage();
+            break;
+         case org.hornetq.api.core.Message.OBJECT_TYPE:
+            amqMsg = new ActiveMQObjectMessage();
+            break;
+         case org.hornetq.api.core.Message.STREAM_TYPE:
+            amqMsg = new ActiveMQStreamMessage();
+            break;
+         case org.hornetq.api.core.Message.TEXT_TYPE:
+            amqMsg = new ActiveMQTextMessage();
+            break;
+         case org.hornetq.api.core.Message.DEFAULT_TYPE:
+            amqMsg = new ActiveMQMessage();
+            break;
+         default:
+            throw new IllegalStateException("Unknown message type: " + coreMessage.getType());
+      }
+
+      String type = coreMessage.getStringProperty(new SimpleString("JMSType"));
+      if (type != null)
+      {
+         amqMsg.setJMSType(type);
+      }
+      amqMsg.setPersistent(coreMessage.isDurable());
+      amqMsg.setExpiration(coreMessage.getExpiration());
+      amqMsg.setPriority(coreMessage.getPriority());
+      amqMsg.setTimestamp(coreMessage.getTimestamp());
+
+      Long brokerInTime = (Long) coreMessage.getObjectProperty(AMQ_MSG_BROKER_IN_TIME);
+      if (brokerInTime == null)
+      {
+         brokerInTime = 0L;
+      }
+      amqMsg.setBrokerInTime(brokerInTime);
+
+      HornetQBuffer buffer = coreMessage.getBodyBuffer();
+      if (buffer != null)
+      {
+         buffer.resetReaderIndex();
+         byte[] bytes = null;
+         synchronized (buffer)
+         {
+            if (coreType == org.hornetq.api.core.Message.TEXT_TYPE)
+            {
+               SimpleString text = buffer.readNullableSimpleString();
+
+               if (text != null)
+               {
+                  ByteArrayOutputStream out = new ByteArrayOutputStream(text.length() + 4);
+                  DataOutputStream dataOut = new DataOutputStream(out);
+                  MarshallingSupport.writeUTF8(dataOut, text.toString());
+                  bytes = out.toByteArray();
+                  out.close();
+               }
+            }
+            else if (coreType == org.hornetq.api.core.Message.MAP_TYPE)
+            {
+               TypedProperties mapData = new TypedProperties();
+               mapData.decode(buffer);
+
+               Map<String, Object> map = mapData.getMap();
+               ByteArrayOutputStream out = new ByteArrayOutputStream(mapData.getEncodeSize());
+               DataOutputStream dataOut = new DataOutputStream(out);
+               MarshallingSupport.marshalPrimitiveMap(map, dataOut);
+               bytes = out.toByteArray();
+               dataOut.close();
+            }
+            else if (coreType == org.hornetq.api.core.Message.OBJECT_TYPE)
+            {
+               int len = buffer.readInt();
+               bytes = new byte[len];
+               buffer.readBytes(bytes);
+            }
+            else if (coreType == org.hornetq.api.core.Message.STREAM_TYPE)
+            {
+               ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.readableBytes());
+               DataOutputStream dataOut = new DataOutputStream(out);
+
+               boolean stop = false;
+               while (!stop && buffer.readable())
+               {
+                  byte primitiveType = buffer.readByte();
+                  switch (primitiveType)
+                  {
+                     case DataConstants.BOOLEAN:
+                        MarshallingSupport.marshalBoolean(dataOut, buffer.readBoolean());
+                        break;
+                     case DataConstants.BYTE:
+                        MarshallingSupport.marshalByte(dataOut, buffer.readByte());
+                        break;
+                     case DataConstants.BYTES:
+                        int len = buffer.readInt();
+                        byte[] bytesData = new byte[len];
+                        buffer.readBytes(bytesData);
+                        MarshallingSupport.marshalByteArray(dataOut, bytesData);
+                        break;
+                     case DataConstants.CHAR:
+                        char ch = (char)buffer.readShort();
+                        MarshallingSupport.marshalChar(dataOut, ch);
+                        break;
+                     case DataConstants.DOUBLE:
+                        double doubleVal = Double.longBitsToDouble(buffer.readLong());
+                        MarshallingSupport.marshalDouble(dataOut, doubleVal);
+                        break;
+                     case DataConstants.FLOAT:
+                        Float floatVal = Float.intBitsToFloat(buffer.readInt());
+                        MarshallingSupport.marshalFloat(dataOut, floatVal);
+                        break;
+                     case DataConstants.INT:
+                        MarshallingSupport.marshalInt(dataOut, buffer.readInt());
+                        break;
+                     case DataConstants.LONG:
+                        MarshallingSupport.marshalLong(dataOut, buffer.readLong());
+                        break;
+                     case DataConstants.SHORT:
+                        MarshallingSupport.marshalShort(dataOut, buffer.readShort());
+                        break;
+                     case DataConstants.STRING:
+                        String string = buffer.readNullableString();
+                        if (string == null)
+                        {
+                           MarshallingSupport.marshalNull(dataOut);
+                        }
+                        else
+                        {
+                           MarshallingSupport.marshalString(dataOut, string);
+                        }
+                        break;
+                     default:
+                        //now we stop
+                        stop = true;
+                        break;
+                  }
+               }
+               bytes = out.toByteArray();
+               dataOut.close();
+            }
+            else
+            {
+               int n = buffer.readableBytes();
+               bytes = new byte[n];
+               buffer.readBytes(bytes);
+            }
+
+            buffer.resetReaderIndex();// this is important for topics as the buffer
+                                      // may be read multiple times
+         }
+
+         if (bytes != null)
+         {
+            ByteSequence content = new ByteSequence(bytes);
+            amqMsg.setContent(content);
+         }
+      }
+
+      //we need check null because messages may come from other clients
+      //and those amq specific attribute may not be set.
+      Long arrival = (Long) coreMessage.getObjectProperty(AMQ_MSG_ARRIVAL);
+      if (arrival == null)
+      {
+         //messages from other sources (like core client) may not set this prop
+         arrival = 0L;
+      }
+      amqMsg.setArrival(arrival);
+
+      String brokerPath = (String) coreMessage.getObjectProperty(AMQ_MSG_BROKER_PATH);
+      if (brokerPath != null && brokerPath.isEmpty())
+      {
+         String[] brokers = brokerPath.split(",");
+         BrokerId[] bids = new BrokerId[brokers.length];
+         for (int i = 0; i < bids.length; i++)
+         {
+            bids[i] = new BrokerId(brokers[i]);
+         }
+         amqMsg.setBrokerPath(bids);
+      }
+
+      String clusterPath = (String) coreMessage.getObjectProperty(AMQ_MSG_CLUSTER);
+      if (clusterPath != null && clusterPath.isEmpty())
+      {
+         String[] cluster = clusterPath.split(",");
+         BrokerId[] bids = new BrokerId[cluster.length];
+         for (int i = 0; i < bids.length; i++)
+         {
+            bids[i] = new BrokerId(cluster[i]);
+         }
+         amqMsg.setCluster(bids);
+      }
+
+      Integer commandId = (Integer) coreMessage.getObjectProperty(AMQ_MSG_COMMAND_ID);
+      if (commandId == null)
+      {
+         commandId = -1;
+      }
+      amqMsg.setCommandId(commandId);
+
+      SimpleString corrId = (SimpleString) coreMessage.getObjectProperty("JMSCorrelationID");
+      if (corrId != null)
+      {
+         amqMsg.setCorrelationId(corrId.toString());
+      }
+
+      byte[] dsBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_DATASTRUCTURE);
+      if (dsBytes != null)
+      {
+         ByteSequence seq = new ByteSequence(dsBytes);
+         DataStructure ds = (DataStructure)marshaller.unmarshal(seq);
+         amqMsg.setDataStructure(ds);
+      }
+
+      byte[] destBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_DESTINATION);
+      if (destBytes != null)
+      {
+         ByteSequence seq = new ByteSequence(destBytes);
+         ActiveMQDestination dest = (ActiveMQDestination) marshaller.unmarshal(seq);
+         amqMsg.setDestination(dest);
+      }
+
+      String groupId = (String) coreMessage.getObjectProperty(AMQ_MSG_GROUP_ID);
+      if (groupId != null)
+      {
+         amqMsg.setGroupID(groupId);
+      }
+
+      Integer groupSequence = (Integer) coreMessage.getObjectProperty(AMQ_MSG_GROUP_SEQUENCE);
+      if (groupSequence == null)
+      {
+         groupSequence = -1;
+      }
+      amqMsg.setGroupSequence(groupSequence);
+
+      MessageId mid = null;
+      byte[] midBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_MESSAGE_ID);
+      if (midBytes != null)
+      {
+         ByteSequence midSeq = new ByteSequence(midBytes);
+         mid = (MessageId)marshaller.unmarshal(midSeq);
+      }
+      else
+      {
+         mid = new MessageId(UUIDGenerator.getInstance().generateStringUUID() + ":-1");
+      }
+
+      amqMsg.setMessageId(mid);
+
+      byte[] origDestBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_ORIG_DESTINATION);
+      if (origDestBytes != null)
+      {
+         ActiveMQDestination origDest = (ActiveMQDestination) marshaller.unmarshal(new ByteSequence(origDestBytes));
+         amqMsg.setOriginalDestination(origDest);
+      }
+
+      byte[] origTxIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_ORIG_TXID);
+      if (origTxIdBytes != null)
+      {
+         TransactionId origTxId = (TransactionId) marshaller.unmarshal(new ByteSequence(origTxIdBytes));
+         amqMsg.setOriginalTransactionId(origTxId);
+      }
+
+      byte[] producerIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_PRODUCER_ID);
+      if (producerIdBytes != null)
+      {
+         ProducerId producerId = (ProducerId) marshaller.unmarshal(new ByteSequence(producerIdBytes));
+         amqMsg.setProducerId(producerId);
+      }
+
+      byte[] marshalledBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_MARSHALL_PROP);
+      if (marshalledBytes != null)
+      {
+         amqMsg.setMarshalledProperties(new ByteSequence(marshalledBytes));
+      }
+
+      Integer redeliveryCounter = (Integer) coreMessage.getObjectProperty(AMQ_MSG_REDELIVER_COUNTER);
+      if (redeliveryCounter != null)
+      {
+         amqMsg.setRedeliveryCounter(redeliveryCounter);
+      }
+
+      byte[] replyToBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_REPLY_TO);
+      if (replyToBytes != null)
+      {
+         ActiveMQDestination replyTo = (ActiveMQDestination) marshaller.unmarshal(new ByteSequence(replyToBytes));
+         amqMsg.setReplyTo(replyTo);
+      }
+
+      byte[] consumerIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_CONSUMER_ID);
+      if (consumerIdBytes != null)
+      {
+         ConsumerId consumerId = (ConsumerId) marshaller.unmarshal(new ByteSequence(consumerIdBytes));
+         amqMsg.setTargetConsumerId(consumerId);
+      }
+
+      byte[] txIdBytes = (byte[]) coreMessage.getObjectProperty(AMQ_MSG_TX_ID);
+      if (txIdBytes != null)
+      {
+         TransactionId txId = (TransactionId) marshaller.unmarshal(new ByteSequence(txIdBytes));
+         amqMsg.setTransactionId(txId);
+      }
+
+      String userId = (String) coreMessage.getObjectProperty(AMQ_MSG_USER_ID);
+      if (userId != null)
+      {
+         amqMsg.setUserID(userId);
+      }
+
+      Boolean isCompressed = (Boolean) coreMessage.getObjectProperty(AMQ_MSG_COMPRESSED);
+      if (isCompressed != null)
+      {
+         amqMsg.setCompressed(isCompressed);
+      }
+      Boolean isDroppable = (Boolean) coreMessage.getObjectProperty(AMQ_MSG_DROPPABLE);
+      if (isDroppable != null)
+      {
+         amqMsg.setDroppable(isDroppable);
+      }
+
+      SimpleString dlqCause = (SimpleString) coreMessage.getObjectProperty(AMQ_MSG_DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY);
+      if (dlqCause != null)
+      {
+         try
+         {
+            amqMsg.setStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY, dlqCause.toString());
+         }
+         catch (JMSException e)
+         {
+            throw new IOException("failure to set dlq property " + dlqCause, e);
+         }
+      }
+      Set<SimpleString> props = coreMessage.getPropertyNames();
+      if (props != null)
+      {
+         for (SimpleString s : props)
+         {
+            String keyStr = s.toString();
+            if (keyStr.startsWith("__HQ") || keyStr.startsWith("__HDR_"))
+            {
+               continue;
+            }
+            Object prop = coreMessage.getObjectProperty(s);
+            try
+            {
+               if (prop instanceof SimpleString)
+               {
+                  amqMsg.setObjectProperty(s.toString(), prop.toString());
+               }
+               else
+               {
+                  amqMsg.setObjectProperty(s.toString(), prop);
+               }
+            }
+            catch (JMSException e)
+            {
+               throw new IOException("exception setting property " + s + " : " + prop, e);
+            }
+         }
+      }
+      return amqMsg;
+   }
+
+}


[48/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered/jndi.properties b/distribution/hornetq/src/main/resources/config/trunk/clustered/jndi.properties
deleted file mode 100644
index e2a9832..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered/jndi.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/clustered/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/clustered/logging.properties b/distribution/hornetq/src/main/resources/config/trunk/clustered/logging.properties
deleted file mode 100644
index dd49ead..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/clustered/logging.properties
+++ /dev/null
@@ -1,34 +0,0 @@
-############################################################
-#  	Default Logging Configuration File
-#
-# You can use a different file by specifying a filename
-# with the java.util.logging.config.file system property.
-# For example java -Djava.util.logging.config.file=myfile
-############################################################
-
-############################################################
-#  	Global properties
-############################################################
-
-# "handlers" specifies a comma separated list of log Handler
-# classes.  These handlers will be installed during VM startup.
-# Note that these classes must be on the system classpath.
-# By default we only configure a ConsoleHandler, which will only
-# show messages at the INFO and above levels.
-handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler
-java.util.logging.ConsoleHandler.formatter=org.hornetq.integration.logging.HornetQLoggerFormatter
-java.util.logging.FileHandler.level=INFO
-java.util.logging.FileHandler.pattern=logs/hornetq.log
-java.util.logging.FileHandler.formatter=org.hornetq.integration.logging.HornetQLoggerFormatter
-# Default global logging level.
-# This specifies which kinds of events are logged across
-# all loggers.  For any given facility this global level
-# can be overriden by a facility specific level
-# Note that the ConsoleHandler also has a separate level
-# setting to limit messages printed to the console.
-.level= INFO
-
-############################################################
-# Handler specific properties.
-# Describes specific configuration info for Handlers.
-############################################################

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-beans.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-beans.xml b/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-beans.xml
deleted file mode 100644
index 195019f..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-beans.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
-
-   <!-- JNDI server. Disable this if you don't want JNDI -->
-   <bean name="JNDIServer" class="org.jnp.server.Main">
-      <property name="namingInfo">
-         <inject bean="Naming"/>
-      </property>
-      <property name="port">1099</property>
-      <property name="bindAddress">localhost</property>
-      <property name="rmiPort">1098</property>
-      <property name="rmiBindAddress">localhost</property>
-   </bean>
-   
-   <!-- MBean server -->
-   <bean name="MBeanServer" class="javax.management.MBeanServer">
-      <constructor factoryClass="java.lang.management.ManagementFactory"
-                   factoryMethod="getPlatformMBeanServer"/>
-   </bean> 
-
-   <!-- The core configuration -->
-   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration">
-   </bean>
-
-	<!-- The security manager -->
-   <bean name="HornetQSecurityManager" class="org.hornetq.spi.core.security.HornetQSecurityManagerImpl">
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-
-	<!-- The core server -->
-   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
-      <constructor>
-         <parameter>
-            <inject bean="Configuration"/>
-         </parameter>
-         <parameter>
-            <inject bean="MBeanServer"/>
-         </parameter>
-         <parameter>
-            <inject bean="HornetQSecurityManager"/>
-         </parameter>        
-      </constructor>
-      <start ignored="true"/>
-      <stop ignored="true"/>
-   </bean>
-   
-   <!-- The JMS server -->
-   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
-      <constructor>         
-         <parameter>
-            <inject bean="HornetQServer"/>
-         </parameter>         
-      </constructor>
-   </bean>
-
-</deployment>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-configuration.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-configuration.xml b/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-configuration.xml
deleted file mode 100644
index d6788f3..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-configuration.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<configuration xmlns="urn:hornetq"
-	       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	       xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
-	
-	<journal-min-files>10</journal-min-files>
-	
-	<connectors>
-		<connector name="netty">
-			<factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-			<param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-			<param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-		</connector>
-		
-		<connector name="netty-throughput">
-            <factory-class>org.hornetq.core.remoting.impl.netty.NettyConnectorFactory</factory-class>
-            <param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-            <param key="port"  value="${hornetq.remoting.netty.port:5455}"/>
-            <param key="batch-delay" value="50"/>
-      </connector>
-	</connectors>
-	
-	<acceptors>
-		<acceptor name="netty">
-			<factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-			<param key="host"  value="${hornetq.remoting.netty.host:localhost}"/>
-			<param key="port"  value="${hornetq.remoting.netty.port:5445}"/>
-		</acceptor>
-		
-        <acceptor name="netty-throughput">
-            <factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory</factory-class>
-            <param key="host"  value="${jboss.bind.address:localhost}"/>
-            <param key="port"  value="${hornetq.remoting.netty.port:5455}"/>
-            <param key="batch-delay" value="50"/>
-            <param key="direct-deliver" value="false"/>
-        </acceptor>
-	</acceptors>
-	
-	<security-settings>
-		<security-setting match="#">
-			<permission type="createNonDurableQueue" roles="guest"/>
-			<permission type="deleteNonDurableQueue" roles="guest"/>
-			<permission type="consume" roles="guest"/>
-			<permission type="send" roles="guest"/>
-		</security-setting>
-	</security-settings>
-	
-    <address-settings>
-       <!--default for catch all-->
-       <address-setting match="#">
-          <dead-letter-address>jms.queue.DLQ</dead-letter-address>
-          <expiry-address>jms.queue.ExpiryQueue</expiry-address>
-          <redelivery-delay>0</redelivery-delay>
-          <max-size-bytes>10485760</max-size-bytes>       
-          <message-counter-history-day-limit>10</message-counter-history-day-limit>
-          <address-full-policy>BLOCK</address-full-policy>
-       </address-setting>
-    </address-settings>
-	
-</configuration>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-jms.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-jms.xml b/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-jms.xml
deleted file mode 100644
index 3a3dbeb..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-jms.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<configuration xmlns="urn:hornetq"
-	       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	       xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
-	
-	<connection-factory name="ConnectionFactory">
-	   <connectors>
-         <connector-ref connector-name="netty"/>
-	   </connectors>
-		<entries>
-			<entry name="/ConnectionFactory"/>
-			<entry name="/XAConnectionFactory"/>
-		</entries>
-	</connection-factory>
-	
-	<!--
-	<connection-factory name="NettyThroughputConnectionFactory">
-	   <connectors>
-         <connector-ref connector-name="netty-throughput"/>
-	   </connectors>
-		<entries>
-			<entry name="/ThroughputConnectionFactory"/>
-			<entry name="/XAThroughputConnectionFactory"/>
-		</entries>
-	</connection-factory>
-	-->
-	
-	<queue name="DLQ">
-		<entry name="/queue/DLQ"/>
-	</queue>
-	<queue name="ExpiryQueue">
-		<entry name="/queue/ExpiryQueue"/>
-	</queue>   
-	<queue name="ExampleQueue">
-		<entry name="/queue/ExampleQueue"/>
-	</queue>
-	<topic name="ExampleTopic">
-		<entry name="/topic/ExampleTopic"/>
-	</topic>
-	
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-users.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-users.xml b/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-users.xml
deleted file mode 100644
index 934306c..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/hornetq-users.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
-   <!-- the default user.  this is used where username is null-->
-   <defaultuser name="guest" password="guest">
-      <role name="guest"/>
-   </defaultuser>
-</configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/non-clustered/jndi.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/jndi.properties b/distribution/hornetq/src/main/resources/config/trunk/non-clustered/jndi.properties
deleted file mode 100644
index e2a9832..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/jndi.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
-java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/config/trunk/non-clustered/logging.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/logging.properties b/distribution/hornetq/src/main/resources/config/trunk/non-clustered/logging.properties
deleted file mode 100644
index 00f9c3d..0000000
--- a/distribution/hornetq/src/main/resources/config/trunk/non-clustered/logging.properties
+++ /dev/null
@@ -1,38 +0,0 @@
-############################################################
-#  	Default Logging Configuration File
-#
-# You can use a different file by specifying a filename
-# with the java.util.logging.config.file system property.
-# For example java -Djava.util.logging.config.file=myfile
-############################################################
-
-############################################################
-#  	Global properties
-############################################################
-
-# "handlers" specifies a comma separated list of log Handler
-# classes.  These handlers will be installed during VM startup.
-# Note that these classes must be on the system classpath.
-# By default we only configure a ConsoleHandler, which will only
-# show messages at the INFO and above levels.
-handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler
-java.util.logging.ConsoleHandler.formatter=org.hornetq.integration.logging.HornetQLoggerFormatter
-java.util.logging.FileHandler.level=INFO
-java.util.logging.FileHandler.formatter=org.hornetq.integration.logging.HornetQLoggerFormatter
-# cycle through 10 files of 20MiB max which append logs
-java.util.logging.FileHandler.count=10
-java.util.logging.FileHandler.limit=20971520
-java.util.logging.FileHandler.append=true
-java.util.logging.FileHandler.pattern=logs/hornetq.%g.log
-# Default global logging level.
-# This specifies which kinds of events are logged across
-# all loggers.  For any given facility this global level
-# can be overriden by a facility specific level
-# Note that the ConsoleHandler also has a separate level
-# setting to limit messages printed to the console.
-.level= INFO
-
-############################################################
-# Handler specific properties.
-# Describes specific configuration info for Handlers.
-############################################################

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/src/main/resources/examples/common/config/ant.properties
----------------------------------------------------------------------
diff --git a/distribution/hornetq/src/main/resources/examples/common/config/ant.properties b/distribution/hornetq/src/main/resources/examples/common/config/ant.properties
deleted file mode 100644
index 88ef1a7..0000000
--- a/distribution/hornetq/src/main/resources/examples/common/config/ant.properties
+++ /dev/null
@@ -1,4 +0,0 @@
-hornetq.example.logserveroutput=true
-hornetq.jars.dir=${imported.basedir}/../../lib
-jars.dir=${imported.basedir}/../../lib
-aio.library.path=${imported.basedir}/../../bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/jboss-mc/pom.xml
----------------------------------------------------------------------
diff --git a/distribution/jboss-mc/pom.xml b/distribution/jboss-mc/pom.xml
deleted file mode 100644
index 1a3fc0a..0000000
--- a/distribution/jboss-mc/pom.xml
+++ /dev/null
@@ -1,123 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-   <modelVersion>4.0.0</modelVersion>
-
-
-   <parent>
-      <groupId>org.hornetq</groupId>
-      <artifactId>hornetq-distribution</artifactId>
-      <version>2.5.0-SNAPSHOT</version>
-   </parent>
-
-   <artifactId>jboss-mc</artifactId>
-   <packaging>jar</packaging>
-   <name>JBoss Microcontainer jar</name>
-
-   <dependencies>
-      <!--<dependency>
-          <groupId>org.jboss.logging</groupId>
-          <artifactId>jboss-logging-spi</artifactId>
-      </dependency>-->
-      <dependency>
-          <groupId>org.jboss.microcontainer</groupId>
-          <artifactId>jboss-kernel</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.jboss.microcontainer</groupId>
-          <artifactId>jboss-dependency</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.jboss</groupId>
-          <artifactId>jboss-reflect</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.jboss</groupId>
-          <artifactId>jboss-common-core</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.jboss</groupId>
-          <artifactId>jboss-mdr</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.jboss</groupId>
-          <artifactId>jbossxb</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>sun-jaxb</groupId>
-          <artifactId>jaxb-api</artifactId>
-      </dependency>
-      <dependency>
-            <groupId>org.jboss.logging</groupId>
-            <artifactId>jboss-logging</artifactId>
-        </dependency>
-      <dependency>
-            <groupId>org.jboss.logmanager</groupId>
-            <artifactId>jboss-logmanager</artifactId>
-        </dependency>
-   </dependencies>
-
-   <build>
-      <resources>
-         <resource>
-            <directory>src/main/resources</directory>
-            <filtering>true</filtering>
-         </resource>
-      </resources>
-      <plugins>
-         <plugin>
-            <groupId>org.apache.maven.plugins</groupId>
-            <artifactId>maven-shade-plugin</artifactId>
-            <executions>
-               <execution>
-                  <phase>package</phase>
-                  <goals>
-                     <goal>shade</goal>
-                  </goals>
-                  <configuration>
-                     <artifactSet>
-                        <excludes>
-                           <exclude>org.jboss.netty:netty</exclude>
-                           <exclude>org.jboss.logging:jboss-logging-spi</exclude>
-                        </excludes>
-                     </artifactSet>
-                     <filters>
-                        <!--<filter>
-                           <artifact>org.jboss.logging:jboss-logging-spi</artifact>
-                        </filter>-->
-                        <filter>
-                           <artifact>org.jboss.microcontainer:jboss-kernel</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>org.jboss.microcontainer:jboss-dependency</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>org.jboss:jboss-reflect</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>org.jboss:jboss-common-core</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>org.jboss:jboss-mdr</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>org.jboss:jbossxb</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>sun-jaxb:jaxb-api</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>org.jboss.logging:jboss-logging</artifact>
-                        </filter>
-                        <filter>
-                           <artifact>org.jboss.logmanager:jboss-logmanager</artifact>
-                        </filter>
-                     </filters>
-                  </configuration>
-               </execution>
-
-            </executions>
-         </plugin>
-      </plugins>
-   </build>
-
-</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/pom.xml
----------------------------------------------------------------------
diff --git a/distribution/pom.xml b/distribution/pom.xml
index 498d761..538e685 100644
--- a/distribution/pom.xml
+++ b/distribution/pom.xml
@@ -34,7 +34,6 @@
 
    <modules>
       <module>jnp-client</module>
-      <module>jboss-mc</module>
       <module>hornetq</module>
    </modules>
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/quickstart-guide/en/running.xml
----------------------------------------------------------------------
diff --git a/docs/quickstart-guide/en/running.xml b/docs/quickstart-guide/en/running.xml
index 39f8797..de0ba4f 100644
--- a/docs/quickstart-guide/en/running.xml
+++ b/docs/quickstart-guide/en/running.xml
@@ -26,21 +26,21 @@
    <section id="running.standalone">
       <title>Standalone HornetQ</title>
       <para>To run a stand-alone server, open up a shell or command prompt and navigate into the
-            <literal>bin</literal> directory. Then execute <literal>./run.sh</literal> (or <literal
-            >run.bat</literal> on Windows) and you should see the following output </para>
+            <literal>bin</literal> directory. Then execute <literal>./hornetq run</literal> (or <literal
+            >./hornetq.cmd run</literal> on Windows) and you should see the following output </para>
       <programlisting>
-         bin$ ./run.sh
-         
-         15:05:54,108 INFO  @main [HornetQBootstrapServer] Starting HornetQ server
+         bin$ ./hornetq run
+
+         11:05:06,589 INFO  [org.hornetq.integration.bootstrap] HQ101000: Starting HornetQ Server
          ...
-         15:06:02,566 INFO  @main [HornetQServerImpl] HornetQ Server version 
-         2.0.0.CR3 (yellowjacket, 111) started
+         11:05:10,848 INFO  [org.hornetq.core.server] HQ221001: HornetQ Server version 2.5.0.SNAPSHOT (Wild Hornet, 125) [e32ae252-52ee-11e4-a716-7785dc3013a3]
       </programlisting>
       <para>HornetQ is now running.</para>
       <para>Both the run and the stop scripts use the config under <literal
-            >config/stand-alone/non-clustered</literal> by default. The configuration can be changed
-         by running <literal>./run.sh ../config/stand-alone/clustered</literal> or another config of
-         your choosing. This is the same for the stop script and the windows bat files.</para>
+            >config/non-clustered</literal> by default. The configuration can be changed
+         by running <literal>./hornetq run xml:../config/non-clustered/bootstrap.xml</literal> or another config of
+         your choosing.</para>
+      <para>The server can be stopped by running <literal>./hornetq stop</literal></para>
    </section>
    <section id="running.jboss.Wildfly">
       <title>HornetQ In Wildfly</title>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/HornetQ_User_Manual.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/HornetQ_User_Manual.xml b/docs/user-manual/en/HornetQ_User_Manual.xml
index 3ddf954..a726cfc 100644
--- a/docs/user-manual/en/HornetQ_User_Manual.xml
+++ b/docs/user-manual/en/HornetQ_User_Manual.xml
@@ -36,6 +36,7 @@
   <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="persistence.xml"/>
   <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="configuring-transports.xml"/>
   <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="connection-ttl.xml"/>
+  <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="slow-consumers.xml"/>
   <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="transaction-config.xml"/>
   <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="flow-control.xml"/>
   <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="send-guarantees.xml"/>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/clusters.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/clusters.xml b/docs/user-manual/en/clusters.xml
index 25e79b2..2dd1896 100644
--- a/docs/user-manual/en/clusters.xml
+++ b/docs/user-manual/en/clusters.xml
@@ -594,11 +594,13 @@ ClientSession session = factory.createSession();</programlisting>
                shows all the available configuration options</para>
             <itemizedlist>
                 <listitem id="clusters.address">
-                    <para><literal>address</literal>. Each cluster connection only applies to
-                        messages sent to an address that starts with this value. Note: this does
-                        not use wild-card matching.</para>
-                    <para>In this case, this cluster connection will load balance messages sent to
-                        address that start with <literal>jms</literal>. This cluster connection,
+                    <para><literal>address</literal> Each cluster connection only applies to addresses that match the
+                        specified address field.  An address is matched on the cluster connection when it begins with the
+                        string specified in this field.  The address field on a cluster connection also supports comma
+                        separated lists and an exclude syntax '!'.  To prevent an address from being matched on this
+                        cluster connection, prepend a cluster connection address string with '!'.</para>
+                    <para>In the case shown above the cluster connection will load balance messages sent to
+                        addresses that start with <literal>jms</literal>. This cluster connection,
                         will, in effect apply to all JMS queues and topics since they map to core
                         queues that start with the substring "jms".</para>
                     <para>The address can be any value and you can have many cluster connections
@@ -611,6 +613,24 @@ ClientSession session = factory.createSession();</programlisting>
                         values of <literal>address</literal>, e.g. "europe" and "europe.news" since
                         this could result in the same messages being distributed between more than
                         one cluster connection, possibly resulting in duplicate deliveries.</para>
+                   <para>
+                      Examples:
+                      <itemizedlist>
+                         <listitem><literal>'jms.eu'</literal> matches all addresses starting with 'jms.eu'</listitem>
+                         <listitem><literal>'!jms.eu'</literal>  matches all address except for those starting with
+                             'jms.eu'</listitem>
+                         <listitem><literal>'jms.eu.uk,jms.eu.de'</literal>  matches all addresses starting with either
+                             'jms.eu.uk' or 'jms.eu.de'</listitem>
+                         <listitem><literal>'jms.eu,!jms.eu.uk'</literal>  matches all addresses starting with 'jms.eu'
+                              but not those starting with 'jms.eu.uk'</listitem>
+                      </itemizedlist>
+                      Notes:
+                      <itemizedlist>
+                         <listitem>Address exclusion will always takes precedence over address inclusion.</listitem>
+                         <listitem>Address matching on cluster connections does not support wild-card matching.
+                         </listitem>
+                      </itemizedlist>
+                   </para>
                     <para>This parameter is mandatory.</para>
                 </listitem>
                 <listitem>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/configuring-transports.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/configuring-transports.xml b/docs/user-manual/en/configuring-transports.xml
index 066e783..d2f4143 100644
--- a/docs/user-manual/en/configuring-transports.xml
+++ b/docs/user-manual/en/configuring-transports.xml
@@ -177,10 +177,10 @@ etc</programlisting>
             Java IO, or NIO (non-blocking), also to use straightforward TCP sockets, SSL, or to
             tunnel over HTTP or HTTPS..</para>
         <para>We believe this caters for the vast majority of transport requirements.</para>
-        <section>
+        <section id="configuring-transports.single-port">
             <title>Single Port Support</title>
             <para>As of version 2.4 HornetQ now supports using a single port for all protocols, HornetQ will automatically
-            detect which protocol is being used CORE, AMQP or STOMP and use the appropriate HornetQ handler. It will also detect
+            detect which protocol is being used CORE, AMQP, STOMP or OPENWIRE and use the appropriate HornetQ handler. It will also detect
             whether protocols such as HTTP or Web Sockets are being used and also use the appropriate decoders</para>
             <para>It is possible to limit which protocols are supported by using the <literal>protocols</literal> parameter
             on the Acceptor like so:</para>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/core-bridges.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/core-bridges.xml b/docs/user-manual/en/core-bridges.xml
index 9004e7f..822510a 100644
--- a/docs/user-manual/en/core-bridges.xml
+++ b/docs/user-manual/en/core-bridges.xml
@@ -197,11 +197,13 @@
                     connection used to forward messages to the target node. This attribute is
                     described in section <xref linkend="client-reconnection"/></para>
 
-                 <warning><para>When using the bridge to forward messages from a queue which has a
-                    max-size-bytes set it's important that confirmation-window-size is less than
-                    or equal to <literal>max-size-bytes</literal> to prevent the flow of
-                    messages from ceasing.</para>
-                 </warning>
+                <warning><para>When using the bridge to forward messages to an address which uses
+                    the <literal>BLOCK</literal> <literal>address-full-policy</literal> from a
+                    queue which has a <literal>max-size-bytes</literal> set it's important that
+                    <literal>confirmation-window-size</literal> is less than or equal to
+                    <literal>max-size-bytes</literal> to prevent the flow of messages from
+                    ceasing.</para>
+                </warning>
 
             </listitem>
             <listitem>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/diagrams/ha-colocated.odg
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/diagrams/ha-colocated.odg b/docs/user-manual/en/diagrams/ha-colocated.odg
new file mode 100644
index 0000000..e464bb7
Binary files /dev/null and b/docs/user-manual/en/diagrams/ha-colocated.odg differ

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/diagrams/ha-scaledown.odg
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/diagrams/ha-scaledown.odg b/docs/user-manual/en/diagrams/ha-scaledown.odg
new file mode 100644
index 0000000..933829f
Binary files /dev/null and b/docs/user-manual/en/diagrams/ha-scaledown.odg differ

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/examples.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/examples.xml b/docs/user-manual/en/examples.xml
index cec4021..d202c89 100644
--- a/docs/user-manual/en/examples.xml
+++ b/docs/user-manual/en/examples.xml
@@ -401,6 +401,11 @@
                  sessions are used, once and only once message delivery is not guaranteed and it is possible
                  that some messages will be lost or delivered twice.</para>
         </section>
+        <section id="examples.openwire">
+            <title>OpenWire</title>
+            <para>The <literal>Openwire</literal> example shows how to configure a HornetQ
+            server to communicate with an ActiveMQ JMS client that uses open-wire protocol.</para>
+        </section>
         <section id="examples.paging">
             <title>Paging</title>
             <para>The <literal>paging</literal> example shows how HornetQ can support huge queues

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/ha.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/ha.xml b/docs/user-manual/en/ha.xml
index f4b2d2b..f6772f4 100644
--- a/docs/user-manual/en/ha.xml
+++ b/docs/user-manual/en/ha.xml
@@ -30,7 +30,6 @@
     <para>A part of high availability is <emphasis>failover</emphasis> which we define as the
        <emphasis>ability for client connections to migrate from one server to another in event of
           server failure so client applications can continue to operate</emphasis>.</para>
-
     <section>
         <title>Live - Backup Groups</title>
 
@@ -48,14 +47,71 @@
            live server goes down, if the current live server is configured to allow automatic failback
            then it will detect the live server coming back up and automatically stop.</para>
 
-        <section id="ha.mode">
-            <title>HA modes</title>
+        <section id="ha.policies">
+            <title>HA Policies</title>
             <para>HornetQ supports two different strategies for backing up a server <emphasis>shared
-               store</emphasis> and <emphasis>replication</emphasis>.</para>
+               store</emphasis> and <emphasis>replication</emphasis>. Which is configured via the
+               <literal>ha-policy</literal> configuration element.</para>
+           <programlisting>
+&lt;ha-policy>
+  &lt;replication/>
+&lt;/ha-policy>
+           </programlisting>
+           <para>
+              or
+           </para>
+           <programlisting>
+&lt;ha-policy>
+   &lt;shared-store/>
+&lt;/ha-policy>
+           </programlisting>
+           <para>
+              As well as these 2 strategies there is also a 3rd called <literal>live-only</literal>. This of course means there
+              will be no Backup Strategy and is the default if none is provided, however this is used to configure
+              <literal>scale-down</literal> which we will cover in a later chapter.
+           </para>
+           <note>
+              <para>
+                 The <literal>ha-policy</literal> configurations replaces any current HA configuration in the root of the
+                 <literal>hornetq-configuration.xml</literal> configuration. All old configuration is now deprecated altho
+                 best efforts will be made to honour it if configured this way.
+              </para>
+           </note>
             <note>
                 <para>Only persistent message data will survive failover. Any non persistent message
                    data will not be available after failover.</para>
             </note>
+           <para>The <literal>ha-policy</literal> type configures which strategy a cluster should use to provide the
+              backing up of a servers data. Within this configuration element is configured how a server should behave
+              within the cluster, either as a master (live), slave (backup) or colocated (both live and backup). This
+              would look something like: </para>
+           <programlisting>
+&lt;ha-policy>
+   &lt;replication>
+      &lt;master/>
+   &lt;/replication>
+&lt;/ha-policy>
+           </programlisting>
+           <para>
+              or
+           </para>
+           <programlisting>
+&lt;ha-policy>
+   &lt;shared-store/>
+      &lt;slave/>
+   &lt;/shared-store/>
+&lt;/ha-policy>
+           </programlisting>
+           <para>
+              or
+           </para>
+           <programlisting>
+&lt;ha-policy>
+   &lt;replication>
+      &lt;colocated/>
+   &lt;/replication>
+&lt;/ha-policy>
+           </programlisting>
         </section>
 
         <section id="ha.mode.replicated">
@@ -81,7 +137,7 @@
                the one at the live's storage. If you configure your live server to perform a
                <xref linkend="ha.allow-fail-back">'fail-back'</xref> when restarted, it will synchronize
                its data with the backup's. If both servers are shutdown, the administrator will have
-               to determine which one has the lastest data.</para>
+               to determine which one has the latest data.</para>
 
             <para>The replicating live and backup pair must be part of a cluster.  The Cluster
                Connection also defines how backup servers will find the remote live servers to pair
@@ -104,39 +160,40 @@
             <itemizedlist>
                 <listitem>
                     <para><literal>specifying a node group</literal>. You can specify a group of live servers that a backup
-                       server can connect to. This is done by configuring <literal>backup-group-name</literal> in the main
+                       server can connect to. This is done by configuring <literal>group-name</literal> in either the <literal>master</literal>
+                       or the <literal>slave</literal> element of the
                        <literal>hornetq-configuration.xml</literal>. A Backup server will only connect to a live server that
                        shares the same node group name</para>
                 </listitem>
                 <listitem>
-                   <para><literal>connecting to any live</literal>. Simply put not configuring <literal>backup-group-name</literal>
-                      will allow a backup server to connect to any live server</para>
+                   <para><literal>connecting to any live</literal>. This will be the behaviour if <literal>group-name</literal>
+                      is not configured allowing a backup server to connect to any live server</para>
                 </listitem>
             </itemizedlist>
             <note>
-                <para>A <literal>backup-group-name</literal> example: suppose you have 5 live servers and 6 backup
+                <para>A <literal>group-name</literal> example: suppose you have 5 live servers and 6 backup
                    servers:</para>
                 <itemizedlist>
                     <listitem>
                         <para><literal>live1</literal>, <literal>live2</literal>, <literal>live3</literal>: with
-                           <literal>backup-group-name=fish</literal></para>
+                           <literal>group-name=fish</literal></para>
                     </listitem>
                     <listitem>
-                       <para><literal>live4</literal>, <literal>live5</literal>: with <literal>backup-group-name=bird</literal></para>
+                       <para><literal>live4</literal>, <literal>live5</literal>: with <literal>group-name=bird</literal></para>
                     </listitem>
                     <listitem>
                        <para><literal>backup1</literal>, <literal>backup2</literal>, <literal>backup3</literal>,
-                          <literal>backup4</literal>: with <literal>backup-group-name=fish</literal></para>
+                          <literal>backup4</literal>: with <literal>group-name=fish</literal></para>
                     </listitem>
                     <listitem>
                        <para><literal>backup5</literal>, <literal>backup6</literal>: with
-                          <literal>backup-group-name=bird</literal></para>
+                          <literal>group-name=bird</literal></para>
                     </listitem>
                 </itemizedlist>
-                <para>After joining the cluster the backups with <literal>backup-group-name=fish</literal> will
-                   search for live servers with <literal>backup-group-name=fish</literal> to pair with. Since there
+                <para>After joining the cluster the backups with <literal>group-name=fish</literal> will
+                   search for live servers with <literal>group-name=fish</literal> to pair with. Since there
                    is one backup too many, the <literal>fish</literal> will remain with one spare backup.</para>
-                <para>The 2 backups with <literal>backup-group-name=bird</literal> (<literal>backup5</literal> and
+                <para>The 2 backups with <literal>group-name=bird</literal> (<literal>backup5</literal> and
                    <literal>backup6</literal>) will pair with live servers <literal>live4</literal> and
                    <literal>live5</literal>.</para>
             </note>
@@ -145,14 +202,14 @@
                configured. If no live server is available it will wait until the cluster topology changes and
                repeats the process.</para>
             <note>
-               <para>This is an important distinction from a shared-store backup, as in that case if
-                  the backup starts and does not find its live server, the server will just activate
-                  and start to serve client requests. In the replication case, the backup just keeps
-                  waiting for a live server to pair with. Notice that in replication the backup server
+               <para>This is an important distinction from a shared-store backup, if a backup starts and does not find
+                  a live server, the server will just activate and start to serve client requests.
+                  In the replication case, the backup just keeps
+                  waiting for a live server to pair with. Note that in replication the backup server
                   does not know whether any data it might have is up to date, so it really cannot
                   decide to activate automatically. To activate a replicating backup server using the data
-                  it has, the administrator must change its configuration to make a live server of it,
-                  that change <literal>backup=true</literal> to <literal>backup=false</literal>.</para>
+                  it has, the administrator must change its configuration to make it a live server by changing
+                  <literal>slave</literal> to <literal>master</literal>.</para>
             </note>
 
             <para>Much like in the shared-store case, when the live server stops or crashes,
@@ -169,12 +226,14 @@
                 <title>Configuration</title>
 
                 <para>To configure the live and backup servers to be a replicating pair, configure
-                   both servers' <literal>hornetq-configuration.xml</literal> to have:</para>
+                   the live server in ' <literal>hornetq-configuration.xml</literal> to have:</para>
 
                 <programlisting>
-&lt;!-- FOR BOTH LIVE AND BACKUP SERVERS' -->
-&lt;shared-store>false&lt;/shared-store>
-.
+&lt;ha-policy>
+   &lt;replication>
+      &lt;master/>
+   &lt;/replication>
+&lt;/ha-policy>
 .
 &lt;cluster-connections>
    &lt;cluster-connection name="my-cluster">
@@ -183,12 +242,95 @@
 &lt;/cluster-connections>
                 </programlisting>
 
-                <para>The backup server must also be configured as a backup.</para>
+                <para>The backup server must be similarly configured but as a <literal>slave</literal></para>
 
                 <programlisting>
-&lt;backup>true&lt;/backup>
-</programlisting>
+&lt;ha-policy>
+   &lt;replication>
+      &lt;slave/>
+   &lt;/replication>
+&lt;/ha-policy></programlisting>
             </section>
+           <section>
+              <title>All Replication Configuration</title>
+
+              <para>The following table lists all the <literal>ha-policy</literal> configuration elements for HA strategy
+                 Replication for <literal>master</literal>:</para>
+              <table>
+                 <tgroup cols="2">
+                    <colspec colname="c1" colnum="1"/>
+                    <colspec colname="c2" colnum="2"/>
+                    <thead>
+                       <row>
+                          <entry>name</entry>
+                          <entry>Description</entry>
+                       </row>
+                    </thead>
+                    <tbody>
+                       <row>
+                          <entry><literal>check-for-live-server</literal></entry>
+                          <entry>Whether to check the cluster for a (live) server using our own server ID when starting
+                             up. This option is only necessary for performing 'fail-back' on replicating servers.</entry>
+                       </row>
+                       <row>
+                          <entry><literal>cluster-name</literal></entry>
+                          <entry>Name of the cluster configuration to use for replication. This setting is only necessary if you
+                             configure multiple cluster connections. If configured then the connector configuration of the
+                             cluster configuration with this name will be used when connecting to the cluster to discover
+                          if a live server is already running, see <literal>check-for-live-server</literal>. If unset then
+                          the default cluster connections configuration is used (the first one configured)</entry>
+                       </row>
+                       <row>
+                          <entry><literal>group-name</literal></entry>
+                          <entry>If set, backup servers will only pair with live servers with matching group-name</entry>
+                       </row>
+                    </tbody>
+                 </tgroup>
+              </table>
+              <para>The following table lists all the <literal>ha-policy</literal> configuration elements for HA strategy
+                 Replication for <literal>slave</literal>:</para>
+              <table>
+                 <tgroup cols="2">
+                    <colspec colname="c1" colnum="1"/>
+                    <colspec colname="c2" colnum="2"/>
+                    <thead>
+                       <row>
+                          <entry>name</entry>
+                          <entry>Description</entry>
+                       </row>
+                    </thead>
+                    <tbody>
+                       <row>
+                          <entry><literal>cluster-name</literal></entry>
+                          <entry>Name of the cluster configuration to use for replication. This setting is only necessary if you
+                             configure multiple cluster connections. If configured then the connector configuration of the
+                             cluster configuration with this name will be used when connecting to the cluster to discover
+                             if a live server is already running, see <literal>check-for-live-server</literal>. If unset then
+                             the default cluster connections configuration is used (the first one configured)</entry>
+                       </row>
+                       <row>
+                          <entry><literal>group-name</literal></entry>
+                          <entry>If set, backup servers will only pair with live servers with matching group-name</entry>
+                       </row>
+                       <row>
+                          <entry><literal>max-saved-replicated-journals-size</literal></entry>
+                          <entry>This specifies how many times a replicated backup server can restart after moving its files on start.
+                             Once there are this number of backup journal files the server will stop permanently after if fails
+                             back.</entry>
+                       </row>
+                       <row>
+                          <entry><literal>allow-failback</literal></entry>
+                          <entry>Whether a server will automatically stop when a another places a request to take over
+                             its place. The use case is when the backup has failed over </entry>
+                       </row>
+                       <row>
+                          <entry><literal>failback-delay</literal></entry>
+                          <entry>delay to wait before fail-back occurs on (failed over live's) restart</entry>
+                       </row>
+                    </tbody>
+                 </tgroup>
+              </table>
+           </section>
         </section>
 
         <section id="ha.mode.shared">
@@ -213,20 +355,37 @@
                the shared store which can take some time depending on the amount of data in the
                store.</para>
             <para>If you require the highest performance during normal operation, have access to
-               a fast SAN, and can live with a slightly slower failover (depending on amount of
-               data), we recommend shared store high availability</para>
+               a fast SAN and live with a slightly slower failover (depending on amount of
+               data).</para>
             <graphic fileref="images/ha-shared-store.png" align="center"/>
 
             <section id="ha/mode.shared.configuration">
                 <title>Configuration</title>
                 <para>To configure the live and backup servers to share their store, configure
-                   all <literal>hornetq-configuration.xml</literal>:</para>
-                <programlisting>
-&lt;shared-store>true&lt;/shared-store>
-                </programlisting>
-                <para>Additionally, each backup server must be flagged explicitly as a backup:</para>
-                <programlisting>
-&lt;backup>true&lt;/backup></programlisting>
+                   id via the <literal>ha-policy</literal> configuration in <literal>hornetq-configuration.xml</literal>:</para>
+               <programlisting>
+&lt;ha-policy>
+   &lt;shared-store>
+      &lt;master/>
+   &lt;/shared-store>
+&lt;/ha-policy>
+.
+&lt;cluster-connections>
+   &lt;cluster-connection name="my-cluster">
+...
+   &lt;/cluster-connection>
+&lt;/cluster-connections>
+               </programlisting>
+
+               <para>The backup server must also be configured as a backup.</para>
+
+               <programlisting>
+&lt;ha-policy>
+   &lt;shared-store>
+      &lt;slave/>
+   &lt;/shared-store>
+&lt;/ha-policy>
+               </programlisting>
                 <para>In order for live - backup groups to operate properly with a shared store,
                    both servers must have configured the location of journal directory to point
                    to the <emphasis>same shared location</emphasis> (as explained in
@@ -244,14 +403,57 @@
             <title>Failing Back to live Server</title>
             <para>After a live server has failed and a backup taken has taken over its duties, you may want to
                restart the live server and have clients fail back.</para>
-            <para>In case of "shared disk", simply restart the original live
-               server and kill the new live server. You can do this by killing the process itself or just waiting for the server to crash naturally.</para>
-            <para>In case of a replicating live server that has been replaced by a remote backup you will need to also set <link linkend="hq.check-for-live-server">check-for-live-server</link>. This option is necessary because a starting server cannot know whether there is a (remote) server running in its place, so with this option set, the server will check the cluster for another server using its node-ID and if it finds one it will try initiate a fail-back. This option only applies to live servers that are restarting, it is ignored by backup servers.</para>
-            <para>It is also possible to cause failover to occur on normal server shutdown, to enable
-               this set the following property to true in the <literal>hornetq-configuration.xml</literal>
-               configuration file like so:</para>
+            <para>In case of "shared disk", simply restart the original live server and kill the new live server by can
+               do this by killing the process itself. Alternatively you can set <literal>allow-fail-back</literal> to
+               <literal>true</literal> on the slave config which will force the backup that has become live to automatically
+               stop. This configuration would look like:</para>
+           <programlisting>
+&lt;ha-policy>
+   &lt;shared-store>
+      &lt;slave>
+         &lt;allow-failback>true&lt;/allow-failback>
+         &lt;failback-delay>5000&lt;/failback-delay>
+      &lt;/slave>
+   &lt;/shared-store>
+&lt;/ha-policy>
+           </programlisting>
+           <para>The <literal>failback-delay</literal> configures how long the backup must wait after automatically
+              stopping before it restarts. This is to gives the live server time to start and obtain its lock.</para>
+           <para id="hq.check-for-live-server">In replication HA mode you need to set an extra property <literal>check-for-live-server</literal>
+              to <literal>true</literal> in the <literal>master</literal> configuration. If set to true, during start-up
+              a live server will first search the cluster for another server using its nodeID. If it finds one, it will
+              contact this server and try to "fail-back". Since this is a remote replication scenario, the "starting live"
+              will have to synchronize its data with the server running with its ID, once they are in sync, it will
+              request the other server (which it assumes it is a back that has assumed its duties) to shutdown for it to
+              take over. This is necessary because otherwise the live server has no means to know whether there was a
+              fail-over or not, and if there was if the server that took its duties is still running or not.
+              To configure this option at your <literal>hornetq-configuration.xml</literal> configuration file as follows:</para>
+           <programlisting>
+&lt;ha-policy>
+   &lt;replication>
+      &lt;master>
+         &lt;check-for-live-server>true&lt;/check-for-live-server>
+      &lt;master>
+   &lt;/replication>
+&lt;/ha-policy></programlisting>
+           <warning>
+              <para>
+                 Be aware that if you restart a live server while after failover has occurred then this value must be
+                 set to <literal><emphasis role="bold">true</emphasis></literal>. If not the live server will restart and server the same
+                 messages that the backup has already handled causing duplicates.
+              </para>
+           </warning>
+            <para>It is also possible, in the case of shared store, to cause failover to occur on normal server shutdown,
+               to enable this set the following property to true in the <literal>ha-policy</literal> configuration on either
+               the <literal>master</literal> or <literal>slave</literal> like so:</para>
             <programlisting>
-&lt;failover-on-shutdown>true&lt;/failover-on-shutdown></programlisting>
+&lt;ha-policy>
+   &lt;shared-store>
+      &lt;master>
+         &lt;failover-on-shutdown>true&lt;/failover-on-shutdown>
+      &lt;/master>
+   &lt;/shared-store>
+&lt;/ha-policy></programlisting>
             <para>By default this is set to false, if by some chance you have set this to false but still
                want to stop the server normally and cause failover then you can do this by using the management
                API as explained at <xref linkend="management.core.server"/></para>
@@ -259,39 +461,284 @@
                the original live server to take over automatically by setting the following property in the
                <literal>hornetq-configuration.xml</literal> configuration file as follows:</para>
             <programlisting>
-&lt;allow-failback>true&lt;/allow-failback></programlisting>
-            <para id="hq.check-for-live-server">In replication HA mode you need to set an extra property <literal>check-for-live-server</literal>
-               to <literal>true</literal>. If set to true, during start-up a live server will first search the cluster for another server using its nodeID. If it finds one, it will contact this server and try to "fail-back". Since this is a remote replication scenario, the "starting live" will have to synchronize its data with the server running with its ID, once they are in sync, it will request the other server (which it assumes it is a back that has assumed its duties) to shutdown for it to take over. This is necessary because otherwise the live server has no means to know whether there was a fail-over or not, and if there was if the server that took its duties is still running or not. To configure this option at your <literal>hornetq-configuration.xml</literal> configuration file as follows:</para>
-            <programlisting>
-&lt;check-for-live-server>true&lt;/check-for-live-server></programlisting>
+&lt;ha-policy>
+   &lt;shared-store>
+      &lt;slave>
+         &lt;allow-failback>true&lt;/allow-failback>
+      &lt;/slave>
+   &lt;/shared-store>
+&lt;/ha-policy></programlisting>
+
+           <section>
+              <title>All Shared Store Configuration</title>
+
+              <para>The following table lists all the <literal>ha-policy</literal> configuration elements for HA strategy
+                 shared store for <literal>master</literal>:</para>
+              <table>
+                 <tgroup cols="2">
+                    <colspec colname="c1" colnum="1"/>
+                    <colspec colname="c2" colnum="2"/>
+                    <thead>
+                       <row>
+                          <entry>name</entry>
+                          <entry>Description</entry>
+                       </row>
+                    </thead>
+                    <tbody>
+                       <row>
+                          <entry><literal>failback-delay</literal></entry>
+                          <entry>If a backup server is detected as being live, via the lock file, then the live server
+                          will wait announce itself as a backup and wait this amount of time (in ms) before starting as
+                          a live</entry>
+                       </row>
+                       <row>
+                          <entry><literal>failover-on-server-shutdown</literal></entry>
+                          <entry>If set to true then when this server is stopped normally the backup will become live
+                          assuming failover. If false then the backup server will remain passive. Note that if false you
+                             want failover to occur the you can use the the management API as explained at <xref linkend="management.core.server"/></entry>
+                       </row>
+                    </tbody>
+                 </tgroup>
+              </table>
+              <para>The following table lists all the <literal>ha-policy</literal> configuration elements for HA strategy
+                 Shared Store for <literal>slave</literal>:</para>
+              <table>
+                 <tgroup cols="2">
+                    <colspec colname="c1" colnum="1"/>
+                    <colspec colname="c2" colnum="2"/>
+                    <thead>
+                       <row>
+                          <entry>name</entry>
+                          <entry>Description</entry>
+                       </row>
+                    </thead>
+                    <tbody>
+                       <row>
+                          <entry><literal>failover-on-server-shutdown</literal></entry>
+                          <entry>In the case of a backup that has become live. then when set to true then when this server
+                             is stopped normally the backup will become liveassuming failover. If false then the backup
+                             server will remain passive. Note that if false you want failover to occur the you can use
+                             the the management API as explained at <xref linkend="management.core.server"/></entry>
+                       </row>
+                       <row>
+                          <entry><literal>allow-failback</literal></entry>
+                          <entry>Whether a server will automatically stop when a another places a request to take over
+                             its place. The use case is when the backup has failed over.</entry>
+                       </row>
+                       <row>
+                          <entry><literal>failback-delay</literal></entry>
+                          <entry>After failover and the slave has become live, this is set on the new live server.
+                             When starting If a backup server is detected as being live, via the lock file, then the live server
+                             will wait announce itself as a backup and wait this amount of time (in ms) before starting as
+                             a live, however this is unlikely since this backup has just stopped anyway. It is also used
+                          as the delay after failback before this backup will restart (if <literal>allow-failback</literal>
+                          is set to true.</entry>
+                       </row>
+                    </tbody>
+                 </tgroup>
+              </table>
+           </section>
+
         </section>
         <section id="ha.colocated">
             <title>Colocated Backup Servers</title>
             <para>It is also possible when running standalone to colocate backup servers in the same
-                JVM as another live server.The colocated backup will become a backup for another live
-                server in the cluster but not the one it shares the vm with. To configure a colocated
-                backup server simply add the following to the <literal>hornetq-configuration.xml</literal> file</para>
+                JVM as another live server. Live Servers can be configured to request another live server in the cluster
+                to start a backup server in the same JVM either using shared store or replication. The new backup server
+                will inherit its configuration from the live server creating it apart from its name, which will be set to
+                <literal>colocated_backup_n</literal> where n is the number of backups the server has created, and any directories
+                 and its Connectors and Acceptors which are discussed later on in this chapter. A live server can also
+                be configured to allow requests from backups and also how many backups a live server can start. this way
+                you can evenly distribute backups around the cluster. This is configured via the <literal>ha-policy</literal>
+                element in the <literal>hornetq-configuration.xml</literal> file like so:</para>
             <programlisting>
-&lt;backup-servers>
-    &lt;backup-server name="backup2" inherit-configuration="true" port-offset="1000">
-        &lt;configuration>
-            &lt;bindings-directory>target/server1/data/messaging/bindings&lt;/bindings-directory>
-            &lt;journal-directory>target/server1/data/messaging/journal&lt;/journal-directory>
-            &lt;large-messages-directory>target/server1/data/messaging/largemessages&lt;/large-messages-directory>
-            &lt;paging-directory>target/server1/data/messaging/paging&lt;/paging-directory>
-        &lt;/configuration>
-    &lt;/backup-server>
-&lt;/backup-servers>
+&lt;ha-policy>
+   &lt;replication>
+      &lt;colocated>
+         &lt;request-backup>true&lt;/request-backup>
+         &lt;max-backups>1&lt;/max-backups>
+         &lt;backup-request-retries>-1&lt;/backup-request-retries>
+         &lt;backup-request-retry-interval>5000&lt;/backup-request-retry-interval>
+         &lt;master/>
+         &lt;slave/>
+      &lt;/colocated>
+   &lt;replication>
+&lt;/ha-policy>
             </programlisting>
-            <para> you will notice 3 attributes on the <literal>backup-server</literal>, <literal>name</literal>
-                which is a unique name used to identify the backup server, <literal>inherit-configuration</literal>
-            which if set to true means the server will inherit the configuration of its parent server
-            and <literal>port-offset</literal> which is what the port for any netty connectors or
-            acceptors will be increased by if the configuration is inherited.</para>
-            <para>it is also possible to configure the backup server in the normal way, in this example you will
-            notice we have changed the journal directories.</para>
+            <para>the above example is configured to use replication, in this case the <literal>master</literal> and
+            <literal>slave</literal> configurations must match those for normal replication as in the previous chapter.
+            <literal>shared-store</literal> is also supported</para>
+
+           <graphic fileref="images/ha-colocated.png" align="center"/>
+           <section id="ha.colocated.connectorsandacceptors">
+              <title>Configuring Connectors and Acceptors</title>
+              <para>If the HA Policy is colocated then connectors and acceptors will be inherited from the live server
+                 creating it and offset depending on the setting of <literal>backup-port-offset</literal> configuration element.
+                 If this is set to say 100 (which is the default) and a connector is using port 5445 then this will be
+                 set to 5545 for the first server created, 5645 for the second and so on.</para>
+              <note><para>for INVM connectors and Acceptors the id will have <literal>colocated_backup_n</literal> appended,
+              where n is the backup server number.</para></note>
+              <section id="ha.colocated.connectorsandacceptors.remote">
+                 <title>Remote Connectors</title>
+                 <para>It may be that some of the Connectors configured are for external servers and hence should be excluded from the offset.
+                 for instance a Connector used by the cluster connection to do quorum voting for a replicated backup server,
+                  these can be omitted from being offset by adding them to the <literal>ha-policy</literal> configuration like so:</para>
+                 <programlisting>
+&lt;ha-policy>
+   &lt;replication>
+      &lt;colocated>
+         &lt;excludes>
+            &lt;connector-ref>remote-connector&lt;/connector-ref>
+         &lt;/excludes>
+.........
+&lt;/ha-policy>
+                 </programlisting>
+              </section>
+           </section>
+           <section id="ha.colocated.directories">
+              <title>Configuring Directories</title>
+              <para>Directories for the Journal, Large messages and Paging will be set according to what the HA strategy is.
+              If shared store the the requesting server will notify the target server of which directories to use. If replication
+              is configured then directories will be inherited from the creating server but have the new backups name
+              appended.</para>
+           </section>
+
+           <para>The following table lists all the <literal>ha-policy</literal> configuration elements:</para>
+           <table>
+              <tgroup cols="2">
+                 <colspec colname="c1" colnum="1"/>
+                 <colspec colname="c2" colnum="2"/>
+                 <thead>
+                    <row>
+                       <entry>name</entry>
+                       <entry>Description</entry>
+                    </row>
+                 </thead>
+                 <tbody>
+                    <row>
+                       <entry><literal>request-backup</literal></entry>
+                       <entry>If true then the server will request a backup on another node</entry>
+                    </row>
+                    <row>
+                       <entry><literal>backup-request-retries</literal></entry>
+                       <entry>How many times the live server will try to request a backup, -1 means for ever.</entry>
+                    </row>
+                    <row>
+                       <entry><literal>backup-request-retry-interval</literal></entry>
+                       <entry>How long to wait for retries between attempts to request a backup server.</entry>
+                    </row>
+                    <row>
+                       <entry><literal>max-backups</literal></entry>
+                       <entry>Whether or not this live server will accept backup requests from other live servers.</entry>
+                    </row>
+                    <row>
+                       <entry><literal>backup-port-offset</literal></entry>
+                       <entry>The offset to use for the Connectors and Acceptors when creating a new backup server.</entry>
+                    </row>
+                 </tbody>
+              </tgroup>
+           </table>
         </section>
     </section>
+   <section id="ha.scaledown">
+      <title>Scaling Down</title>
+      <para>An alternative to using Live/Backup groups is to configure scaledown. when configured for scale down a server
+      can copy all its messages and transaction state to another live server. The advantage of this is that you dont need
+      full backups to provide some form of HA, however there are disadvantages with this approach the first being that it
+         only deals with a server being stopped and not a server crash. The caveat here is if you configure a backup to scale down. </para>
+      <para>Another disadvantage is that it is possible to lose message ordering. This happens in the following scenario,
+      say you have 2 live servers and messages are distributed evenly between the servers from a single producer, if one
+         of the servers scales down then the messages sent back to the other server will be in the queue after the ones
+         already there, so server 1 could have messages 1,3,5,7,9 and server 2 would have 2,4,6,8,10, if server 2 scales
+         down the order in server 1 would be 1,3,5,7,9,2,4,6,8,10.</para>
+      <graphic fileref="images/ha-scaledown.png" align="center"/>
+      <para>The configuration for a live server to scale down would be something like:</para>
+      <programlisting>
+&lt;ha-policy>
+   &lt;live-only>
+      &lt;scale-down>
+         &lt;connectors>
+            &lt;connector-ref>server1-connector&lt;/connector-ref>
+         &lt;/connectors>
+      &lt;/scale-down>
+   &lt;/live-only>
+&lt;/ha-policy>
+      </programlisting>
+      <para>In this instance the server is configured to use a specific connector to scale down, if a connector is not
+         specified then the first INVM connector is chosen, this is to make scale down fromm a backup server easy to configure.
+         It is also possible to use discovery to scale down, this would look like:</para>
+      <programlisting>
+&lt;ha-policy>
+   &lt;live-only>
+      &lt;scale-down>
+         &lt;discovery-group>my-discovery-group&lt;/discovery-group>
+      &lt;/scale-down>
+   &lt;/live-only>
+&lt;/ha-policy>
+      </programlisting>
+      <section id="ha.scaledown.group">
+         <title>Scale Down with groups</title>
+         <para>It is also possible to configure servers to only scale down to servers that belong in the same group. This
+         is done by configuring the group like so:</para>
+         <programlisting>
+&lt;ha-policy>
+   &lt;live-only>
+      &lt;scale-down>
+         ...
+         &lt;group-name>my-group&lt;/group-name>
+      &lt;/scale-down>
+   &lt;/live-only>
+&lt;/ha-policy>
+         </programlisting>
+         <para>In this scenario only servers that belong to the group <literal>my-group</literal> will be scaled down to</para>
+      </section>
+      <section>
+         <title>Scale Down and Backups</title>
+         <para>It is also possible to mix scale down with HA via backup servers. If a slave is configured to scale down
+         then after failover has occurred, instead of starting fully the backup server will immediately scale down to
+         another live server. The most appropriate configuration for this is using the <literal>colocated</literal> approach.
+         it means as you bring up live server they will automatically be backed up by server and as live servers are
+         shutdown, there messages are made available on another live server. A typical configuration would look like:</para>
+         <programlisting>
+&lt;ha-policy>
+   &lt;replication>
+      &lt;colocated>
+         &lt;backup-request-retries>44&lt;/backup-request-retries>
+         &lt;backup-request-retry-interval>33&lt;/backup-request-retry-interval>
+         &lt;max-backups>3&lt;/max-backups>
+         &lt;request-backup>false&lt;/request-backup>
+         &lt;backup-port-offset>33&lt;/backup-port-offset>
+         &lt;master>
+            &lt;group-name>purple&lt;/group-name>
+            &lt;check-for-live-server>true&lt;/check-for-live-server>
+            &lt;cluster-name>abcdefg&lt;/cluster-name>
+         &lt;/master>
+         &lt;slave>
+            &lt;group-name>tiddles&lt;/group-name>
+            &lt;max-saved-replicated-journals-size>22&lt;/max-saved-replicated-journals-size>
+            &lt;cluster-name>33rrrrr&lt;/cluster-name>
+            &lt;restart-backup>false&lt;/restart-backup>
+            &lt;scale-down>
+               &lt;!--a grouping of servers that can be scaled down to-->
+               &lt;group-name>boo!&lt;/group-name>
+               &lt;!--either a discovery group-->
+               &lt;discovery-group>wahey&lt;/discovery-group>
+            &lt;/scale-down>
+         &lt;/slave>
+      &lt;/colocated>
+   &lt;/replication>
+&lt;/ha-policy>
+         </programlisting>
+      </section>
+   <section id="ha.scaledown.client">
+      <title>Scale Down and Clients</title>
+      <para>When a server is stopping and preparing to scale down it will send a message to all its clients informing them
+      which server it is scaling down to before disconnecting them. At this point the client will reconnect however this
+      will only succeed once the server has completed scaledown. This is to ensure that any state such as queues or transactions
+      are there for the client when it reconnects. The normal reconnect settings apply when the client is reconnecting so
+      these should be high enough to deal with the time needed to scale down.</para>
+      </section>
+   </section>
     <section id="failover">
         <title>Failover Modes</title>
         <para>HornetQ defines two types of client failover:</para>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/images/ha-colocated.png
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/images/ha-colocated.png b/docs/user-manual/en/images/ha-colocated.png
new file mode 100644
index 0000000..e7b2d30
Binary files /dev/null and b/docs/user-manual/en/images/ha-colocated.png differ

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/images/ha-scaledown.png
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/images/ha-scaledown.png b/docs/user-manual/en/images/ha-scaledown.png
new file mode 100644
index 0000000..b33f5ce
Binary files /dev/null and b/docs/user-manual/en/images/ha-scaledown.png differ

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/interoperability.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/interoperability.xml b/docs/user-manual/en/interoperability.xml
index e4261d7..68e2962 100644
--- a/docs/user-manual/en/interoperability.xml
+++ b/docs/user-manual/en/interoperability.xml
@@ -285,4 +285,23 @@ java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces</programlisting
                 however in this version HornetQ will only support single transactions per session</para></note>
         </section>
     </section>
+    <section>
+        <title>OpenWire</title>
+        <para>HornetQ now supports the <ulink url="http://activemq.apache.org/openwire.html">OpenWire</ulink>
+        protocol so that an ActiveMQ JMS client can talk directly to a HornetQ server. To enable OpenWire support
+        you must configure a Netty Acceptor, like so:</para>
+        <programlisting>
+&lt;acceptor name="openwire-acceptor">
+&lt;factory-class>org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory&lt;/factory-class>
+&lt;param key="protocols"  value="OPENWIRE"/>
+&lt;param key="port"  value="61616"/>
+&lt;/acceptor>
+        </programlisting>
+        <para>The HornetQ server will then listens on port 61616 for incoming openwire commands. Please note the "protocols" is not mandatory here. 
+        The openwire configuration conforms to HornetQ's "Single Port" feature. Please refer to 
+        <link linkend="configuring-transports.single-port">Configuring Single Port</link> for details.</para>
+        <para>Please refer to the openwire example for more coding details.</para>
+        <para>Currently we support ActiveMQ clients that using standard JMS APIs. In the future we will get more supports
+        for some advanced, ActiveMQ specific features into HornetQ.</para>
+    </section>
 </chapter>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/management.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/management.xml b/docs/user-manual/en/management.xml
index be5cd32..c8ec3a3 100644
--- a/docs/user-manual/en/management.xml
+++ b/docs/user-manual/en/management.xml
@@ -148,15 +148,16 @@
                         >core.server</literal>).</para>
                </listitem>
                <listitem>
-                   <para>It is possible to stop the server and force failover to occur with any currently attached clients.</para>
-                   <para>to do this use the <literal>forceFailover()</literal> on the <literal
+                  <para>It is possible to stop the server and force failover to occur with any currently attached clients.</para>
+                  <para>to do this use the <literal>forceFailover()</literal> on the <literal
                         >HornetQServerControl</literal> (with the ObjectName <literal
                         >org.hornetq:module=Core,type=Server</literal> or the resource name <literal
                         >core.server</literal>) </para>
-                   <para>
-                       <note>Since this method actually stops the server you will probably receive some sort of error
-                       depending on which management service you use to call it.</note>
-                   </para>
+                  <note>
+                     <para>Since this method actually stops the server you will probably receive some sort of error
+                        depending on which management service you use to call it.
+                     </para>
+                  </note>
                </listitem>
             </itemizedlist>
          </section>
@@ -834,7 +835,7 @@ notificationConsumer.setMessageListener(new MessageListener()
                how to use a JMS <literal>MessageListener</literal> to receive management notifications
                from HornetQ server.</para>
        </section>
-       <section>
+       <section id="notification.types.and.headers">
            <title>Notification Types and Headers</title>
            <para>Below is a list of all the different kinds of notifications as well as which headers are
                 on the messages.  Every notification has a <literal>_HQ_NotifType</literal> (value noted in parentheses)
@@ -966,6 +967,14 @@ notificationConsumer.setMessageListener(new MessageListener()
                        <literal>_HQ_Address</literal>, <literal>_HQ_Distance</literal></para>
                </listitem>
            </itemizedlist>
+           <itemizedlist>
+               <listitem>
+                   <para><literal>CONSUMER_SLOW</literal> (21)</para>
+                   <para><literal>_HQ_Address</literal>, <literal>_HQ_ConsumerCount</literal>,
+                       <literal>_HQ_RemoteAddress</literal>, <literal>_HQ_ConnectionName</literal>,
+                       <literal>_HQ_ConsumerName</literal>, <literal>_HQ_SessionName</literal></para>
+                </listitem>
+           </itemizedlist>
        </section>
    </section>
    <section id="management.message-counters">

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/queue-attributes.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/queue-attributes.xml b/docs/user-manual/en/queue-attributes.xml
index 8ec06b5..f9b2fd8 100644
--- a/docs/user-manual/en/queue-attributes.xml
+++ b/docs/user-manual/en/queue-attributes.xml
@@ -109,6 +109,9 @@
       &lt;redistribution-delay>0&lt;/redistribution-delay>
       &lt;send-to-dla-on-no-route>true&lt;/send-to-dla-on-no-route>
       &lt;address-full-policy>PAGE&lt;/address-full-policy>
+      &lt;slow-consumer-threshold>-1&lt;/slow-consumer-threshold>
+      &lt;slow-consumer-policy>NOTIFY&lt;/slow-consumer-policy>
+      &lt;slow-consumer-check-period>5&lt;/slow-consumer-check-period>
    &lt;/address-setting>
 &lt;/address-settings></programlisting>
         <para>The idea with address settings, is you can provide a block of settings which will be
@@ -154,7 +157,16 @@
         
         See the following chapters for more info <xref linkend="flow-control"/>, <xref linkend="paging"/>.
         </para>
-        
-   
+       <para><literal>slow-consumer-threshold</literal>. The minimum rate of message consumption allowed before a
+          consumer is considered "slow." Measured in messages-per-second. Default is -1 (i.e. disabled); any other valid
+          value must be greater than 0.</para>
+       <para><literal>slow-consumer-policy</literal>. What should happen when a slow consumer is detected.
+          <literal>KILL</literal> will kill the consumer's connection (which will obviously impact any other client
+          threads using that same connection). <literal>NOTIFY</literal> will send a CONSUMER_SLOW management
+          notification which an application could receive and take action with. See
+          <xref linkend="notification.types.and.headers"/> for more details on this notification.</para>
+       <para><literal>slow-consumer-check-period</literal>. How often to check for slow consumers on a particular queue.
+          Measured in minutes. Default is 5. See <xref linkend="slow-consumers"/> for more information about slow
+          consumer detection.</para>
     </section>
 </chapter>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/docs/user-manual/en/slow-consumers.xml
----------------------------------------------------------------------
diff --git a/docs/user-manual/en/slow-consumers.xml b/docs/user-manual/en/slow-consumers.xml
new file mode 100644
index 0000000..aef287d
--- /dev/null
+++ b/docs/user-manual/en/slow-consumers.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- ============================================================================= -->
+<!-- Copyright © 2009 Red Hat, Inc. and others.                                    -->
+<!--                                                                               -->
+<!-- The text of and illustrations in this document are licensed by Red Hat under  -->
+<!-- a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). -->
+<!--                                                                               -->
+<!-- An explanation of CC-BY-SA is available at                                    -->
+<!--                                                                               -->
+<!--            http://creativecommons.org/licenses/by-sa/3.0/.                    -->
+<!--                                                                               -->
+<!-- In accordance with CC-BY-SA, if you distribute this document or an adaptation -->
+<!-- of it, you must provide the URL for the original version.                     -->
+<!--                                                                               -->
+<!-- Red Hat, as the licensor of this document, waives the right to enforce,       -->
+<!-- and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent        -->
+<!-- permitted by applicable law.                                                  -->
+<!-- ============================================================================= -->
+
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+<!ENTITY % BOOK_ENTITIES SYSTEM "HornetQ_User_Manual.ent">
+%BOOK_ENTITIES;
+]>
+<chapter id="slow-consumers">
+   <title>Detecting Slow Consumers</title>
+   <para>In this section we will discuss how HornetQ can be configured to deal with slow consumers. A slow consumer with
+      a server-side queue (e.g. JMS topic subscriber) can pose a significant problem for broker performance. If messages
+      build up in the consumer's server-side queue then memory will begin filling up and the broker may enter paging
+      mode which would impact performance negatively. However, criteria can be set so that consumers which don't
+      acknowledge messages quickly enough can potentially be disconnected from the broker which in the case of a
+      non-durable JMS subscriber would allow the broker to remove the subscription and all of its messages freeing up
+      valuable server resources.
+   </para>
+   <section id="slow.consumer.configuration">
+      <title>Configuration required for detecting slow consumers</title>
+      <para>By default the server will not detect slow consumers. If slow consumer detection is desired then see
+      <xref linkend="queue-attributes.address-settings"/>
+         for more details.
+      </para>
+      <para>The calculation to determine whether or not a consumer is slow only inspects the number of messages a
+         particular consumer has <emphasis>acknowledged</emphasis>. It doesn't take into account whether or not flow
+         control has been enabled on the consumer, whether or not the consumer is streaming a large message, etc. Keep
+         this in mind when configuring slow consumer detection.
+      </para>
+      <para>Please note that slow consumer checks are performed using the scheduled thread pool and that each queue on
+         the broker with slow consumer detection enabled will cause a new entry in the internal
+         <literal>java.util.concurrent.ScheduledThreadPoolExecutor</literal> instance. If there are a high number of
+         queues and the <literal>slow-consumer-check-period</literal> is relatively low then there may be delays in
+         executing some of the checks. However, this will not impact the accuracy of the calculations used by the
+         detection algorithm. See <xref linkend="server.scheduled.thread.pool"/> for more details about this pool.
+      </para>
+   </section>
+</chapter>


[07/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/IsolatedTopologyTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/IsolatedTopologyTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/IsolatedTopologyTest.java
index 5b99685..ebbe331 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/IsolatedTopologyTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/IsolatedTopologyTest.java
@@ -106,11 +106,6 @@ public class IsolatedTopologyTest extends ServiceTestBase
 
    private HornetQServer createServer1() throws Exception
    {
-      // Server1 with two acceptors, each acceptor on a different cluster connection
-      // talking to a different connector.
-      // i.e. two cluster connections isolated on the same node
-      Configuration config1 = createBasicConfig(0);
-
       Map<String, Object> params = new HashMap<String, Object>();
       params.put(TransportConstants.CLUSTER_CONNECTION, "cc1");
       params.put(org.hornetq.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, "1");
@@ -118,13 +113,6 @@ public class IsolatedTopologyTest extends ServiceTestBase
       TransportConfiguration acceptor1VM1 = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY,
                                                                        params,
                                                                        "acceptor-cc1");
-      config1.getAcceptorConfigurations().add(acceptor1VM1);
-
-      config1.getConnectorConfigurations().put("local-cc1", createInVMTransportConnectorConfig(1, "local-cc1"));
-      config1.getConnectorConfigurations().put("local-cc2", createInVMTransportConnectorConfig(2, "local-cc2"));
-
-      config1.getConnectorConfigurations().put("other-cc1", createInVMTransportConnectorConfig(3, "other-cc1"));
-      config1.getConnectorConfigurations().put("other-cc2", createInVMTransportConnectorConfig(4, "other-cc2"));
 
       params = new HashMap<String, Object>();
       params.put(TransportConstants.CLUSTER_CONNECTION, "cc2");
@@ -133,46 +121,47 @@ public class IsolatedTopologyTest extends ServiceTestBase
       TransportConfiguration acceptor2VM1 = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY,
                                                                        params,
                                                                        "acceptor-cc2");
-      config1.getAcceptorConfigurations().add(acceptor2VM1);
 
       List<String> connectTo = new ArrayList<String>();
       connectTo.add("other-cc1");
 
-      ClusterConnectionConfiguration server1CC1 =
-         new ClusterConnectionConfiguration("cc1", "jms", "local-cc1",
-                                            250,
-                                            true,
-                                            false,
-                                            1,
-                                            1024,
-                                            connectTo,
-                                            false);
-
-      config1.getClusterConfigurations().add(server1CC1);
+      ClusterConnectionConfiguration server1CC1 = new ClusterConnectionConfiguration()
+         .setName("cc1")
+         .setAddress("jms")
+         .setConnectorName("local-cc1")
+         .setRetryInterval(250)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(connectTo);
 
       ArrayList<String> connectTo2 = new ArrayList<String>();
       connectTo2.add("other-cc2");
 
-      ClusterConnectionConfiguration server1CC2 =
-         new ClusterConnectionConfiguration("cc2", "jms", "local-cc2", 250,
-                                            true,
-                                            false,
-                                            1,
-                                            1024,
-                                            connectTo2,
-                                            false);
+      ClusterConnectionConfiguration server1CC2 = new ClusterConnectionConfiguration()
+         .setName("cc2")
+         .setAddress("jms")
+         .setConnectorName("local-cc2")
+         .setRetryInterval(250)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(connectTo2);
 
-      config1.getClusterConfigurations().add(server1CC2);
+      // Server1 with two acceptors, each acceptor on a different cluster connection
+      // talking to a different connector.
+      // i.e. two cluster connections isolated on the same node
+      Configuration config1 = createBasicConfig(0)
+         .addConnectorConfiguration("local-cc1", createInVMTransportConnectorConfig(1, "local-cc1"))
+         .addConnectorConfiguration("local-cc2", createInVMTransportConnectorConfig(2, "local-cc2"))
+         .addConnectorConfiguration("other-cc1", createInVMTransportConnectorConfig(3, "other-cc1"))
+         .addConnectorConfiguration("other-cc2", createInVMTransportConnectorConfig(4, "other-cc2"))
+         .addAcceptorConfiguration(acceptor1VM1)
+         .addAcceptorConfiguration(acceptor2VM1)
+         .addClusterConfiguration(server1CC1)
+         .addClusterConfiguration(server1CC2);
 
       return createServer(false, config1);
    }
 
    private HornetQServer createServer2() throws Exception
    {
-      // Server1 with two acceptors, each acceptor on a different cluster connection
-      // talking to a different connector.
-      // i.e. two cluster connections isolated on the same node
-      Configuration config1 = createBasicConfig(3);
 
       Map<String, Object> params = new HashMap<String, Object>();
       params.put(TransportConstants.CLUSTER_CONNECTION, "cc1");
@@ -181,13 +170,6 @@ public class IsolatedTopologyTest extends ServiceTestBase
       TransportConfiguration acceptor1VM1 = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY,
                                                                        params,
                                                                        "acceptor-cc1");
-      config1.getAcceptorConfigurations().add(acceptor1VM1);
-
-      config1.getConnectorConfigurations().put("local-cc1", createInVMTransportConnectorConfig(3, "local-cc1"));
-      config1.getConnectorConfigurations().put("local-cc2", createInVMTransportConnectorConfig(4, "local-cc2"));
-
-      config1.getConnectorConfigurations().put("other-cc1", createInVMTransportConnectorConfig(1, "other-cc1"));
-      config1.getConnectorConfigurations().put("other-cc2", createInVMTransportConnectorConfig(2, "other-cc2"));
 
       params = new HashMap<String, Object>();
       params.put(TransportConstants.CLUSTER_CONNECTION, "cc2");
@@ -196,25 +178,41 @@ public class IsolatedTopologyTest extends ServiceTestBase
       TransportConfiguration acceptor2VM1 = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY,
                                                                        params,
                                                                        "acceptor-cc2");
-      config1.getAcceptorConfigurations().add(acceptor2VM1);
 
       List<String> connectTo = new ArrayList<String>();
       connectTo.add("other-cc1");
 
-      ClusterConnectionConfiguration server1CC1 =
-         new ClusterConnectionConfiguration("cc1", "jms", "local-cc1", 250, true, false, 1, 1024, connectTo,
-                                            false);
+      ClusterConnectionConfiguration server1CC1 = new ClusterConnectionConfiguration()
+         .setName("cc1")
+         .setAddress("jms")
+         .setConnectorName("local-cc1")
+         .setRetryInterval(250)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(connectTo);
 
-      config1.getClusterConfigurations().add(server1CC1);
-
-      ArrayList<String> connectTo2 = new ArrayList<String>();
+      List<String> connectTo2 = new ArrayList<String>();
       connectTo2.add("other-cc2");
 
-      ClusterConnectionConfiguration server1CC2 =
-         new ClusterConnectionConfiguration("cc2", "jms", "local-cc2", 250, true, false, 1, 1024, connectTo2,
-                                            false);
+      ClusterConnectionConfiguration server1CC2 = new ClusterConnectionConfiguration()
+         .setName("cc2")
+         .setAddress("jms")
+         .setConnectorName("local-cc2")
+         .setRetryInterval(250)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(connectTo2);
 
-      config1.getClusterConfigurations().add(server1CC2);
+      // Server1 with two acceptors, each acceptor on a different cluster connection
+      // talking to a different connector.
+      // i.e. two cluster connections isolated on the same node
+      Configuration config1 = createBasicConfig(3)
+         .addAcceptorConfiguration(acceptor1VM1)
+         .addAcceptorConfiguration(acceptor2VM1)
+         .addConnectorConfiguration("local-cc1", createInVMTransportConnectorConfig(3, "local-cc1"))
+         .addConnectorConfiguration("local-cc2", createInVMTransportConnectorConfig(4, "local-cc2"))
+         .addConnectorConfiguration("other-cc1", createInVMTransportConnectorConfig(1, "other-cc1"))
+         .addConnectorConfiguration("other-cc2", createInVMTransportConnectorConfig(2, "other-cc2"))
+         .addClusterConfiguration(server1CC1)
+         .addClusterConfiguration(server1CC2);
 
       return createServer(false, config1);
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/NonHATopologyTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/NonHATopologyTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/NonHATopologyTest.java
index 41beedb..57acb40 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/NonHATopologyTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/topology/NonHATopologyTest.java
@@ -76,9 +76,14 @@ public class NonHATopologyTest extends ServiceTestBase
             ArrayList<String> list = new ArrayList<String>();
             list.add("netty");
             Configuration config = server.getConfiguration();
-            config.getClusterConfigurations().add(new ClusterConnectionConfiguration("tst", "jms", "netty", 1000, true,
-                                                                                     false, 1, 1000, list, true));
-
+            config.getClusterConfigurations().add(new ClusterConnectionConfiguration()
+               .setName("tst")
+               .setAddress("jms")
+               .setConnectorName("netty")
+               .setRetryInterval(1000)
+               .setConfirmationWindowSize(1000)
+               .setStaticConnectors(list)
+               .setAllowDirectConnectionsOnly(true));
          }
 
          server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/BackupSyncDelay.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/BackupSyncDelay.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/BackupSyncDelay.java
index 60e8cb0..d3f51f9 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/BackupSyncDelay.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/BackupSyncDelay.java
@@ -29,6 +29,7 @@ import org.hornetq.core.protocol.core.impl.wireformat.ReplicationResponseMessage
 import org.hornetq.core.protocol.core.impl.wireformat.ReplicationStartSyncMessage;
 import org.hornetq.core.replication.ReplicationEndpoint;
 import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.impl.SharedNothingBackupActivation;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 
 /**
@@ -75,8 +76,6 @@ public class BackupSyncDelay implements Interceptor
     */
    public BackupSyncDelay(HornetQServer backup, HornetQServer live, byte packetCode)
    {
-      assert backup.getConfiguration().getHAPolicy().isBackup();
-      assert !live.getConfiguration().getHAPolicy().isBackup();
       this.backup = backup;
       this.live = live;
       live.getRemotingService().addIncomingInterceptor(this);
@@ -99,7 +98,8 @@ public class BackupSyncDelay implements Interceptor
       {
          try
          {
-            ReplicationEndpoint repEnd = backup.getReplicationEndpoint();
+            SharedNothingBackupActivation activation = (SharedNothingBackupActivation) backup.getActivation();
+            ReplicationEndpoint repEnd = activation.getReplicationEndpoint();
             handler.addSubHandler(repEnd);
             Channel repChannel = repEnd.getChannel();
             repChannel.setHandler(handler);
@@ -313,6 +313,12 @@ public class BackupSyncDelay implements Interceptor
       }
 
       @Override
+      public void returnBlocking(Throwable cause)
+      {
+         throw new UnsupportedOperationException();
+      }
+
+      @Override
       public Lock getLock()
       {
          throw new UnsupportedOperationException();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/MultiServerTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/MultiServerTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/MultiServerTestBase.java
index 7cd0595..8b2ee1d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/MultiServerTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/util/MultiServerTestBase.java
@@ -11,7 +11,10 @@
  * permissions and limitations under the License.
  */
 package org.hornetq.tests.integration.cluster.util;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.junit.Before;
 
 import java.util.ArrayList;
@@ -175,33 +178,21 @@ public class MultiServerTestBase extends ServiceTestBase
                                                               final boolean sharedStorage) throws Exception
    {
       NodeManager nodeManager = null;
+      TransportConfiguration serverConfigAcceptor = createTransportConfiguration(useNetty(), true, generateParams(node, useNetty()));
+      TransportConfiguration thisConnector = createTransportConfiguration(useNetty(), false, generateParams(node, useNetty()));
 
       if (sharedStorage)
       {
          nodeManager = new InVMNodeManager(false);
       }
 
-      Configuration configuration = createBasicConfig(node);
-
-      configuration.setJournalMaxIO_AIO(1000);
-
-      if (sharedStorage)
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      else
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.REPLICATED);
-
-      configuration.setThreadPoolMaxSize(10);
-
-      configuration.getAcceptorConfigurations().clear();
-
-      TransportConfiguration serverConfigAcceptor = createTransportConfiguration(useNetty(), true,
-                                                                                 generateParams(node, useNetty()));
-      configuration.getAcceptorConfigurations().add(serverConfigAcceptor);
-
-
-      TransportConfiguration thisConnector = createTransportConfiguration(useNetty(), false, generateParams(node, useNetty()));
-
-      configuration.getConnectorConfigurations().put("thisConnector", thisConnector);
+      Configuration configuration = createBasicConfig(node)
+         .setJournalMaxIO_AIO(1000)
+         .setThreadPoolMaxSize(10)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(serverConfigAcceptor)
+         .addConnectorConfiguration("thisConnector", thisConnector)
+         .setHAPolicyConfiguration(sharedStorage ? new SharedStoreMasterPolicyConfiguration() : new ReplicatedPolicyConfiguration());
 
       List<String> targetServersOnConnection = new ArrayList<String>();
 
@@ -224,15 +215,14 @@ public class MultiServerTestBase extends ServiceTestBase
          configuration.getConnectorConfigurations().put(backupConnectorName, backupConnector);
       }
 
-      ClusterConnectionConfiguration clusterConf =
-         new ClusterConnectionConfiguration("localCluster" + node, "cluster-queues", "thisConnector",
-                                            100,
-                                            true,
-                                            false,
-                                            1,
-                                            1024,
-                                            targetServersOnConnection,
-                                            false);
+      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration()
+         .setName("localCluster" + node)
+         .setAddress("cluster-queues")
+         .setConnectorName("thisConnector")
+         .setRetryInterval(100)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(targetServersOnConnection);
+
       configuration.getClusterConfigurations().add(clusterConf);
 
       HornetQServer server;
@@ -258,24 +248,14 @@ public class MultiServerTestBase extends ServiceTestBase
                                              final int liveNode,
                                              final NodeManager nodeManager) throws Exception
    {
-      Configuration configuration = createBasicConfig(useSharedStorage() ? liveNode : node);
-
-      if (useSharedStorage())
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      else
-         configuration.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-
-      configuration.getAcceptorConfigurations().clear();
-
-      TransportConfiguration serverConfigAcceptor = createTransportConfiguration(useNetty(), true,
-                                                                                 generateParams(node, useNetty()));
-      configuration.getAcceptorConfigurations().add(serverConfigAcceptor);
-
-
-
+      TransportConfiguration serverConfigAcceptor = createTransportConfiguration(useNetty(), true, generateParams(node, useNetty()));
       TransportConfiguration thisConnector = createTransportConfiguration(useNetty(), false, generateParams(node, useNetty()));
 
-      configuration.getConnectorConfigurations().put("thisConnector", thisConnector);
+      Configuration configuration = createBasicConfig(useSharedStorage() ? liveNode : node)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(serverConfigAcceptor)
+         .addConnectorConfiguration("thisConnector", thisConnector)
+         .setHAPolicyConfiguration(useSharedStorage() ? new SharedStoreSlavePolicyConfiguration() : new ReplicaPolicyConfiguration());
 
       List<String> targetServersOnConnection = new ArrayList<String>();
 
@@ -288,19 +268,18 @@ public class MultiServerTestBase extends ServiceTestBase
 //         }
          String targetConnectorName = "targetConnector-" + targetNode;
          TransportConfiguration targetServer = createTransportConfiguration(useNetty(), false, generateParams(targetNode, useNetty()));
-         configuration.getConnectorConfigurations().put(targetConnectorName, targetServer);
+         configuration.addConnectorConfiguration(targetConnectorName, targetServer);
          targetServersOnConnection.add(targetConnectorName);
       }
 
-      ClusterConnectionConfiguration clusterConf =
-         new ClusterConnectionConfiguration("localCluster" + node, "cluster-queues", "thisConnector",
-                                            100,
-                                            true,
-                                            false,
-                                            1,
-                                            1024,
-                                            targetServersOnConnection,
-                                            false);
+      ClusterConnectionConfiguration clusterConf = new ClusterConnectionConfiguration()
+         .setName("localCluster" + node)
+         .setAddress("cluster-queues")
+         .setConnectorName("thisConnector")
+         .setRetryInterval(100)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(targetServersOnConnection);
+
       configuration.getClusterConfigurations().add(clusterConf);
 
       HornetQServer server;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/discovery/DiscoveryTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/discovery/DiscoveryTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/discovery/DiscoveryTest.java
index 0111ee7..2b10d2c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/discovery/DiscoveryTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/discovery/DiscoveryTest.java
@@ -12,8 +12,12 @@
  */
 package org.hornetq.tests.integration.discovery;
 
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
 import java.net.InetAddress;
 import java.net.NetworkInterface;
 import java.util.ArrayList;
@@ -33,7 +37,7 @@ import org.hornetq.api.core.JGroupsBroadcastGroupConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.UDPBroadcastGroupConfiguration;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.cluster.DiscoveryEntry;
 import org.hornetq.core.cluster.DiscoveryGroup;
 import org.hornetq.core.cluster.DiscoveryListener;
@@ -114,7 +118,7 @@ public class DiscoveryTest extends UnitTestCase
 
       bg = new BroadcastGroupImpl(new FakeNodeManager(nodeID),
                                   RandomUtil.randomString(),
-                                  0, null, new UDPBroadcastGroupConfiguration(address1, groupPort, null, -1).createBroadcastEndpointFactory());
+                                  0, null, new UDPBroadcastGroupConfiguration().setGroupAddress(address1).setGroupPort(groupPort).createBroadcastEndpointFactory());
 
       bg.start();
 
@@ -1158,7 +1162,7 @@ public class DiscoveryTest extends UnitTestCase
 
       Assert.assertEquals(1, notifListener.getNotifications().size());
       Notification notif = notifListener.getNotifications().get(0);
-      Assert.assertEquals(NotificationType.DISCOVERY_GROUP_STARTED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.DISCOVERY_GROUP_STARTED, notif.getType());
       Assert.assertEquals(dg.getName(), notif.getProperties()
          .getSimpleStringProperty(new SimpleString("name"))
          .toString());
@@ -1167,7 +1171,7 @@ public class DiscoveryTest extends UnitTestCase
 
       Assert.assertEquals(2, notifListener.getNotifications().size());
       notif = notifListener.getNotifications().get(1);
-      Assert.assertEquals(NotificationType.DISCOVERY_GROUP_STOPPED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.DISCOVERY_GROUP_STOPPED, notif.getType());
       Assert.assertEquals(dg.getName(), notif.getProperties()
          .getSimpleStringProperty(new SimpleString("name"))
          .toString());
@@ -1198,7 +1202,7 @@ public class DiscoveryTest extends UnitTestCase
 
       Assert.assertEquals(1, notifListener.getNotifications().size());
       Notification notif = notifListener.getNotifications().get(0);
-      Assert.assertEquals(NotificationType.BROADCAST_GROUP_STARTED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.BROADCAST_GROUP_STARTED, notif.getType());
       Assert.assertEquals(bg.getName(), notif.getProperties()
          .getSimpleStringProperty(new SimpleString("name"))
          .toString());
@@ -1207,12 +1211,34 @@ public class DiscoveryTest extends UnitTestCase
 
       Assert.assertEquals(2, notifListener.getNotifications().size());
       notif = notifListener.getNotifications().get(1);
-      Assert.assertEquals(NotificationType.BROADCAST_GROUP_STOPPED, notif.getType());
+      Assert.assertEquals(CoreNotificationType.BROADCAST_GROUP_STOPPED, notif.getType());
       Assert.assertEquals(bg.getName(), notif.getProperties()
          .getSimpleStringProperty(new SimpleString("name"))
          .toString());
    }
 
+   /**
+    * https://issues.jboss.org/browse/HORNETQ-1389
+    * @throws Exception
+    */
+   @Test
+   public void testJGroupsBroadcastGroupConfigurationSerializable() throws Exception
+   {
+      JGroupsBroadcastGroupConfiguration jgroupsConfig =
+         new JGroupsBroadcastGroupConfiguration(TEST_JGROUPS_CONF_FILE, "somChannel");
+      ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+      ObjectOutputStream objectOut = new ObjectOutputStream(byteOut);
+      objectOut.writeObject(jgroupsConfig);
+
+      byte[] serializedData = byteOut.toByteArray();
+      ByteArrayInputStream byteIn = new ByteArrayInputStream(serializedData);
+      ObjectInputStream objectIn = new ObjectInputStream(byteIn);
+
+      Object object = objectIn.readObject();
+      assertNotNull(object);
+      assertTrue(object instanceof JGroupsBroadcastGroupConfiguration);
+   }
+
    private TransportConfiguration generateTC(String debug)
    {
       String className = "org.foo.bar." + debug + "|" + UUIDGenerator.getInstance().generateStringUUID() + "";
@@ -1305,9 +1331,12 @@ public class DiscoveryTest extends UnitTestCase
                                            final InetAddress groupAddress,
                                            final int groupPort) throws Exception
    {
-      return new BroadcastGroupImpl(new FakeNodeManager(nodeID), name, 0, null,
-                                    new UDPBroadcastGroupConfiguration(groupAddress.getHostAddress(), groupPort,
-                                                                       localAddress != null ? localAddress.getHostAddress() : null, localPort).createBroadcastEndpointFactory());
+      return new BroadcastGroupImpl(new FakeNodeManager(nodeID), name, 0, null, new UDPBroadcastGroupConfiguration()
+         .setGroupAddress(groupAddress.getHostAddress())
+         .setGroupPort(groupPort)
+         .setLocalBindAddress(localAddress != null ? localAddress.getHostAddress() : null)
+         .setLocalBindPort(localPort)
+         .createBroadcastEndpointFactory());
    }
 
    private DiscoveryGroup newDiscoveryGroup(final String nodeID, final String name, final InetAddress localBindAddress,
@@ -1319,9 +1348,11 @@ public class DiscoveryTest extends UnitTestCase
    private DiscoveryGroup newDiscoveryGroup(final String nodeID, final String name, final InetAddress localBindAddress,
                                             final InetAddress groupAddress, final int groupPort, final long timeout, NotificationService notif) throws Exception
    {
-      return new DiscoveryGroup(nodeID, name, timeout,
-                                new UDPBroadcastGroupConfiguration(groupAddress.getHostAddress(), groupPort,
-                                                                   localBindAddress != null ? localBindAddress.getHostAddress() : null, -1).createBroadcastEndpointFactory(), notif);
+      return new DiscoveryGroup(nodeID, name, timeout, new UDPBroadcastGroupConfiguration()
+         .setGroupAddress(groupAddress.getHostAddress())
+         .setGroupPort(groupPort)
+         .setLocalBindAddress(localBindAddress != null ? localBindAddress.getHostAddress() : null)
+         .createBroadcastEndpointFactory(), notif);
    }
 
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/DivertTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/DivertTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/DivertTest.java
index 2b0d61e..6bae7f1 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/DivertTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/DivertTest.java
@@ -24,8 +24,10 @@ import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.DivertConfiguration;
+import org.hornetq.core.message.impl.MessageImpl;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
+import org.hornetq.core.settings.impl.AddressSettings;
 import org.hornetq.tests.util.ServiceTestBase;
 import org.junit.Assert;
 import org.junit.Test;
@@ -49,13 +51,11 @@ public class DivertTest extends ServiceTestBase
 
       final String forwardAddress = "forwardAddress";
 
-      DivertConfiguration divertConf = new DivertConfiguration("divert1",
-                                                               "divert1",
-                                                               testAddress,
-                                                               forwardAddress,
-                                                               false,
-                                                               null,
-                                                               null);
+      DivertConfiguration divertConf = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -135,6 +135,145 @@ public class DivertTest extends ServiceTestBase
       messagingService.stop();
    }
 
+
+   @Test
+   public void testSingleDivertWithExpiry() throws Exception
+   {
+      Configuration conf = createDefaultConfig();
+      final String testAddress = "testAddress";
+
+      final String forwardAddress = "forwardAddress";
+
+      final String expiryAddress = "expiryAddress";
+
+      conf.getAddressesSettings().clear();
+
+      AddressSettings expirySettings = new AddressSettings();
+      expirySettings.setExpiryAddress(new SimpleString(expiryAddress));
+
+      conf.getAddressesSettings().put("#", expirySettings);
+
+      DivertConfiguration divertConf = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress);
+
+      List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
+
+      divertConfs.add(divertConf);
+
+      conf.setDivertConfigurations(divertConfs);
+
+      HornetQServer messagingService = addServer(HornetQServers.newHornetQServer(conf, true));
+
+      messagingService.start();
+
+
+      ServerLocator locator = createInVMNonHALocator();
+
+      ClientSessionFactory sf = createSessionFactory(locator);
+
+      ClientSession session = sf.createSession(false, false, false);
+
+      final SimpleString queueName1 = new SimpleString("queue1");
+
+      final SimpleString queueName2 = new SimpleString("queue2");
+
+      session.createQueue(new SimpleString(forwardAddress), queueName1, null, true);
+
+      session.createQueue(new SimpleString(testAddress), queueName2, null, true);
+
+      session.createQueue(new SimpleString(expiryAddress), new SimpleString(expiryAddress), null, true);
+
+      session.start();
+
+      ClientProducer producer = session.createProducer(new SimpleString(testAddress));
+
+      ClientConsumer consumer1 = session.createConsumer(queueName1);
+
+      ClientConsumer consumer2 = session.createConsumer(queueName2);
+
+      final int numMessages = 1;
+
+      final SimpleString propKey = new SimpleString("testkey");
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         ClientMessage message = session.createMessage(true);
+
+         message.putIntProperty(propKey, i);
+
+         message.setExpiration(System.currentTimeMillis() + 1000);
+
+         producer.send(message);
+      }
+      session.commit();
+
+
+      // this context is validating if these messages are routed correctly
+      {
+         int count1 = 0;
+         ClientMessage message = null;
+         while ((message = consumer1.receiveImmediate()) != null)
+         {
+            message.acknowledge();
+            count1++;
+         }
+
+         int count2 = 0;
+         message = null;
+         while ((message = consumer2.receiveImmediate()) != null)
+         {
+            message.acknowledge();
+            count2++;
+         }
+
+         assertEquals(1, count1);
+         assertEquals(1, count2);
+         session.rollback();
+      }
+      Thread.sleep(2000);
+
+      // it must been expired by now
+      assertNull(consumer1.receiveImmediate());
+      // it must been expired by now
+      assertNull(consumer2.receiveImmediate());
+
+      int countOriginal1 = 0;
+      int countOriginal2 = 0;
+      ClientConsumer consumerExpiry = session.createConsumer(expiryAddress);
+
+      for (int i = 0; i < numMessages * 2; i++)
+      {
+         ClientMessage message = consumerExpiry.receive(5000);
+         System.out.println("Received message " + message);
+         assertNotNull(message);
+
+         if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue1"))
+         {
+            countOriginal1++;
+         }
+         else if (message.getStringProperty(MessageImpl.HDR_ORIGINAL_QUEUE).equals("queue2"))
+         {
+            countOriginal2++;
+         }
+         else
+         {
+            System.out.println("message not part of any expired queue" + message);
+         }
+      }
+
+      assertEquals(numMessages, countOriginal1);
+      assertEquals(numMessages, countOriginal2);
+
+      session.close();
+
+      sf.close();
+
+      messagingService.stop();
+   }
+
    @Test
    public void testSingleNonExclusiveDivert2() throws Exception
    {
@@ -143,13 +282,11 @@ public class DivertTest extends ServiceTestBase
 
       final String forwardAddress = "forwardAddress";
 
-      DivertConfiguration divertConf = new DivertConfiguration("divert1",
-                                                               "divert1",
-                                                               testAddress,
-                                                               forwardAddress,
-                                                               false,
-                                                               null,
-                                                               null);
+      DivertConfiguration divertConf = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -275,13 +412,11 @@ public class DivertTest extends ServiceTestBase
 
       final String forwardAddress = "forwardAddress";
 
-      DivertConfiguration divertConf = new DivertConfiguration("divert1",
-                                                               "divert1",
-                                                               testAddress,
-                                                               forwardAddress,
-                                                               false,
-                                                               null,
-                                                               null);
+      DivertConfiguration divertConf = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -349,13 +484,12 @@ public class DivertTest extends ServiceTestBase
 
       final String forwardAddress = "forwardAddress";
 
-      DivertConfiguration divertConf = new DivertConfiguration("divert1",
-                                                               "divert1",
-                                                               testAddress,
-                                                               forwardAddress,
-                                                               true,
-                                                               null,
-                                                               null);
+      DivertConfiguration divertConf = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress)
+         .setExclusive(true);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -448,29 +582,23 @@ public class DivertTest extends ServiceTestBase
       final String forwardAddress2 = "forwardAddress2";
       final String forwardAddress3 = "forwardAddress3";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "divert1",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert2",
-                                                                "divert2",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert3",
-                                                                "divert3",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                false,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("divert2")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert3")
+         .setRoutingName("divert3")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -599,29 +727,26 @@ public class DivertTest extends ServiceTestBase
       final String forwardAddress2 = "forwardAddress2";
       final String forwardAddress3 = "forwardAddress3";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "divert1",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                true,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert2",
-                                                                "divert2",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                true,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert3",
-                                                                "divert3",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                true,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1)
+         .setExclusive(true);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("divert2")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2)
+         .setExclusive(true);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert3")
+         .setRoutingName("divert3")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3)
+         .setExclusive(true);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -740,29 +865,25 @@ public class DivertTest extends ServiceTestBase
       final String forwardAddress2 = "forwardAddress2";
       final String forwardAddress3 = "forwardAddress3";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "divert1",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                true,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert2",
-                                                                "divert2",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                true,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert3",
-                                                                "divert3",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                false,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1)
+         .setExclusive(true);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("divert2")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2)
+         .setExclusive(true);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert3")
+         .setRoutingName("divert3")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -872,29 +993,25 @@ public class DivertTest extends ServiceTestBase
 
       final String filter = "animal='antelope'";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "divert1",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                true,
-                                                                filter,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert2",
-                                                                "divert2",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert3",
-                                                                "divert3",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                false,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1)
+         .setExclusive(true)
+         .setFilterString(filter);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("divert2")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert3")
+         .setRoutingName("divert3")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -1055,29 +1172,23 @@ public class DivertTest extends ServiceTestBase
       final String forwardAddress2 = "forwardAddress2";
       final String forwardAddress3 = "forwardAddress3";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "thename",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert2",
-                                                                "thename",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert3",
-                                                                "thename",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                false,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("thename")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("thename")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert3")
+         .setRoutingName("thename")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -1215,29 +1326,23 @@ public class DivertTest extends ServiceTestBase
       final String forwardAddress2 = "forwardAddress2";
       final String forwardAddress3 = "forwardAddress3";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "thename1",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert1",
-                                                                "thename2",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert2",
-                                                                "thename3",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                false,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("thename1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("thename2")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("thename3")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/PersistentDivertTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/PersistentDivertTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/PersistentDivertTest.java
index 91b0954..95264f7 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/PersistentDivertTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/divert/PersistentDivertTest.java
@@ -71,29 +71,23 @@ public class PersistentDivertTest extends ServiceTestBase
 
       final String forwardAddress3 = "forwardAddress3";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "divert1",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert2",
-                                                                "divert2",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert3",
-                                                                "divert3",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                false,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("divert2")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert3")
+         .setRoutingName("divert3")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 
@@ -274,29 +268,23 @@ public class PersistentDivertTest extends ServiceTestBase
 
       final String forwardAddress3 = "forwardAddress3";
 
-      DivertConfiguration divertConf1 = new DivertConfiguration("divert1",
-                                                                "divert1",
-                                                                testAddress,
-                                                                forwardAddress1,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf2 = new DivertConfiguration("divert2",
-                                                                "divert2",
-                                                                testAddress,
-                                                                forwardAddress2,
-                                                                false,
-                                                                null,
-                                                                null);
-
-      DivertConfiguration divertConf3 = new DivertConfiguration("divert3",
-                                                                "divert3",
-                                                                testAddress,
-                                                                forwardAddress3,
-                                                                false,
-                                                                null,
-                                                                null);
+      DivertConfiguration divertConf1 = new DivertConfiguration()
+         .setName("divert1")
+         .setRoutingName("divert1")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress1);
+
+      DivertConfiguration divertConf2 = new DivertConfiguration()
+         .setName("divert2")
+         .setRoutingName("divert2")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress2);
+
+      DivertConfiguration divertConf3 = new DivertConfiguration()
+         .setName("divert3")
+         .setRoutingName("divert3")
+         .setAddress(testAddress)
+         .setForwardingAddress(forwardAddress3);
 
       List<DivertConfiguration> divertConfs = new ArrayList<DivertConfiguration>();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/embedded/ValidateAIOTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/embedded/ValidateAIOTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/embedded/ValidateAIOTest.java
index 9d782a0..3f9b5d5 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/embedded/ValidateAIOTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/embedded/ValidateAIOTest.java
@@ -31,9 +31,9 @@ public class ValidateAIOTest extends ServiceTestBase
    @Test
    public void testValidateAIO() throws Exception
    {
-      Configuration config = createDefaultConfig(false);
-      // This will force AsyncIO
-      config.setJournalType(JournalType.ASYNCIO);
+      Configuration config = createDefaultConfig(false)
+         // This will force AsyncIO
+         .setJournalType(JournalType.ASYNCIO);
       HornetQServer server = HornetQServers.newHornetQServer(config, true);
       try
       {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/http/CoreClientOverHttpTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/http/CoreClientOverHttpTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/http/CoreClientOverHttpTest.java
index 964616a..7c08c77 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/http/CoreClientOverHttpTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/http/CoreClientOverHttpTest.java
@@ -51,12 +51,12 @@ public class CoreClientOverHttpTest extends UnitTestCase
    public void setUp() throws Exception
    {
       super.setUp();
-      conf = createDefaultConfig();
-
-      conf.setSecurityEnabled(false);
       HashMap<String, Object> params = new HashMap<String, Object>();
       params.put(TransportConstants.HTTP_ENABLED_PROP_NAME, true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
+
+      conf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
 
       server = addServer(HornetQServers.newHornetQServer(conf, false));
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/FloodServerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/FloodServerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/FloodServerTest.java
index 03b2460..1550d0b 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/FloodServerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/FloodServerTest.java
@@ -84,10 +84,8 @@ public class FloodServerTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(NettyAcceptorFactory.class.getName()));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(NettyAcceptorFactory.class.getName()));
       server = HornetQServers.newHornetQServer(conf, false);
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/HornetQConnectionFactoryTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/HornetQConnectionFactoryTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/HornetQConnectionFactoryTest.java
index 4205942..1e2def9 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/HornetQConnectionFactoryTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/HornetQConnectionFactoryTest.java
@@ -11,7 +11,7 @@
  * permissions and limitations under the License.
  */
 package org.hornetq.tests.integration.jms;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
 import org.junit.Before;
 
 import org.junit.Test;
@@ -164,8 +164,10 @@ public class HornetQConnectionFactoryTest extends UnitTestCase
    @Test
    public void testDiscoveryConstructor() throws Exception
    {
-      DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration(HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT,
-            new UDPBroadcastGroupConfiguration(groupAddress, groupPort, null, -1));
+      DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration()
+         .setBroadcastEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+                                                      .setGroupAddress(groupAddress)
+                                                      .setGroupPort(groupPort));
       HornetQConnectionFactory cf = HornetQJMSClient.createConnectionFactoryWithoutHA(groupConfiguration, JMSFactoryType.CF);
       assertFactoryParams(cf,
                           null,
@@ -707,27 +709,31 @@ public class HornetQConnectionFactoryTest extends UnitTestCase
 
    private void startServer() throws Exception
    {
-      Configuration liveConf = createBasicConfig();
-      liveConf.setSecurityEnabled(false);
       liveTC = new TransportConfiguration(INVM_CONNECTOR_FACTORY);
-      liveConf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       Map<String, TransportConfiguration> connectors = new HashMap<String, TransportConfiguration>();
       connectors.put(liveTC.getName(), liveTC);
-      liveConf.setConnectorConfigurations(connectors);
-      liveConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
       List<String> connectorNames = new ArrayList<String>();
       connectorNames.add(liveTC.getName());
 
+      Configuration liveConf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY))
+         .setConnectorConfigurations(connectors)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration());
+
       final long broadcastPeriod = 250;
 
       final String bcGroupName = "bc1";
 
       final int localBindPort = 5432;
 
-      BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration(bcGroupName,
-                                                                              broadcastPeriod,
-                                                                              connectorNames,
-                                              new UDPBroadcastGroupConfiguration(groupAddress, groupPort, null, localBindPort));
+      BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration()
+         .setName(bcGroupName)
+         .setBroadcastPeriod(broadcastPeriod)
+         .setConnectorInfos(connectorNames)
+         .setEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+                                             .setGroupAddress(groupAddress)
+                                             .setGroupPort(groupPort)
+                                             .setLocalBindPort(localBindPort));
 
       List<BroadcastGroupConfiguration> bcConfigs1 = new ArrayList<BroadcastGroupConfiguration>();
       bcConfigs1.add(bcConfig1);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/ManualReconnectionToSingleServerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/ManualReconnectionToSingleServerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/ManualReconnectionToSingleServerTest.java
index 90c71e5..1f35454 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/ManualReconnectionToSingleServerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/ManualReconnectionToSingleServerTest.java
@@ -148,25 +148,25 @@ public class ManualReconnectionToSingleServerTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
+      context = new InVMNamingContext();
+
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
+
       server = createServer(false, conf);
 
       JMSConfiguration configuration = new JMSConfigurationImpl();
-      context = new InVMNamingContext();
       configuration.setContext(context);
-      configuration.getQueueConfigurations().add(new JMSQueueConfigurationImpl(QUEUE_NAME, null, true, QUEUE_NAME));
+      configuration.getQueueConfigurations().add(new JMSQueueConfigurationImpl().setName(QUEUE_NAME).setBindings(QUEUE_NAME));
 
       ArrayList<TransportConfiguration> configs = new ArrayList<TransportConfiguration>();
       configs.add(new TransportConfiguration(NETTY_CONNECTOR_FACTORY));
-      ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl("cf",
-            false,
-            registerConnectors(server, configs), "/cf");
-      cfConfig.setRetryInterval(1000);
-      cfConfig.setRetryIntervalMultiplier(1.0);
-      cfConfig.setReconnectAttempts(-1);
+      ConnectionFactoryConfiguration cfConfig = new ConnectionFactoryConfigurationImpl()
+         .setName("cf")
+         .setConnectorNames(registerConnectors(server, configs))
+         .setBindings("/cf")
+         .setRetryInterval(1000)
+         .setReconnectAttempts(-1);
       configuration.getConnectionFactoryConfigurations().add(cfConfig);
       serverManager = new JMSServerManagerImpl(server, configuration);
       serverManager.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/BridgeTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/BridgeTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/BridgeTestBase.java
index a4e491b..11811e6 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/BridgeTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/BridgeTestBase.java
@@ -98,7 +98,7 @@ public abstract class BridgeTestBase extends UnitTestCase
 
    protected InVMNamingContext context1;
 
-   private HashMap<String, Object> params1;
+   protected HashMap<String, Object> params1;
 
    protected ConnectionFactoryFactory cff0LowProducerWindow;
 
@@ -109,11 +109,11 @@ public abstract class BridgeTestBase extends UnitTestCase
       super.setUp();
 
       // Start the servers
-      Configuration conf0 = createBasicConfig();
-      conf0.setJournalDirectory(getJournalDir(0, false));
-      conf0.setBindingsDirectory(getBindingsDir(0, false));
-      conf0.setSecurityEnabled(false);
-      conf0.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf0 = createBasicConfig()
+         .setJournalDirectory(getJournalDir(0, false))
+         .setBindingsDirectory(getBindingsDir(0, false))
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+
       server0 = addServer(HornetQServers.newHornetQServer(conf0, false));
 
       context0 = new InVMNamingContext();
@@ -121,13 +121,13 @@ public abstract class BridgeTestBase extends UnitTestCase
       jmsServer0.setContext(context0);
       jmsServer0.start();
 
-      Configuration conf1 = createBasicConfig();
-      conf1.setSecurityEnabled(false);
-      conf1.setJournalDirectory(getJournalDir(1, false));
-      conf1.setBindingsDirectory(getBindingsDir(1, false));
       params1 = new HashMap<String, Object>();
       params1.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-      conf1.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params1));
+
+      Configuration conf1 = createBasicConfig()
+         .setJournalDirectory(getJournalDir(1, false))
+         .setBindingsDirectory(getBindingsDir(1, false))
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params1));
 
       server1 = addServer(HornetQServers.newHornetQServer(conf1, false));
 
@@ -562,11 +562,16 @@ public abstract class BridgeTestBase extends UnitTestCase
       }
       JMSQueueControl queueControl = (JMSQueueControl) managementService.getResource(ResourceNames.JMS_QUEUE + queue.getQueueName());
 
-      Long messageCount = queueControl.getMessageCount();
-
-      if (messageCount > 0)
+      //server may be closed
+      if (queueControl != null)
       {
-         queueControl.removeMessages(null);
+         queueControl.flushExecutor();
+         Long messageCount = queueControl.getMessageCount();
+
+         if (messageCount > 0)
+         {
+            queueControl.removeMessages(null);
+         }
       }
       return true;
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/ClusteredBridgeTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/ClusteredBridgeTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/ClusteredBridgeTestBase.java
index 451e2ed..cc75b20 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/ClusteredBridgeTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/ClusteredBridgeTestBase.java
@@ -37,10 +37,11 @@ import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.api.jms.HornetQJMSClient;
 import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
 import org.hornetq.core.remoting.impl.invm.TransportConstants;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.jms.bridge.ConnectionFactoryFactory;
 import org.hornetq.jms.bridge.DestinationFactory;
 import org.hornetq.jms.client.HornetQConnectionFactory;
@@ -151,14 +152,13 @@ public abstract class ClusteredBridgeTestBase extends ServiceTestBase
          backupConnector = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params, "in-vm-backup");
 
          //live
-         Configuration conf0 = createBasicConfig();
-         conf0.setJournalDirectory(getJournalDir(id, false));
-         conf0.setBindingsDirectory(getBindingsDir(id, false));
-         conf0.setSecurityEnabled(false);
-         conf0.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params0));
-         conf0.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-         conf0.getHAPolicy().setFailoverOnServerShutdown(true);
-         basicClusterConnectionConfig(conf0, liveConnector.getName());
+         Configuration conf0 = createBasicConfig()
+            .setJournalDirectory(getJournalDir(id, false))
+            .setBindingsDirectory(getBindingsDir(id, false))
+            .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params0))
+            .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+            .setHAPolicyConfiguration(new ReplicatedPolicyConfiguration())
+            .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName()));
 
          HornetQServer server0 = addServer(HornetQServers.newHornetQServer(conf0, true));
 
@@ -167,17 +167,14 @@ public abstract class ClusteredBridgeTestBase extends ServiceTestBase
          liveNode.setContext(liveContext);
 
          //backup
-         Configuration conf = createBasicConfig();
-         conf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_REPLICATED);
-         conf.setJournalDirectory(getJournalDir(id, true));
-         conf.setBindingsDirectory(getBindingsDir(id, true));
-         conf.setSecurityEnabled(false);
-         conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params));
-
-         conf.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-         conf.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-         conf.getHAPolicy().setFailoverOnServerShutdown(true);
-         basicClusterConnectionConfig(conf, backupConnector.getName(), liveConnector.getName());
+         Configuration conf = createBasicConfig()
+            .setJournalDirectory(getJournalDir(id, true))
+            .setBindingsDirectory(getBindingsDir(id, true))
+            .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params))
+            .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+            .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+            .setHAPolicyConfiguration(new ReplicaPolicyConfiguration())
+            .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName()));
 
          HornetQServer backup = addServer(HornetQServers.newHornetQServer(conf, true));
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/JMSBridgeReconnectionTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/JMSBridgeReconnectionTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/JMSBridgeReconnectionTest.java
index 2a94222..c20c48d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/JMSBridgeReconnectionTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/bridge/JMSBridgeReconnectionTest.java
@@ -12,13 +12,27 @@
  */
 package org.hornetq.tests.integration.jms.bridge;
 
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.api.jms.HornetQJMSClient;
+import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.jms.bridge.ConnectionFactoryFactory;
 import org.hornetq.jms.bridge.QualityOfServiceMode;
 import org.hornetq.jms.bridge.impl.JMSBridgeImpl;
+import org.hornetq.jms.client.HornetQXAConnectionFactory;
 import org.hornetq.tests.integration.IntegrationTestLogger;
+import org.hornetq.tests.integration.ra.DummyTransactionManager;
 import org.junit.Assert;
 import org.junit.Test;
 
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.RollbackException;
+import javax.transaction.Synchronization;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import javax.transaction.xa.XAResource;
+
 /**
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  */
@@ -259,9 +273,221 @@ public class JMSBridgeReconnectionTest extends BridgeTestBase
 
       JMSBridgeReconnectionTest.log.info("Sent messages");
 
-      checkMessagesReceived(cf1, targetQueue, qosMode, NUM_MESSAGES, false, largeMessage);
+      jmsServer1.stop();
+
+      bridge.stop();
+
+      System.out.println("JMSBridgeReconnectionTest.performCrashAndReconnectDestBasic");
+   }
+
+   @Test
+   public void performCrashDestinationStopBridge() throws Exception
+   {
+      ConnectionFactoryFactory factInUse0 = cff0;
+      ConnectionFactoryFactory factInUse1 = cff1;
+      final JMSBridgeImpl bridge =
+            new JMSBridgeImpl(factInUse0,
+                  factInUse1,
+                  sourceQueueFactory,
+                  targetQueueFactory,
+                  null,
+                  null,
+                  null,
+                  null,
+                  null,
+                  1000,
+                  -1,
+                  QualityOfServiceMode.DUPLICATES_OK,
+                  10,
+                  -1,
+                  null,
+                  null,
+                  false);
+
+
+      addHornetQComponent(bridge);
+      bridge.setTransactionManager(newTransactionManager());
+      bridge.start();
+
+      Thread clientThread = new Thread(new Runnable()
+      {
+         @Override
+         public void run()
+         {
+            while (bridge.isStarted())
+            {
+               try
+               {
+                  sendMessages(cf0, sourceQueue, 0, 1, false, false);
+               }
+               catch (Exception e)
+               {
+                  e.printStackTrace();
+               }
+            }
+         }
+      });
+
+      clientThread.start();
+
+      checkAllMessageReceivedInOrder(cf1, targetQueue, 0, 1, false);
+
+      JMSBridgeReconnectionTest.log.info("About to crash server");
+
+      jmsServer1.stop();
+
+      // Wait a while before starting up to simulate the dest being down for a while
+      JMSBridgeReconnectionTest.log.info("Waiting 5 secs before bringing server back up");
+      Thread.sleep(TIME_WAIT);
+      JMSBridgeReconnectionTest.log.info("Done wait");
+
+      bridge.stop();
+
+      clientThread.join(5000);
+
+      assertTrue(!clientThread.isAlive());
+   }
+
+   @Test
+   public void performCrashAndReconnect() throws Exception
+   {
+      performCrashAndReconnect(true);
+   }
+
+   @Test
+   public void performCrashAndNoReconnect() throws Exception
+   {
+      performCrashAndReconnect(false);
+   }
+
+
+   private void performCrashAndReconnect(boolean restart) throws Exception
+   {
+      cff1xa = new ConnectionFactoryFactory()
+      {
+         public Object createConnectionFactory() throws Exception
+         {
+            HornetQXAConnectionFactory cf = (HornetQXAConnectionFactory) HornetQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.XA_CF,
+                  new TransportConfiguration(
+                        INVM_CONNECTOR_FACTORY,
+                        params1));
+
+            // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection
+            cf.setReconnectAttempts(-1);
+            cf.setBlockOnNonDurableSend(true);
+            cf.setBlockOnDurableSend(true);
+            cf.setCacheLargeMessagesClient(true);
+
+            return cf;
+         }
+
+      };
+
+      DummyTransactionManager tm = new DummyTransactionManager();
+      DummyTransaction tx = new DummyTransaction();
+      tm.tx = tx;
+
+      JMSBridgeImpl bridge =
+            new JMSBridgeImpl(cff0xa,
+                  cff1xa,
+                  sourceQueueFactory,
+                  targetQueueFactory,
+                  null,
+                  null,
+                  null,
+                  null,
+                  null,
+                  1000,
+                  -1,
+                  QualityOfServiceMode.ONCE_AND_ONLY_ONCE,
+                  10,
+                  5000,
+                  null,
+                  null,
+                  false);
+      addHornetQComponent(bridge);
+      bridge.setTransactionManager(tm);
+
+      bridge.start();
+
+      // Now crash the dest server
+
+      JMSBridgeReconnectionTest.log.info("About to crash server");
+
+      jmsServer1.stop();
+
+      if (restart)
+      {
+         jmsServer1.start();
+      }
+      // Wait a while before starting up to simulate the dest being down for a while
+      JMSBridgeReconnectionTest.log.info("Waiting 5 secs before bringing server back up");
+      Thread.sleep(TIME_WAIT);
+      JMSBridgeReconnectionTest.log.info("Done wait");
+
+      bridge.stop();
+
+      if (restart)
+      {
+         assertTrue(tx.rolledback);
+         assertTrue(tx.targetConnected);
+      }
+      else
+      {
+         assertTrue(tx.rolledback);
+         assertFalse(tx.targetConnected);
+      }
    }
 
+   private class DummyTransaction implements Transaction
+   {
+      boolean rolledback = false;
+      ClientSession targetSession;
+      boolean targetConnected = false;
+      @Override
+      public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException
+      {
+
+      }
+
+      @Override
+      public void rollback() throws IllegalStateException, SystemException
+      {
+         rolledback = true;
+         targetConnected = !targetSession.isClosed();
+      }
+
+      @Override
+      public void setRollbackOnly() throws IllegalStateException, SystemException
+      {
+
+      }
+
+      @Override
+      public int getStatus() throws SystemException
+      {
+         return 0;
+      }
+
+      @Override
+      public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException
+      {
+         targetSession = (ClientSession) xaResource;
+         return false;
+      }
+
+      @Override
+      public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException
+      {
+         return false;
+      }
+
+      @Override
+      public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException
+      {
+
+      }
+   }
    /*
     * Send some messages
     * Crash the destination server

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/ExpiryMessageTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/ExpiryMessageTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/ExpiryMessageTest.java
index 1de3f14..bb9cc94 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/ExpiryMessageTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/jms/client/ExpiryMessageTest.java
@@ -44,9 +44,8 @@ public class ExpiryMessageTest extends JMSTestBase
    @Override
    protected Configuration createDefaultConfig(boolean netty) throws Exception
    {
-      Configuration conf = super.createDefaultConfig(netty);
-
-      conf.setMessageExpiryScanPeriod(1000);
+      Configuration conf = super.createDefaultConfig(netty)
+         .setMessageExpiryScanPeriod(1000);
 
       return conf;
    }
@@ -58,8 +57,6 @@ public class ExpiryMessageTest extends JMSTestBase
       Topic topic = createTopic("test-topic");
       TopicControl control = ManagementControlHelper.createTopicControl(topic, mbeanServer);
 
-      System.out.println("size = " + control.getMessageCount());
-
       Connection conn2 = cf.createConnection();
 
       conn2.setClientID("client1");


[04/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControl2Test.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControl2Test.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControl2Test.java
index 2091296..43e6010 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControl2Test.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControl2Test.java
@@ -118,44 +118,54 @@ public class ClusterConnectionControl2Test extends ManagementTestBase
       TransportConfiguration connectorConfig_1 = new TransportConfiguration(NETTY_CONNECTOR_FACTORY, acceptorParams_1);
       TransportConfiguration connectorConfig_0 = new TransportConfiguration(NETTY_CONNECTOR_FACTORY);
 
-      CoreQueueConfiguration queueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                              RandomUtil.randomString(),
-                                                              null,
-                                                              false);
+      CoreQueueConfiguration queueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
       List<String> connectorInfos = new ArrayList<String>();
       connectorInfos.add("netty");
-      BroadcastGroupConfiguration broadcastGroupConfig = new BroadcastGroupConfiguration(discoveryName,
-                                                                                         250,
-                                                                                         connectorInfos,
-                                             new UDPBroadcastGroupConfiguration(groupAddress, groupPort, null, -1));
-      DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration(discoveryName,
-                                                                                         0,
-                                                                                         0,
-                                             new UDPBroadcastGroupConfiguration(groupAddress, groupPort, null, -1));
-
-      Configuration conf_1 = createBasicConfig();
-      conf_1.setSecurityEnabled(false);
-      conf_1.setJMXManagementEnabled(true);
-
-      clusterConnectionConfig_0 =
-               new ClusterConnectionConfiguration(clusterName, queueConfig.getAddress(), "netty", 1000, false, false,
-                                                  1, 1024,
-                                                  discoveryName);
-      conf_1.getClusterConfigurations().add(clusterConnectionConfig_0);
-      conf_1.getAcceptorConfigurations().add(acceptorConfig_1);
-      conf_1.getConnectorConfigurations().put("netty", connectorConfig_1);
-      conf_1.getQueueConfigurations().add(queueConfig);
-      conf_1.getDiscoveryGroupConfigurations().put(discoveryName, discoveryGroupConfig);
-      conf_1.getBroadcastGroupConfigurations().add(broadcastGroupConfig);
-
-      Configuration conf_0 = createBasicConfig(1);
-      conf_0.setSecurityEnabled(false);
-      conf_0.setJMXManagementEnabled(true);
-      conf_0.getAcceptorConfigurations().add(acceptorConfig_0);
-      conf_0.getConnectorConfigurations().put("netty", connectorConfig_0);
-      conf_0.getClusterConfigurations().add(clusterConnectionConfig_0);
-      conf_0.getDiscoveryGroupConfigurations().put(discoveryName, discoveryGroupConfig);
-      conf_0.getBroadcastGroupConfigurations().add(broadcastGroupConfig);
+
+      BroadcastGroupConfiguration broadcastGroupConfig = new BroadcastGroupConfiguration()
+         .setName(discoveryName)
+         .setBroadcastPeriod(250)
+         .setConnectorInfos(connectorInfos)
+         .setEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(groupAddress)
+            .setGroupPort(groupPort));
+
+      DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration()
+         .setName(discoveryName)
+         .setRefreshTimeout(0)
+         .setDiscoveryInitialWaitTimeout(0)
+         .setBroadcastEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(groupAddress)
+            .setGroupPort(groupPort));
+
+      clusterConnectionConfig_0 = new ClusterConnectionConfiguration()
+         .setName(clusterName)
+         .setAddress(queueConfig.getAddress())
+         .setConnectorName("netty")
+         .setRetryInterval(1000)
+         .setDuplicateDetection(false)
+         .setForwardWhenNoConsumers(false)
+         .setMaxHops(1)
+         .setConfirmationWindowSize(1024)
+         .setDiscoveryGroupName(discoveryName);
+
+      Configuration conf_1 = createBasicConfig()
+         .addClusterConfiguration(clusterConnectionConfig_0)
+         .addAcceptorConfiguration(acceptorConfig_1)
+         .addConnectorConfiguration("netty", connectorConfig_1)
+         .addQueueConfiguration(queueConfig)
+         .addDiscoveryGroupConfiguration(discoveryName, discoveryGroupConfig)
+         .addBroadcastGroupConfiguration(broadcastGroupConfig);
+
+      Configuration conf_0 = createBasicConfig(1)
+         .addClusterConfiguration(clusterConnectionConfig_0)
+         .addAcceptorConfiguration(acceptorConfig_0)
+         .addConnectorConfiguration("netty", connectorConfig_0)
+         .addDiscoveryGroupConfiguration(discoveryName, discoveryGroupConfig)
+         .addBroadcastGroupConfiguration(broadcastGroupConfig);
 
       mbeanServer_1 = MBeanServerFactory.createMBeanServer();
       server1 = addServer(HornetQServers.newHornetQServer(conf_1, mbeanServer_1, false));

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControlTest.java
index 7a9284f..79985af 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ClusterConnectionControlTest.java
@@ -13,7 +13,6 @@
 package org.hornetq.tests.integration.management;
 import org.junit.Before;
 import org.junit.After;
-
 import org.junit.Test;
 
 import java.util.ArrayList;
@@ -25,13 +24,12 @@ import javax.management.MBeanServer;
 import javax.management.MBeanServerFactory;
 
 import org.junit.Assert;
-
 import org.hornetq.api.core.DiscoveryGroupConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.UDPBroadcastGroupConfiguration;
 import org.hornetq.api.core.management.ClusterConnectionControl;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ObjectNameBuilder;
 import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
@@ -167,8 +165,8 @@ public class ClusterConnectionControlTest extends ManagementTestBase
       clusterConnectionControl.stop();
 
       Assert.assertTrue(notifListener.getNotifications().size() > 0);
-      Notification notif = notifListener.getNotifications().get(0);
-      Assert.assertEquals(NotificationType.CLUSTER_CONNECTION_STOPPED, notif.getType());
+      Notification notif = getFirstNotificationOfType(notifListener.getNotifications(), CoreNotificationType.CLUSTER_CONNECTION_STOPPED);
+      Assert.assertNotNull(notif);
       Assert.assertEquals(clusterConnectionControl.getName(), notif.getProperties()
                                                                    .getSimpleStringProperty(new SimpleString("name"))
                                                                    .toString());
@@ -176,13 +174,31 @@ public class ClusterConnectionControlTest extends ManagementTestBase
       clusterConnectionControl.start();
 
       Assert.assertTrue(notifListener.getNotifications().size() > 0);
-      notif = notifListener.getNotifications().get(1);
-      Assert.assertEquals(NotificationType.CLUSTER_CONNECTION_STARTED, notif.getType());
+      notif = getFirstNotificationOfType(notifListener.getNotifications(), CoreNotificationType.CLUSTER_CONNECTION_STARTED);
+      Assert.assertNotNull(notif);
       Assert.assertEquals(clusterConnectionControl.getName(), notif.getProperties()
                                                                    .getSimpleStringProperty(new SimpleString("name"))
                                                                    .toString());
    }
 
+   private Notification getFirstNotificationOfType(List<Notification> notifications, CoreNotificationType type)
+   {
+      Notification result = null;
+
+      // the notifications can change while we're looping
+      List<Notification> notificationsClone = new ArrayList<>(notifications);
+
+      for (Notification notification : notificationsClone)
+      {
+         if (notification.getType().equals(type))
+         {
+            result = notification;
+         }
+      }
+
+      return result;
+   }
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
@@ -203,46 +219,55 @@ public class ClusterConnectionControlTest extends ManagementTestBase
                                                                           acceptorParams,
                                                                           RandomUtil.randomString());
 
-      CoreQueueConfiguration queueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                              RandomUtil.randomString(),
-                                                              null,
-                                                              false);
+      CoreQueueConfiguration queueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
       List<String> connectors = new ArrayList<String>();
       connectors.add(connectorConfig.getName());
 
 
       String discoveryGroupName = RandomUtil.randomString();
-      DiscoveryGroupConfiguration discoveryGroupConfig =
-               new DiscoveryGroupConfiguration(discoveryGroupName, 500, 0,
-                     new UDPBroadcastGroupConfiguration("230.1.2.3", 6745, null, -1));
-
-      Configuration conf_1 = createBasicConfig();
-      conf_1.setSecurityEnabled(false);
-      conf_1.setJMXManagementEnabled(true);
-      conf_1.getAcceptorConfigurations().add(acceptorConfig);
-      conf_1.getQueueConfigurations().add(queueConfig);
-
-      Configuration conf_0 = createBasicConfig();
-      clusterConnectionConfig1 =
-               new ClusterConnectionConfiguration(RandomUtil.randomString(), queueConfig.getAddress(),
-                                                  connectorConfig.getName(), RandomUtil.randomPositiveLong(),
-                                                  RandomUtil.randomBoolean(), RandomUtil.randomBoolean(),
-                                                  RandomUtil.randomPositiveInt(), RandomUtil.randomPositiveInt(),
-                                                  connectors, false);
-      clusterConnectionConfig2 =
-               new ClusterConnectionConfiguration(RandomUtil.randomString(), queueConfig.getAddress(),
-                                                  connectorConfig.getName(), RandomUtil.randomPositiveLong(),
-                                                  RandomUtil.randomBoolean(), RandomUtil.randomBoolean(),
-                                                  RandomUtil.randomPositiveInt(), RandomUtil.randomPositiveInt(),
-                                                  discoveryGroupName);
-
-      conf_0.setSecurityEnabled(false);
-      conf_0.setJMXManagementEnabled(true);
-      conf_0.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
-      conf_0.getConnectorConfigurations().put(connectorConfig.getName(), connectorConfig);
-      conf_0.getClusterConfigurations().add(clusterConnectionConfig1);
-      conf_0.getClusterConfigurations().add(clusterConnectionConfig2);
-      conf_0.getDiscoveryGroupConfigurations().put(discoveryGroupName, discoveryGroupConfig);
+      DiscoveryGroupConfiguration discoveryGroupConfig = new DiscoveryGroupConfiguration()
+         .setName(discoveryGroupName)
+         .setRefreshTimeout(500)
+         .setDiscoveryInitialWaitTimeout(0)
+         .setBroadcastEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+                                                      .setGroupAddress("230.1.2.3")
+                                                      .setGroupPort(6745));
+
+      Configuration conf_1 = createBasicConfig()
+         .addAcceptorConfiguration(acceptorConfig)
+         .addQueueConfiguration(queueConfig);
+
+      clusterConnectionConfig1 = new ClusterConnectionConfiguration()
+         .setName(RandomUtil.randomString())
+         .setAddress(queueConfig.getAddress())
+         .setConnectorName(connectorConfig.getName())
+         .setRetryInterval(RandomUtil.randomPositiveLong())
+         .setDuplicateDetection(RandomUtil.randomBoolean())
+         .setForwardWhenNoConsumers(RandomUtil.randomBoolean())
+         .setMaxHops(RandomUtil.randomPositiveInt())
+         .setConfirmationWindowSize(RandomUtil.randomPositiveInt())
+         .setStaticConnectors(connectors);
+
+      clusterConnectionConfig2 = new ClusterConnectionConfiguration()
+         .setName(RandomUtil.randomString())
+         .setAddress(queueConfig.getAddress())
+         .setConnectorName(connectorConfig.getName())
+         .setRetryInterval(RandomUtil.randomPositiveLong())
+         .setDuplicateDetection(RandomUtil.randomBoolean())
+         .setForwardWhenNoConsumers(RandomUtil.randomBoolean())
+         .setMaxHops(RandomUtil.randomPositiveInt())
+         .setConfirmationWindowSize(RandomUtil.randomPositiveInt())
+         .setDiscoveryGroupName(discoveryGroupName);
+
+      Configuration conf_0 = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()))
+         .addConnectorConfiguration(connectorConfig.getName(), connectorConfig)
+         .addClusterConfiguration(clusterConnectionConfig1)
+         .addClusterConfiguration(clusterConnectionConfig2)
+         .addDiscoveryGroupConfiguration(discoveryGroupName, discoveryGroupConfig);
 
       mbeanServer_1 = MBeanServerFactory.createMBeanServer();
       server_1 = addServer(HornetQServers.newHornetQServer(conf_1, mbeanServer_1, false));

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/DivertControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/DivertControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/DivertControlTest.java
index 1998847..ef1e312 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/DivertControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/DivertControlTest.java
@@ -87,31 +87,28 @@ public class DivertControlTest extends ManagementTestBase
 
       TransportConfiguration connectorConfig = new TransportConfiguration(InVMConnectorFactory.class.getName());
 
-      CoreQueueConfiguration queueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                              RandomUtil.randomString(),
-                                                              null,
-                                                              false);
-      CoreQueueConfiguration forwardQueueConfig = new CoreQueueConfiguration(RandomUtil.randomString(),
-                                                                    RandomUtil.randomString(),
-                                                                    null,
-                                                                    false);
-
-      divertConfig = new DivertConfiguration(RandomUtil.randomString(),
-                                             RandomUtil.randomString(),
-                                             queueConfig.getAddress(),
-                                             forwardQueueConfig.getAddress(),
-                                             RandomUtil.randomBoolean(),
-                                             null,
-                                             null);
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getQueueConfigurations().add(queueConfig);
-      conf.getQueueConfigurations().add(forwardQueueConfig);
-      conf.getDivertConfigurations().add(divertConfig);
-
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
-      conf.getConnectorConfigurations().put(connectorConfig.getName(), connectorConfig);
+      CoreQueueConfiguration queueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
+      CoreQueueConfiguration forwardQueueConfig = new CoreQueueConfiguration()
+         .setAddress(RandomUtil.randomString())
+         .setName(RandomUtil.randomString())
+         .setDurable(false);
+
+      divertConfig = new DivertConfiguration()
+         .setName(RandomUtil.randomString())
+         .setRoutingName(RandomUtil.randomString())
+         .setAddress(queueConfig.getAddress())
+         .setForwardingAddress(forwardQueueConfig.getAddress())
+         .setExclusive(RandomUtil.randomBoolean());
+
+      Configuration conf = createBasicConfig()
+         .addQueueConfiguration(queueConfig)
+         .addQueueConfiguration(forwardQueueConfig)
+         .addDivertConfiguration(divertConfig)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()))
+         .addConnectorConfiguration(connectorConfig.getName(), connectorConfig);
 
       service = HornetQServers.newHornetQServer(conf, mbeanServer, false);
       service.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlTest.java
index 00d05d6..12add43 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlTest.java
@@ -40,6 +40,7 @@ import org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory;
 import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
+import org.hornetq.core.settings.impl.SlowConsumerPolicy;
 import org.hornetq.core.transaction.impl.XidImpl;
 import org.hornetq.tests.util.RandomUtil;
 import org.hornetq.tests.util.UnitTestCase;
@@ -101,8 +102,6 @@ public class HornetQServerControlTest extends ManagementTestBase
       Assert.assertEquals(conf.isClustered(), serverControl.isClustered());
       Assert.assertEquals(conf.isPersistDeliveryCountBeforeDelivery(),
                           serverControl.isPersistDeliveryCountBeforeDelivery());
-      Assert.assertEquals(conf.getHAPolicy().isBackup(), serverControl.isBackup());
-      Assert.assertEquals(conf.getHAPolicy().isSharedStore(), serverControl.isSharedStore());
       Assert.assertEquals(conf.getScheduledThreadPoolMaxSize(), serverControl.getScheduledThreadPoolMaxSize());
       Assert.assertEquals(conf.getThreadPoolMaxSize(), serverControl.getThreadPoolMaxSize());
       Assert.assertEquals(conf.getSecurityInvalidationInterval(), serverControl.getSecurityInvalidationInterval());
@@ -144,7 +143,6 @@ public class HornetQServerControlTest extends ManagementTestBase
       Assert.assertEquals(conf.getJournalCompactMinFiles(), serverControl.getJournalCompactMinFiles());
       Assert.assertEquals(conf.getJournalCompactPercentage(), serverControl.getJournalCompactPercentage());
       Assert.assertEquals(conf.isPersistenceEnabled(), serverControl.isPersistenceEnabled());
-      Assert.assertEquals(conf.getHAPolicy().isFailoverOnServerShutdown(), serverControl.isFailoverOnServerShutdown());
    }
 
    @Test
@@ -502,6 +500,9 @@ public class HornetQServerControlTest extends ManagementTestBase
       long redistributionDelay = 5;
       boolean sendToDLAOnNoRoute = true;
       String addressFullMessagePolicy = "PAGE";
+      long slowConsumerThreshold = 5;
+      long slowConsumerCheckPeriod = 10;
+      String slowConsumerPolicy = SlowConsumerPolicy.KILL.toString();
 
       serverControl.addAddressSettings(addressMatch,
                                        DLA,
@@ -517,7 +518,10 @@ public class HornetQServerControlTest extends ManagementTestBase
                                        maxRedeliveryDelay,
                                        redistributionDelay,
                                        sendToDLAOnNoRoute,
-                                       addressFullMessagePolicy);
+                                       addressFullMessagePolicy,
+                                       slowConsumerThreshold,
+                                       slowConsumerCheckPeriod,
+                                       slowConsumerPolicy);
 
 
       boolean ex = false;
@@ -537,7 +541,10 @@ public class HornetQServerControlTest extends ManagementTestBase
                                           maxRedeliveryDelay,
                                           redistributionDelay,
                                           sendToDLAOnNoRoute,
-                                          addressFullMessagePolicy);
+                                          addressFullMessagePolicy,
+                                          slowConsumerThreshold,
+                                          slowConsumerCheckPeriod,
+                                          slowConsumerPolicy);
       }
       catch (Exception expected)
       {
@@ -564,6 +571,9 @@ public class HornetQServerControlTest extends ManagementTestBase
       assertEquals(redistributionDelay, info.getRedistributionDelay());
       assertEquals(sendToDLAOnNoRoute, info.isSendToDLAOnNoRoute());
       assertEquals(addressFullMessagePolicy, info.getAddressFullMessagePolicy());
+      assertEquals(slowConsumerThreshold, info.getSlowConsumerThreshold());
+      assertEquals(slowConsumerCheckPeriod, info.getSlowConsumerCheckPeriod());
+      assertEquals(slowConsumerPolicy, info.getSlowConsumerPolicy());
 
       serverControl.addAddressSettings(addressMatch,
                                        DLA,
@@ -579,7 +589,10 @@ public class HornetQServerControlTest extends ManagementTestBase
                                        maxRedeliveryDelay,
                                        redistributionDelay,
                                        sendToDLAOnNoRoute,
-                                       addressFullMessagePolicy);
+                                       addressFullMessagePolicy,
+                                       slowConsumerThreshold,
+                                       slowConsumerCheckPeriod,
+                                       slowConsumerPolicy);
 
 
       jsonString = serverControl.getAddressSettingsAsJSON(exactAddress);
@@ -598,6 +611,9 @@ public class HornetQServerControlTest extends ManagementTestBase
       assertEquals(redistributionDelay, info.getRedistributionDelay());
       assertEquals(sendToDLAOnNoRoute, info.isSendToDLAOnNoRoute());
       assertEquals(addressFullMessagePolicy, info.getAddressFullMessagePolicy());
+      assertEquals(slowConsumerThreshold, info.getSlowConsumerThreshold());
+      assertEquals(slowConsumerCheckPeriod, info.getSlowConsumerCheckPeriod());
+      assertEquals(slowConsumerPolicy, info.getSlowConsumerPolicy());
 
 
       ex = false;
@@ -617,7 +633,10 @@ public class HornetQServerControlTest extends ManagementTestBase
                                           maxRedeliveryDelay,
                                           redistributionDelay,
                                           sendToDLAOnNoRoute,
-                                          addressFullMessagePolicy);
+                                          addressFullMessagePolicy,
+                                          slowConsumerThreshold,
+                                          slowConsumerCheckPeriod,
+                                          slowConsumerPolicy);
       }
       catch (Exception e)
       {
@@ -948,8 +967,85 @@ public class HornetQServerControlTest extends ManagementTestBase
 
       System.out.println("HornetQServerControlTest.testCommitPreparedTransactions");
    }
-   // Package protected ---------------------------------------------
 
+   @Test
+   public void testScaleDownWithConnector() throws Exception
+   {
+      scaleDown(new ScaleDownHandler()
+      {
+         @Override
+         public void scaleDown(HornetQServerControl control) throws Exception
+         {
+            control.scaleDown("server2-connector");
+         }
+      });
+   }
+
+   @Test
+   public void testScaleDownWithOutConnector() throws Exception
+   {
+      scaleDown(new ScaleDownHandler()
+      {
+         @Override
+         public void scaleDown(HornetQServerControl control) throws Exception
+         {
+            control.scaleDown(null);
+         }
+      });
+   }
+
+   protected void scaleDown(ScaleDownHandler handler) throws Exception
+   {
+      SimpleString address = new SimpleString("testQueue");
+      Configuration conf = createDefaultConfig(false, 2);
+      conf.setSecurityEnabled(false);
+      conf.getAcceptorConfigurations().clear();
+      HashMap<String, Object> params = new HashMap<String, Object>();
+      params.put("server-id", "2");
+      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params));
+      HornetQServer server2 = HornetQServers.newHornetQServer(conf, null, true);
+      this.conf.getConnectorConfigurations().clear();
+      this.conf.getConnectorConfigurations().put("server2-connector", new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY, params));
+      try
+      {
+         server2.start();
+         server.createQueue(address, address, null, true, false);
+         server2.createQueue(address, address, null, true, false);
+         ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
+         ClientSessionFactory csf = createSessionFactory(locator);
+         ClientSession session = csf.createSession();
+         ClientProducer producer = session.createProducer(address);
+         for (int i = 0; i < 100; i++)
+         {
+            ClientMessage message = session.createMessage(true);
+            message.getBodyBuffer().writeString("m" + i);
+            producer.send(message);
+         }
+
+         HornetQServerControl managementControl = createManagementControl();
+         handler.scaleDown(managementControl);
+         locator.close();
+         locator = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY, params));
+         csf = createSessionFactory(locator);
+         session = csf.createSession();
+         session.start();
+         ClientConsumer consumer = session.createConsumer(address);
+         for (int i = 0; i < 100; i++)
+         {
+            ClientMessage m = consumer.receive(5000);
+            assertNotNull(m);
+         }
+      }
+      finally
+      {
+         server2.stop();
+      }
+   }
+   // Package protected ---------------------------------------------
+   interface ScaleDownHandler
+   {
+      void scaleDown(HornetQServerControl control) throws Exception;
+   }
    // Protected -----------------------------------------------------
 
    @Override
@@ -964,13 +1060,13 @@ public class HornetQServerControlTest extends ManagementTestBase
                                                    params,
                                                    RandomUtil.randomString());
 
-      conf = createDefaultConfig(false);
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().clear();
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      conf = createDefaultConfig(false)
+         .setSecurityEnabled(false)
+         .setJMXManagementEnabled(true)
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()))
+         .addConnectorConfiguration(connectorConfig.getName(), connectorConfig);
       server = HornetQServers.newHornetQServer(conf, mbeanServer, true);
-      conf.getConnectorConfigurations().put(connectorConfig.getName(), connectorConfig);
       server.start();
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlUsingCoreTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlUsingCoreTest.java
index 42f2c7e..41051f0 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlUsingCoreTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/HornetQServerControlUsingCoreTest.java
@@ -96,6 +96,17 @@ public class HornetQServerControlUsingCoreTest extends HornetQServerControlTest
 
    }
 
+   // the core messaging proxy doesn't work when the server is stopped so we cant run these 2 tests
+   @Override
+   public void testScaleDownWithOutConnector() throws Exception
+   {
+   }
+
+   @Override
+   public void testScaleDownWithConnector() throws Exception
+   {
+   }
+
    @Override
    protected HornetQServerControl createManagementControl() throws Exception
    {
@@ -107,6 +118,12 @@ public class HornetQServerControlUsingCoreTest extends HornetQServerControlTest
 
          }
 
+         @Override
+         public void scaleDown(String connector) throws Exception
+         {
+            throw new UnsupportedOperationException();
+         }
+
          private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_SERVER);
 
          public boolean isSharedStore()
@@ -119,6 +136,16 @@ public class HornetQServerControlUsingCoreTest extends HornetQServerControlTest
             return (Boolean) proxy.invokeOperation("closeConnectionsForAddress", ipAddress);
          }
 
+         public boolean closeConsumerConnectionsForAddress(final String address) throws Exception
+         {
+            return (Boolean) proxy.invokeOperation("closeConsumerConnectionsForAddress", address);
+         }
+
+         public boolean closeConnectionsForUser(final String userName) throws Exception
+         {
+            return (Boolean) proxy.invokeOperation("closeConnectionsForUser", userName);
+         }
+
          public boolean commitPreparedTransaction(final String transactionAsBase64) throws Exception
          {
             return (Boolean) proxy.invokeOperation("commitPreparedTransaction", transactionAsBase64);
@@ -356,7 +383,7 @@ public class HornetQServerControlUsingCoreTest extends HornetQServerControlTest
 
          public void setScaleDown(boolean scaleDown) throws Exception
          {
-            proxy.invokeOperation("setScaleDown", scaleDown);
+            proxy.invokeOperation("setEnabled", scaleDown);
          }
 
          public boolean isScaleDown()
@@ -548,7 +575,10 @@ public class HornetQServerControlUsingCoreTest extends HornetQServerControlTest
                                         @Parameter(desc = "the maximum redelivery delay", name = "maxRedeliveryDelay") long maxRedeliveryDelay,
                                         @Parameter(desc = "the redistribution delay", name = "redistributionDelay") long redistributionDelay,
                                         @Parameter(desc = "do we send to the DLA when there is no where to route the message", name = "sendToDLAOnNoRoute") boolean sendToDLAOnNoRoute,
-                                        @Parameter(desc = "the policy to use when the address is full", name = "addressFullMessagePolicy") String addressFullMessagePolicy) throws Exception
+                                        @Parameter(desc = "the policy to use when the address is full", name = "addressFullMessagePolicy") String addressFullMessagePolicy,
+                                        @Parameter(desc = "when a consumer falls below this threshold in terms of messages consumed per second it will be considered 'slow'", name = "slowConsumerThreshold") long slowConsumerThreshold,
+                                        @Parameter(desc = "how often (in seconds) to check for slow consumers", name = "slowConsumerCheckPeriod") long slowConsumerCheckPeriod,
+                                        @Parameter(desc = "the policy to use when a slow consumer is detected", name = "slowConsumerPolicy") String slowConsumerPolicy) throws Exception
          {
             proxy.invokeOperation("addAddressSettings",
                                   addressMatch,
@@ -565,7 +595,10 @@ public class HornetQServerControlUsingCoreTest extends HornetQServerControlTest
                                   maxRedeliveryDelay,
                                   redistributionDelay,
                                   sendToDLAOnNoRoute,
-                                  addressFullMessagePolicy);
+                                  addressFullMessagePolicy,
+                                  slowConsumerThreshold,
+                                  slowConsumerCheckPeriod,
+                                  slowConsumerPolicy);
          }
 
          public void removeAddressSettings(String addressMatch) throws Exception

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/JMXDomainTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/JMXDomainTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/JMXDomainTest.java
index f1fe3a0..44d1eed 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/JMXDomainTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/JMXDomainTest.java
@@ -12,15 +12,10 @@
  */
 package org.hornetq.tests.integration.management;
 
-import org.junit.Test;
-
 import java.util.HashMap;
 import java.util.Map;
 
-import javax.management.ObjectName;
-
 import org.hornetq.api.config.HornetQDefaultConfiguration;
-import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.management.ObjectNameBuilder;
 import org.hornetq.core.config.Configuration;
@@ -28,45 +23,35 @@ import org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory;
 import org.hornetq.core.remoting.impl.invm.TransportConstants;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
+import org.junit.After;
+import org.junit.Test;
 
 /**
  * A JMXDomainTest
  *
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
- *
- *
  */
 public class JMXDomainTest extends ManagementTestBase
 {
-
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   // Public --------------------------------------------------------
+   HornetQServer server_0 = null;
+   HornetQServer server_1 = null;
 
    @Test
    public void test2HornetQServersManagedFrom1MBeanServer() throws Exception
    {
-
-      Configuration config_0 = createDefaultConfig();
-      config_0.setJMXManagementEnabled(true);
+      Configuration config_0 = createDefaultConfig()
+         .setJMXManagementEnabled(true);
 
       String jmxDomain_1 = HornetQDefaultConfiguration.getDefaultJmxDomain() + ".1";
 
-      Configuration config_1 = createBasicConfig();
       Map<String, Object> params = new HashMap<String, Object>();
       params.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-      config_1.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params));
-      config_1.setJMXDomain(jmxDomain_1);
-      config_1.setJMXManagementEnabled(true);
+      Configuration config_1 = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName(), params))
+         .setJMXDomain(jmxDomain_1);
 
-      HornetQServer server_0 = HornetQServers.newHornetQServer(config_0, mbeanServer, false);
-      HornetQServer server_1 = HornetQServers.newHornetQServer(config_1, mbeanServer, false);
+      server_0 = HornetQServers.newHornetQServer(config_0, mbeanServer, false);
+      server_1 = HornetQServers.newHornetQServer(config_1, mbeanServer, false);
 
       ObjectNameBuilder builder_0 = ObjectNameBuilder.DEFAULT;
       ObjectNameBuilder builder_1 = ObjectNameBuilder.create(jmxDomain_1);
@@ -93,94 +78,22 @@ public class JMXDomainTest extends ManagementTestBase
 
       checkNoResource(builder_0.getHornetQServerObjectName());
       checkNoResource(builder_1.getHornetQServerObjectName());
-
    }
 
-   @Test
-   public void testDefaultObjectName() throws Exception
+   @Override
+   @After
+   public void tearDown() throws Exception
    {
-      ObjectName objectName = ObjectNameBuilder.DEFAULT.getJMSServerObjectName();
-      ObjectName defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getJMSQueueObjectName("A");
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,jms-queue=\"A\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getAcceptorObjectName("netty");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,remote-acceptor=\"netty\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getAddressObjectName(new SimpleString("jms.queue.M"));
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,core-address=\"jms.queue.M\"");
-
-      assertEquals(defaultValue, objectName);
+      if (server_0 != null)
+      {
+         server_0.stop();
+      }
 
-      objectName = ObjectNameBuilder.DEFAULT.getBridgeObjectName("mybridge");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,bridge=\"mybridge\"");
+      if (server_1 != null)
+      {
+         server_1.stop();
+      }
 
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getBroadcastGroupObjectName("mybroadcastgroup");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,broadcast-group=\"mybroadcastgroup\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getClusterConnectionObjectName("my-cluster-connection");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,cluster-connection=\"my-cluster-connection\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getConnectionFactoryObjectName("connectionFactory");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,connection-factory=\"connectionFactory\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getDiscoveryGroupObjectName("my-discovery-group");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,discovery-group=\"my-discovery-group\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getDivertObjectName("my-divert");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,divert=\"my-divert\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getHornetQServerObjectName();
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getJMSTopicObjectName("my-topic");
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,jms-topic=\"my-topic\"");
-
-      assertEquals(defaultValue, objectName);
-
-      objectName = ObjectNameBuilder.DEFAULT.getQueueObjectName(new SimpleString("some.address"), new SimpleString("some.queue"));
-      System.out.println("value: " + objectName);
-      defaultValue = new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default,address=\"some.address\",runtime-queue=\"some.queue\"");
-
-      assertEquals(defaultValue, objectName);
+      super.tearDown();
    }
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementActivationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementActivationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementActivationTest.java
index 847f675..c672fbc 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementActivationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementActivationTest.java
@@ -83,7 +83,10 @@ public class ManagementActivationTest extends FailoverTestBase
       List<String> connectorNames = new ArrayList<String>();
       connectorNames.add(connectorName);
 
-      ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl("test", false, connectorNames, "/myConnectionFactory");
+      ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl()
+         .setName("test")
+         .setConnectorNames(connectorNames)
+         .setBindings("/myConnectionFactory");
       backupJmsServer.createConnectionFactory(true, config, "/myConnectionFactory");
 
       boolean exception = false;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementServiceImplTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementServiceImplTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementServiceImplTest.java
index 085c256..82ec49c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementServiceImplTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementServiceImplTest.java
@@ -46,8 +46,8 @@ public class ManagementServiceImplTest extends UnitTestCase
       String queue = RandomUtil.randomString();
       String address = RandomUtil.randomString();
 
-      Configuration conf = createBasicConfig();
-      conf.setJMXManagementEnabled(false);
+      Configuration conf = createBasicConfig()
+         .setJMXManagementEnabled(false);
 
       HornetQServer server = HornetQServers.newHornetQServer(conf, false);
       server.start();
@@ -66,8 +66,8 @@ public class ManagementServiceImplTest extends UnitTestCase
    @Test
    public void testHandleManagementMessageWithOperationWhichFails() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setJMXManagementEnabled(false);
+      Configuration conf = createBasicConfig()
+         .setJMXManagementEnabled(false);
 
       HornetQServer server = HornetQServers.newHornetQServer(conf, false);
       server.start();
@@ -86,8 +86,8 @@ public class ManagementServiceImplTest extends UnitTestCase
    @Test
    public void testHandleManagementMessageWithUnknowResource() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setJMXManagementEnabled(false);
+      Configuration conf = createBasicConfig()
+         .setJMXManagementEnabled(false);
 
       HornetQServer server = HornetQServers.newHornetQServer(conf, false);
       server.start();
@@ -106,8 +106,8 @@ public class ManagementServiceImplTest extends UnitTestCase
    @Test
    public void testHandleManagementMessageWithUnknownAttribute() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setJMXManagementEnabled(false);
+      Configuration conf = createBasicConfig()
+         .setJMXManagementEnabled(false);
 
       HornetQServer server = HornetQServers.newHornetQServer(conf, false);
       server.start();
@@ -127,8 +127,8 @@ public class ManagementServiceImplTest extends UnitTestCase
    @Test
    public void testHandleManagementMessageWithKnownAttribute() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setJMXManagementEnabled(false);
+      Configuration conf = createBasicConfig()
+         .setJMXManagementEnabled(false);
 
       HornetQServer server = HornetQServers.newHornetQServer(conf, false);
       server.start();
@@ -148,8 +148,8 @@ public class ManagementServiceImplTest extends UnitTestCase
    @Test
    public void testGetResources() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setJMXManagementEnabled(false);
+      Configuration conf = createBasicConfig()
+         .setJMXManagementEnabled(false);
       ManagementServiceImpl managementService = new ManagementServiceImpl(null, conf);
       managementService.setStorageManager(new NullStorageManager());
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementTestBase.java
index 2a4a762..5d2452a 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementTestBase.java
@@ -12,6 +12,7 @@
  */
 package org.hornetq.tests.integration.management;
 import org.hornetq.api.core.management.QueueControl;
+import org.hornetq.api.jms.management.JMSQueueControl;
 import org.junit.Before;
 import org.junit.After;
 
@@ -121,6 +122,29 @@ public abstract class ManagementTestBase extends ServiceTestBase
       return queueControl;
    }
 
+   protected long getMessageCount(JMSQueueControl control) throws Exception
+   {
+      control.flushExecutor();
+      return control.getMessageCount();
+   }
+
+   protected long getMessagesAdded(JMSQueueControl control) throws Exception
+   {
+      control.flushExecutor();
+      return control.getMessagesAdded();
+   }
+
+   protected long getMessageCount(QueueControl control) throws Exception
+   {
+      control.flushExecutor();
+      return control.getMessageCount();
+   }
+
+   protected long getMessagesAdded(QueueControl control) throws Exception
+   {
+      control.flushExecutor();
+      return control.getMessagesAdded();
+   }
 
    // Private -------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithPagingServerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithPagingServerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithPagingServerTest.java
index 9ecff90..53ea2bf 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithPagingServerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithPagingServerTest.java
@@ -198,11 +198,8 @@ public class ManagementWithPagingServerTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
 
       server = addServer(HornetQServers.newHornetQServer(conf, mbeanServer, true));
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithStompTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithStompTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithStompTest.java
index e2694a9..2bf9096 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithStompTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/ManagementWithStompTest.java
@@ -171,15 +171,15 @@ public class ManagementWithStompTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
       Map<String, Object> params = new HashMap<String, Object>();
-      params.put(TransportConstants.PROTOCOL_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
+      params.put(TransportConstants.PROTOCOLS_PROP_NAME, StompProtocolManagerFactory.STOMP_PROTOCOL_NAME);
       params.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_STOMP_PORT);
       TransportConfiguration stompTransport = new TransportConfiguration(NettyAcceptorFactory.class.getName(), params);
-      conf.getAcceptorConfigurations().add(stompTransport);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(stompTransport)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+
       server = HornetQServers.newHornetQServer(conf, mbeanServer, false, "brianm", "wombats");
 
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/NotificationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/NotificationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/NotificationTest.java
index 4c20a89..d0f7a8f 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/NotificationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/NotificationTest.java
@@ -36,10 +36,10 @@ import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-import static org.hornetq.api.core.management.NotificationType.BINDING_ADDED;
-import static org.hornetq.api.core.management.NotificationType.BINDING_REMOVED;
-import static org.hornetq.api.core.management.NotificationType.CONSUMER_CLOSED;
-import static org.hornetq.api.core.management.NotificationType.CONSUMER_CREATED;
+import static org.hornetq.api.core.management.CoreNotificationType.BINDING_ADDED;
+import static org.hornetq.api.core.management.CoreNotificationType.BINDING_REMOVED;
+import static org.hornetq.api.core.management.CoreNotificationType.CONSUMER_CLOSED;
+import static org.hornetq.api.core.management.CoreNotificationType.CONSUMER_CREATED;
 
 /**
  * A NotificationTest
@@ -252,11 +252,9 @@ public class NotificationTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      // the notifications are independent of JMX
-      conf.setJMXManagementEnabled(false);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration conf = createBasicConfig()
+         // the notifications are independent of JMX
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       service = HornetQServers.newHornetQServer(conf, false);
       service.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlTest.java
index c05fff5..31bea0f 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlTest.java
@@ -17,6 +17,8 @@ import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
+import javax.management.Notification;
+
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.SimpleString;
@@ -29,16 +31,20 @@ import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.client.MessageHandler;
 import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.DayCounterInfo;
 import org.hornetq.api.core.management.HornetQServerControl;
 import org.hornetq.api.core.management.MessageCounterInfo;
+import org.hornetq.api.core.management.ObjectNameBuilder;
 import org.hornetq.api.core.management.QueueControl;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.message.impl.MessageImpl;
 import org.hornetq.core.messagecounter.impl.MessageCounterManagerImpl;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
 import org.hornetq.core.server.Queue;
 import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.tests.integration.jms.server.management.JMSUtil;
 import org.hornetq.tests.util.RandomUtil;
 import org.hornetq.utils.json.JSONArray;
 import org.junit.After;
@@ -247,15 +253,15 @@ public class QueueControlTest extends ManagementTestBase
       session.createQueue(address, queue, null, false);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       ClientProducer producer = session.createProducer(address);
       producer.send(session.createMessage(false));
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       ManagementTestBase.consumeMessages(1, session, queue);
 
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       session.deleteQueue(queue);
    }
@@ -269,7 +275,7 @@ public class QueueControlTest extends ManagementTestBase
       session.createQueue(address, queue, null, false);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       // It's empty, so it's supposed to be like this
       assertEquals("[{}]", queueControl.getFirstMessageAsJSON());
@@ -291,17 +297,43 @@ public class QueueControlTest extends ManagementTestBase
       session.createQueue(address, queue, null, false);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(0, queueControl.getMessagesAdded());
+      Assert.assertEquals(0, getMessagesAdded(queueControl));
 
       ClientProducer producer = session.createProducer(address);
       producer.send(session.createMessage(false));
-      Assert.assertEquals(1, queueControl.getMessagesAdded());
+      Assert.assertEquals(1, getMessagesAdded(queueControl));
       producer.send(session.createMessage(false));
-      Assert.assertEquals(2, queueControl.getMessagesAdded());
+      Assert.assertEquals(2, getMessagesAdded(queueControl));
 
       ManagementTestBase.consumeMessages(2, session, queue);
 
-      Assert.assertEquals(2, queueControl.getMessagesAdded());
+      Assert.assertEquals(2, getMessagesAdded(queueControl));
+
+      session.deleteQueue(queue);
+   }
+
+   @Test
+   public void testGetMessagesAcknowledged() throws Exception
+   {
+      SimpleString address = RandomUtil.randomSimpleString();
+      SimpleString queue = RandomUtil.randomSimpleString();
+
+      session.createQueue(address, queue, null, false);
+
+      QueueControl queueControl = createManagementControl(address, queue);
+      Assert.assertEquals(0, queueControl.getMessagesAcknowledged());
+
+      ClientProducer producer = session.createProducer(address);
+      producer.send(session.createMessage(false));
+      ManagementTestBase.consumeMessages(1, session, queue);
+      Assert.assertEquals(1, queueControl.getMessagesAcknowledged());
+      producer.send(session.createMessage(false));
+      ManagementTestBase.consumeMessages(1, session, queue);
+      Assert.assertEquals(2, queueControl.getMessagesAcknowledged());
+
+//      ManagementTestBase.consumeMessages(2, session, queue);
+
+//      Assert.assertEquals(2, getMessagesAdded(queueControl));
 
       session.deleteQueue(queue);
    }
@@ -771,12 +803,12 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(message);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // moved all messages to otherQueue
       int movedMessagesCount = queueControl.moveMessages(null, otherQueue.toString());
       Assert.assertEquals(1, movedMessagesCount);
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       // check there is no message to consume from queue
       ManagementTestBase.consumeMessages(0, session, queue);
@@ -811,7 +843,7 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(message);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // moved all messages to unknown queue
       try
@@ -822,7 +854,7 @@ public class QueueControlTest extends ManagementTestBase
       catch (Exception e)
       {
       }
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       ManagementTestBase.consumeMessages(1, session, queue);
 
@@ -863,12 +895,12 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(unmatchingMessage);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // moved matching messages to otherQueue
       int movedMatchedMessagesCount = queueControl.moveMessages(key + " =" + matchingValue, otherQueue.toString());
       Assert.assertEquals(1, movedMatchedMessagesCount);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // consume the unmatched message from queue
       ClientConsumer consumer = session.createConsumer(queue);
@@ -908,8 +940,8 @@ public class QueueControlTest extends ManagementTestBase
 
       QueueControl queueControl = createManagementControl(address, queue);
       QueueControl otherQueueControl = createManagementControl(otherAddress, otherQueue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
-      Assert.assertEquals(0, otherQueueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
+      Assert.assertEquals(0, getMessageCount(otherQueueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -918,8 +950,8 @@ public class QueueControlTest extends ManagementTestBase
 
       boolean moved = queueControl.moveMessage(messageID, otherQueue.toString());
       Assert.assertTrue(moved);
-      Assert.assertEquals(1, queueControl.getMessageCount());
-      Assert.assertEquals(1, otherQueueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
+      Assert.assertEquals(1, getMessageCount(otherQueueControl));
 
       ManagementTestBase.consumeMessages(1, session, queue);
       ManagementTestBase.consumeMessages(1, session, otherQueue);
@@ -942,7 +974,7 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(session.createMessage(false));
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -958,7 +990,7 @@ public class QueueControlTest extends ManagementTestBase
       catch (Exception e)
       {
       }
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       ManagementTestBase.consumeMessages(1, session, queue);
 
@@ -995,12 +1027,12 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(unmatchingMessage);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // removed matching messages to otherQueue
       int removedMatchedMessagesCount = queueControl.removeMessages(key + " =" + matchingValue);
       Assert.assertEquals(1, removedMatchedMessagesCount);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // consume the unmatched message from queue
       ClientConsumer consumer = session.createConsumer(queue);
@@ -1040,12 +1072,12 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(unmatchingMessage);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // removed matching messages to otherQueue
       int removedMatchedMessagesCount = queueControl.removeMessages(5, key + " =" + matchingValue);
       Assert.assertEquals(1, removedMatchedMessagesCount);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // consume the unmatched message from queue
       ClientConsumer consumer = session.createConsumer(queue);
@@ -1077,12 +1109,12 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(session.createMessage(false));
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // removed matching messages to otherQueue
       int removedMatchedMessagesCount = queueControl.removeMessages(null);
       Assert.assertEquals(2, removedMatchedMessagesCount);
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       session.deleteQueue(queue);
    }
@@ -1101,12 +1133,12 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(session.createMessage(false));
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // removed matching messages to otherQueue
       int removedMatchedMessagesCount = queueControl.removeMessages("");
       Assert.assertEquals(2, removedMatchedMessagesCount);
-      Assert.assertEquals(0, queueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
 
       session.deleteQueue(queue);
    }
@@ -1125,7 +1157,7 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(session.createMessage(false));
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -1135,7 +1167,7 @@ public class QueueControlTest extends ManagementTestBase
       // delete 1st message
       boolean deleted = queueControl.removeMessage(messageID);
       Assert.assertTrue(deleted);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // check there is a single message to consume from queue
       ManagementTestBase.consumeMessages(1, session, queue);
@@ -1144,6 +1176,48 @@ public class QueueControlTest extends ManagementTestBase
    }
 
    @Test
+   public void testRemoveScheduledMessage() throws Exception
+   {
+      SimpleString address = RandomUtil.randomSimpleString();
+      SimpleString queue = RandomUtil.randomSimpleString();
+
+      session.createQueue(address, queue, null, false);
+      ClientProducer producer = session.createProducer(address);
+
+      // send 2 messages on queue, both scheduled
+      long timeout = System.currentTimeMillis() + 5000;
+      ClientMessage m1 = session.createMessage(true);
+      m1.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, timeout);
+      producer.send(m1);
+      ClientMessage m2 = session.createMessage(true);
+      m2.putLongProperty(MessageImpl.HDR_SCHEDULED_DELIVERY_TIME, timeout);
+      producer.send(m2);
+
+      QueueControl queueControl = createManagementControl(address, queue);
+      Assert.assertEquals(2, queueControl.getScheduledCount());
+
+      // the message IDs are set on the server
+      Map<String, Object>[] messages = queueControl.listScheduledMessages();
+      Assert.assertEquals(2, messages.length);
+      long messageID = (Long) messages[0].get("messageID");
+
+      // delete 1st message
+      boolean deleted = queueControl.removeMessage(messageID);
+      Assert.assertTrue(deleted);
+      Assert.assertEquals(1, queueControl.getScheduledCount());
+
+      // check there is a single message to consume from queue
+      while (timeout > System.currentTimeMillis() && queueControl.getScheduledCount() == 1)
+      {
+         Thread.sleep(100);
+      }
+
+      ManagementTestBase.consumeMessages(1, session, queue);
+
+      session.deleteQueue(queue);
+   }
+
+   @Test
    public void testRemoveMessage2() throws Exception
    {
       SimpleString address = RandomUtil.randomSimpleString();
@@ -1172,7 +1246,7 @@ public class QueueControlTest extends ManagementTestBase
       }
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(100, queueControl.getMessageCount());
+      Assert.assertEquals(100, getMessageCount(queueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -1183,7 +1257,7 @@ public class QueueControlTest extends ManagementTestBase
       // delete 1st message
       boolean deleted = queueControl.removeMessage(messageID);
       Assert.assertTrue(deleted);
-      Assert.assertEquals(99, queueControl.getMessageCount());
+      Assert.assertEquals(99, getMessageCount(queueControl));
 
       cons.close();
 
@@ -1216,7 +1290,7 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(matchingMessage);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(3, queueControl.getMessageCount());
+      Assert.assertEquals(3, getMessageCount(queueControl));
 
       Assert.assertEquals(2, queueControl.countMessages(key + " =" + matchingValue));
       Assert.assertEquals(1, queueControl.countMessages(key + " =" + unmatchingValue));
@@ -1264,7 +1338,7 @@ public class QueueControlTest extends ManagementTestBase
 
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(110, queueControl.getMessageCount());
+      Assert.assertEquals(110, getMessageCount(queueControl));
 
 
       Assert.assertEquals(0, queueControl.countMessages("nonExistentProperty like \'%Temp/88\'"));
@@ -1299,11 +1373,11 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(unmatchingMessage);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       int expiredMessagesCount = queueControl.expireMessages(key + " =" + matchingValue);
       Assert.assertEquals(1, expiredMessagesCount);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // consume the unmatched message from queue
       ClientConsumer consumer = session.createConsumer(queue);
@@ -1339,8 +1413,8 @@ public class QueueControlTest extends ManagementTestBase
 
       QueueControl queueControl = createManagementControl(address, queue);
       QueueControl expiryQueueControl = createManagementControl(expiryAddress, expiryQueue);
-      Assert.assertEquals(1, queueControl.getMessageCount());
-      Assert.assertEquals(0, expiryQueueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
+      Assert.assertEquals(0, getMessageCount(expiryQueueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -1350,8 +1424,8 @@ public class QueueControlTest extends ManagementTestBase
       queueControl.setExpiryAddress(expiryAddress.toString());
       boolean expired = queueControl.expireMessage(messageID);
       Assert.assertTrue(expired);
-      Assert.assertEquals(0, queueControl.getMessageCount());
-      Assert.assertEquals(1, expiryQueueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(queueControl));
+      Assert.assertEquals(1, getMessageCount(expiryQueueControl));
 
       ManagementTestBase.consumeMessages(0, session, queue);
       ManagementTestBase.consumeMessages(1, session, expiryQueue);
@@ -1379,7 +1453,7 @@ public class QueueControlTest extends ManagementTestBase
 
       QueueControl queueControl = createManagementControl(address, queue);
       QueueControl deadLetterQueueControl = createManagementControl(deadLetterAddress, deadLetterQueue);
-      Assert.assertEquals(2, queueControl.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(queueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -1388,11 +1462,11 @@ public class QueueControlTest extends ManagementTestBase
 
       queueControl.setDeadLetterAddress(deadLetterAddress.toString());
 
-      Assert.assertEquals(0, deadLetterQueueControl.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(deadLetterQueueControl));
       boolean movedToDeadLetterAddress = queueControl.sendMessageToDeadLetterAddress(messageID);
       Assert.assertTrue(movedToDeadLetterAddress);
-      Assert.assertEquals(1, queueControl.getMessageCount());
-      Assert.assertEquals(1, deadLetterQueueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
+      Assert.assertEquals(1, getMessageCount(deadLetterQueueControl));
 
       // check there is a single message to consume from queue
       ManagementTestBase.consumeMessages(1, session, queue);
@@ -1421,7 +1495,7 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(message);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -1455,7 +1529,7 @@ public class QueueControlTest extends ManagementTestBase
       producer.send(message);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(1, queueControl.getMessageCount());
+      Assert.assertEquals(1, getMessageCount(queueControl));
 
       // the message IDs are set on the server
       Map<String, Object>[] messages = queueControl.listMessages(null);
@@ -1834,25 +1908,89 @@ public class QueueControlTest extends ManagementTestBase
       session.createQueue(address, queue, null, false);
 
       QueueControl queueControl = createManagementControl(address, queue);
-      Assert.assertEquals(0, queueControl.getMessagesAdded());
+      Assert.assertEquals(0, getMessagesAdded(queueControl));
 
       ClientProducer producer = session.createProducer(address);
       producer.send(session.createMessage(false));
-      Assert.assertEquals(1, queueControl.getMessagesAdded());
+      Assert.assertEquals(1, getMessagesAdded(queueControl));
       producer.send(session.createMessage(false));
-      Assert.assertEquals(2, queueControl.getMessagesAdded());
+      Assert.assertEquals(2, getMessagesAdded(queueControl));
 
       ManagementTestBase.consumeMessages(2, session, queue);
 
-      Assert.assertEquals(2, queueControl.getMessagesAdded());
+      Assert.assertEquals(2, getMessagesAdded(queueControl));
 
       queueControl.resetMessagesAdded();
 
-      Assert.assertEquals(0, queueControl.getMessagesAdded());
+      Assert.assertEquals(0, getMessagesAdded(queueControl));
 
       session.deleteQueue(queue);
    }
 
+   @Test
+   public void testResetMessagesAcknowledged() throws Exception
+   {
+      SimpleString address = RandomUtil.randomSimpleString();
+      SimpleString queue = RandomUtil.randomSimpleString();
+
+      session.createQueue(address, queue, null, false);
+
+      QueueControl queueControl = createManagementControl(address, queue);
+      Assert.assertEquals(0, queueControl.getMessagesAcknowledged());
+
+      ClientProducer producer = session.createProducer(address);
+      producer.send(session.createMessage(false));
+      ManagementTestBase.consumeMessages(1, session, queue);
+      Assert.assertEquals(1, queueControl.getMessagesAcknowledged());
+      producer.send(session.createMessage(false));
+      ManagementTestBase.consumeMessages(1, session, queue);
+      Assert.assertEquals(2, queueControl.getMessagesAcknowledged());
+
+      queueControl.resetMessagesAcknowledged();
+
+      Assert.assertEquals(0, queueControl.getMessagesAcknowledged());
+
+      session.deleteQueue(queue);
+   }
+
+   //make sure notifications are always received no matter whether
+   //a Queue is created via QueueControl or by JMSServerManager directly.
+   @Test
+   public void testCreateQueueNotification() throws Exception
+   {
+      JMSUtil.JMXListener listener = new JMSUtil.JMXListener();
+      this.mbeanServer.addNotificationListener(ObjectNameBuilder.DEFAULT.getHornetQServerObjectName(), listener, null, null);
+
+      SimpleString testQueueName = new SimpleString("newQueue");
+      String testQueueName2 = "newQueue2";
+      this.server.createQueue(testQueueName,  testQueueName,  null,  false,  false);
+
+      Notification notif = listener.getNotification();
+
+      System.out.println("got notif: " + notif);
+      assertEquals(CoreNotificationType.BINDING_ADDED.toString(), notif.getType());
+
+      this.server.destroyQueue(testQueueName);
+
+      notif = listener.getNotification();
+      System.out.println("got notif: " + notif);
+      assertEquals(CoreNotificationType.BINDING_REMOVED.toString(), notif.getType());
+
+      HornetQServerControl control = ManagementControlHelper.createHornetQServerControl(mbeanServer);
+
+      control.createQueue(testQueueName2, testQueueName2);
+
+      notif = listener.getNotification();
+      System.out.println("got notif: " + notif);
+      assertEquals(CoreNotificationType.BINDING_ADDED.toString(), notif.getType());
+
+      control.destroyQueue(testQueueName2);
+
+      notif = listener.getNotification();
+      System.out.println("got notif: " + notif);
+      assertEquals(CoreNotificationType.BINDING_REMOVED.toString(), notif.getType());
+   }
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
@@ -1863,10 +2001,8 @@ public class QueueControlTest extends ManagementTestBase
    {
       super.setUp();
 
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(false);
-      conf.setJMXManagementEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
+      Configuration conf = createBasicConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
       server = addServer(HornetQServers.newHornetQServer(conf, mbeanServer, false));
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlUsingCoreTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlUsingCoreTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlUsingCoreTest.java
index 852da9f..4d6629b 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlUsingCoreTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/QueueControlUsingCoreTest.java
@@ -41,6 +41,19 @@ public class QueueControlUsingCoreTest extends QueueControlTest
       {
          private final CoreMessagingProxy proxy = new CoreMessagingProxy(session, ResourceNames.CORE_QUEUE + queue);
 
+         @Override
+         public void flushExecutor()
+         {
+            try
+            {
+               proxy.invokeOperation("flushExecutor");
+            }
+            catch (Exception e)
+            {
+               throw new RuntimeException(e.getMessage(), e);
+            }
+         }
+
          public boolean changeMessagePriority(final long messageID, final int newPriority) throws Exception
          {
             return (Boolean) proxy.invokeOperation("changeMessagePriority", messageID, newPriority);
@@ -106,11 +119,21 @@ public class QueueControlUsingCoreTest extends QueueControlTest
             return (Integer) proxy.retrieveAttributeValue("messagesAdded");
          }
 
+         public long getMessagesAcknowledged()
+         {
+            return (Integer) proxy.retrieveAttributeValue("messagesAcknowledged");
+         }
+
          public void resetMessagesAdded() throws Exception
          {
             proxy.invokeOperation("resetMessagesAdded");
          }
 
+         public void resetMessagesAcknowledged() throws Exception
+         {
+            proxy.invokeOperation("resetMessagesAcknowledged");
+         }
+
          public String getName()
          {
             return (String) proxy.retrieveAttributeValue("name");

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java
index b0ba06e..19efdaf 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithConfiguredAdminUserTest.java
@@ -88,9 +88,9 @@ public class SecurityManagementWithConfiguredAdminUserTest extends SecurityManag
    @Override
    protected HornetQServer setupAndStartHornetQServer() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setSecurityEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration conf = createBasicConfig()
+         .setSecurityEnabled(true)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       HornetQServer server = addServer(HornetQServers.newHornetQServer(conf, false));
       server.start();
       HierarchicalRepository<Set<Role>> securityRepository = server.getSecurityRepository();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java
index 2015d27..36a0889 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithDefaultConfigurationTest.java
@@ -56,10 +56,10 @@ public class SecurityManagementWithDefaultConfigurationTest extends SecurityMana
    @Override
    protected HornetQServer setupAndStartHornetQServer() throws Exception
    {
-      Configuration conf = createBasicConfig();
-      conf.setClusterPassword(HornetQDefaultConfiguration.getDefaultClusterPassword());
-      conf.setSecurityEnabled(true);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      Configuration conf = createBasicConfig()
+         .setClusterPassword(HornetQDefaultConfiguration.getDefaultClusterPassword())
+         .setSecurityEnabled(true)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       HornetQServer server = addServer(HornetQServers.newHornetQServer(conf, false));
       server.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java
index c6e6422..dbb0a36 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/management/SecurityManagementWithModifiedConfigurationTest.java
@@ -74,10 +74,10 @@ public class SecurityManagementWithModifiedConfigurationTest extends SecurityMan
    @Override
    protected HornetQServer setupAndStartHornetQServer() throws Exception
    {
-      ConfigurationImpl conf = createBasicConfig();
-      conf.setSecurityEnabled(true);
-      conf.setClusterPassword(configuredClusterPassword);
-      conf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
+      ConfigurationImpl conf = createBasicConfig()
+         .setSecurityEnabled(true)
+         .setClusterPassword(configuredClusterPassword)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
       HornetQServer server = HornetQServers.newHornetQServer(conf, false);
       server.start();
 


[51/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
ACTIVEMQ6-2 Update to HQ master


Project: http://git-wip-us.apache.org/repos/asf/activemq-6/repo
Commit: http://git-wip-us.apache.org/repos/asf/activemq-6/commit/177e6820
Tree: http://git-wip-us.apache.org/repos/asf/activemq-6/tree/177e6820
Diff: http://git-wip-us.apache.org/repos/asf/activemq-6/diff/177e6820

Branch: refs/heads/master
Commit: 177e6820b541e0a71b952eebf503a4d2235910c5
Parents: 8ecd255
Author: Martyn Taylor <mt...@redhat.com>
Authored: Mon Nov 10 16:14:12 2014 +0000
Committer: Andy Taylor <an...@gmail.com>
Committed: Tue Nov 11 10:48:14 2014 +0000

----------------------------------------------------------------------
 README.md                                       |   34 +-
 distribution/hornetq/pom.xml                    |  169 +-
 distribution/hornetq/src/main/assembly/dep.xml  |  519 +----
 .../hornetq/src/main/resources/bin/hornetq      |   87 +
 .../src/main/resources/bin/hornetq-service      |  138 ++
 .../hornetq/src/main/resources/bin/hornetq.cmd  |   58 +
 .../hornetq/src/main/resources/bin/run.bat      |   22 +-
 .../hornetq/src/main/resources/bin/run.sh       |   34 +-
 .../hornetq/src/main/resources/bin/stop.bat     |   10 +-
 .../hornetq/src/main/resources/bin/stop.sh      |    4 +-
 .../resources/config/clustered/bootstrap.xml    |   25 +
 .../config/clustered/hornetq-configuration.xml  |   94 +
 .../resources/config/clustered/hornetq-jms.xml  |   53 +
 .../config/clustered/hornetq-users.xml          |    7 +
 .../resources/config/clustered/jndi.properties  |    2 +
 .../clustered/hornetq-configuration.xml         |  122 --
 .../clustered/hornetq-jboss-beans.xml           |   62 -
 .../config/jboss-as-6/clustered/hornetq-jms.xml |   47 -
 .../config/jboss-as-6/clustered/jms-ds.xml      |   26 -
 .../non-clustered/hornetq-configuration.xml     |   97 -
 .../non-clustered/hornetq-jboss-beans.xml       |   61 -
 .../jboss-as-6/non-clustered/hornetq-jms.xml    |   46 -
 .../config/jboss-as-6/non-clustered/jms-ds.xml  |   26 -
 .../main/resources/config/logging.properties    |   56 +
 .../config/non-clustered/bootstrap.xml          |   25 +
 .../non-clustered/hornetq-configuration.xml     |   67 +
 .../config/non-clustered/hornetq-jms.xml        |   53 +
 .../config/non-clustered/hornetq-users.xml      |    7 +
 .../config/non-clustered/jndi.properties        |    2 +
 .../resources/config/replicated/bootstrap.xml   |   25 +
 .../config/replicated/hornetq-configuration.xml |  104 ++
 .../resources/config/replicated/hornetq-jms.xml |   53 +
 .../config/replicated/hornetq-users.xml         |    7 +
 .../resources/config/replicated/jndi.properties |    2 +
 .../resources/config/shared-store/bootstrap.xml |   25 +
 .../shared-store/hornetq-configuration.xml      |  104 ++
 .../config/shared-store/hornetq-jms.xml         |   53 +
 .../config/shared-store/hornetq-users.xml       |    7 +
 .../config/shared-store/jndi.properties         |    2 +
 .../stand-alone/clustered/hornetq-beans.xml     |   61 -
 .../clustered/hornetq-configuration.xml         |   94 -
 .../stand-alone/clustered/hornetq-jms.xml       |   53 -
 .../stand-alone/clustered/hornetq-users.xml     |    7 -
 .../stand-alone/clustered/jndi.properties       |    2 -
 .../stand-alone/clustered/logging.properties    |   56 -
 .../stand-alone/non-clustered/hornetq-beans.xml |   61 -
 .../non-clustered/hornetq-configuration.xml     |   67 -
 .../stand-alone/non-clustered/hornetq-jms.xml   |   53 -
 .../stand-alone/non-clustered/hornetq-users.xml |    7 -
 .../stand-alone/non-clustered/jndi.properties   |    2 -
 .../non-clustered/logging.properties            |   56 -
 .../stand-alone/replicated/hornetq-beans.xml    |   61 -
 .../replicated/hornetq-configuration.xml        |  101 -
 .../stand-alone/replicated/hornetq-jms.xml      |   53 -
 .../stand-alone/replicated/hornetq-users.xml    |    7 -
 .../stand-alone/replicated/jndi.properties      |    2 -
 .../stand-alone/replicated/logging.properties   |   56 -
 .../stand-alone/shared-store/hornetq-beans.xml  |   61 -
 .../shared-store/hornetq-configuration.xml      |  101 -
 .../stand-alone/shared-store/hornetq-jms.xml    |   53 -
 .../stand-alone/shared-store/hornetq-users.xml  |    7 -
 .../stand-alone/shared-store/jndi.properties    |    2 -
 .../stand-alone/shared-store/logging.properties |   56 -
 .../trunk/clustered-backup/hornetq-beans.xml    |   74 -
 .../clustered-backup/hornetq-configuration.xml  |   88 -
 .../trunk/clustered-backup/hornetq-jms.xml      |   28 -
 .../trunk/clustered-backup/hornetq-users.xml    |    7 -
 .../trunk/clustered-backup/jndi.properties      |   15 -
 .../trunk/clustered-backup/logging.properties   |   34 -
 .../config/trunk/clustered/hornetq-beans.xml    |   61 -
 .../trunk/clustered/hornetq-configuration.xml   |   73 -
 .../config/trunk/clustered/hornetq-jms.xml      |   28 -
 .../config/trunk/clustered/hornetq-users.xml    |    7 -
 .../config/trunk/clustered/jndi.properties      |    2 -
 .../config/trunk/clustered/logging.properties   |   34 -
 .../trunk/non-clustered/hornetq-beans.xml       |   60 -
 .../non-clustered/hornetq-configuration.xml     |   59 -
 .../config/trunk/non-clustered/hornetq-jms.xml  |   40 -
 .../trunk/non-clustered/hornetq-users.xml       |    7 -
 .../config/trunk/non-clustered/jndi.properties  |    2 -
 .../trunk/non-clustered/logging.properties      |   38 -
 .../examples/common/config/ant.properties       |    4 -
 distribution/jboss-mc/pom.xml                   |  123 --
 distribution/pom.xml                            |    1 -
 docs/quickstart-guide/en/running.xml            |   20 +-
 docs/user-manual/en/HornetQ_User_Manual.xml     |    1 +
 docs/user-manual/en/clusters.xml                |   30 +-
 docs/user-manual/en/configuring-transports.xml  |    4 +-
 docs/user-manual/en/core-bridges.xml            |   12 +-
 docs/user-manual/en/diagrams/ha-colocated.odg   |  Bin 0 -> 16917 bytes
 docs/user-manual/en/diagrams/ha-scaledown.odg   |  Bin 0 -> 15455 bytes
 docs/user-manual/en/examples.xml                |    5 +
 docs/user-manual/en/ha.xml                      |  587 +++++-
 docs/user-manual/en/images/ha-colocated.png     |  Bin 0 -> 19713 bytes
 docs/user-manual/en/images/ha-scaledown.png     |  Bin 0 -> 16525 bytes
 docs/user-manual/en/interoperability.xml        |   19 +
 docs/user-manual/en/management.xml              |   23 +-
 docs/user-manual/en/queue-attributes.xml        |   16 +-
 docs/user-manual/en/slow-consumers.xml          |   53 +
 docs/user-manual/en/using-core.xml              |   25 +-
 docs/user-manual/en/using-server.xml            |  262 +--
 docs/user-manual/user-manual.xpr                |    1 +
 etc/checkstyle.xml                              |   11 +
 examples/core/microcontainer/pom.xml            |   84 -
 examples/core/microcontainer/readme.html        |   82 -
 .../example/EmbeddedMicroContainerExample.java  |  108 --
 .../src/main/resources/hornetq-beans.xml        |   36 -
 .../main/resources/hornetq-configuration.xml    |   29 -
 .../main/resources/server0/hornetq-beans.xml    |   17 -
 .../main/resources/server0/hornetq-beans.xml    |   59 -
 examples/core/vertx-connector/pom.xml           |    2 +-
 .../main/resources/server0/hornetq-beans.xml    |   59 -
 .../src/test/resources/arquillian.xml           |    2 +-
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    6 +-
 .../jms/example/ClusteredGroupingExample.java   |   22 +-
 .../resources/hornetq/server0/hornetq-beans.xml |   60 -
 .../resources/hornetq/server1/hornetq-beans.xml |   59 -
 .../jms/colocated-failover-scale-down/pom.xml   |    2 +-
 .../colocated-failover-scale-down/readme.html   |   26 +-
 .../hornetq/server0/hornetq-configuration.xml   |   16 +-
 .../hornetq/server1/hornetq-configuration.xml   |   16 +-
 examples/jms/colocated-failover/readme.html     |   16 +-
 .../hornetq/server0/hornetq-configuration.xml   |   14 +-
 .../hornetq/server1/hornetq-configuration.xml   |   14 +-
 .../resources/hornetq/server0/hornetq-beans.xml |   59 -
 .../resources/hornetq/server0/hornetq-beans.xml |   60 -
 .../resources/hornetq/server0/hornetq-beans.xml |   60 -
 .../resources/hornetq/server0/hornetq-beans.xml |   60 -
 .../hornetq/server0/hornetq-configuration.xml   |   31 +-
 .../hornetq/server1/hornetq-configuration.xml   |   31 +-
 .../config/hornetq-example-beans.xml            |  165 --
 examples/jms/hornetq-ra-rar/pom.xml             |    2 +-
 .../src/main/resources/hornetq-beans.xml        |  234 ---
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    6 +-
 .../hornetq/server2/hornetq-configuration.xml   |    6 +-
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    6 +-
 .../hornetq/server2/hornetq-configuration.xml   |    6 +-
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    8 +-
 examples/jms/openwire/pom.xml                   |  125 ++
 examples/jms/openwire/readme.html               |   79 +
 .../hornetq/jms/example/OpenWireExample.java    |   96 +
 .../hornetq/server0/hornetq-configuration.xml   |   50 +
 .../resources/hornetq/server0/hornetq-jms.xml   |   19 +
 .../resources/hornetq/server0/hornetq-users.xml |    7 +
 examples/jms/proton-cpp/compile.sh              |    2 +
 examples/jms/proton-cpp/pom.xml                 |  135 ++
 examples/jms/proton-cpp/readme.html             |  104 ++
 examples/jms/proton-cpp/src/main/cpp/hello.cpp  |   72 +
 .../hornetq/server0/hornetq-configuration.xml   |   35 +
 .../resources/hornetq/server0/hornetq-jms.xml   |   10 +
 .../resources/hornetq/server0/hornetq-users.xml |    7 +
 examples/jms/proton-j/readme.html               |   11 +-
 .../org/hornetq/jms/example/ProtonJExample.java |    4 +-
 .../hornetq/server0/hornetq-configuration.xml   |    3 +-
 .../resources/hornetq/server0/hornetq-jms.xml   |    4 +
 .../jms/replicated-failback-static/readme.html  |    2 -
 .../hornetq/server0/hornetq-configuration.xml   |   12 +-
 .../hornetq/server1/hornetq-configuration.xml   |   12 +-
 .../hornetq/server0/hornetq-configuration.xml   |   12 +-
 .../hornetq/server1/hornetq-configuration.xml   |    8 +-
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    6 +-
 .../hornetq/server2/hornetq-configuration.xml   |    6 +-
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    8 +-
 examples/jms/scale-down/readme.html             |   18 +-
 .../hornetq/server0/hornetq-configuration.xml   |    8 +-
 .../hornetq/server1/hornetq-configuration.xml   |   13 +-
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    6 +-
 .../resources/hornetq/server0/hornetq-beans.xml |   59 -
 .../hornetq/server0/hornetq-configuration.xml   |    6 +-
 .../hornetq/server1/hornetq-configuration.xml   |    6 +-
 examples/jms/xa-with-jta/pom.xml                |    2 +-
 examples/soak/normal/README                     |   49 +-
 examples/soak/normal/build.xml                  |   92 -
 examples/soak/normal/pom.xml                    |  195 ++
 examples/soak/normal/server0/hornetq-beans.xml  |   40 -
 .../org/hornetq/jms/soak/example/SoakBase.java  |  129 ++
 .../hornetq/jms/soak/example/SoakParams.java    |  183 ++
 .../hornetq/jms/soak/example/SoakReceiver.java  |  244 +++
 .../hornetq/jms/soak/example/SoakSender.java    |  245 +++
 .../org/hornetq/jms/soak/example/SoakBase.java  |  134 --
 .../hornetq/jms/soak/example/SoakParams.java    |  183 --
 .../hornetq/jms/soak/example/SoakReceiver.java  |  235 ---
 .../hornetq/jms/soak/example/SoakSender.java    |  249 ---
 examples/soak/pom.xml                           |   29 +
 examples/soak/tx-restarts/README                |   29 -
 examples/soak/tx-restarts/build.bat             |   13 -
 examples/soak/tx-restarts/build.sh              |   15 -
 examples/soak/tx-restarts/build.xml             |   38 -
 .../tx-restarts/server0/client-jndi.properties  |    3 -
 .../soak/tx-restarts/server0/hornetq-beans.xml  |   59 -
 .../server0/hornetq-configuration.xml           |   65 -
 .../soak/tx-restarts/server0/hornetq-jms.xml    |   28 -
 .../soak/tx-restarts/server0/hornetq-users.xml  |    7 -
 .../soak/tx-restarts/server0/jndi.properties    |    2 -
 .../org/hornetq/jms/example/ClientAbstract.java |  277 ---
 .../src/org/hornetq/jms/example/Receiver.java   |  191 --
 .../src/org/hornetq/jms/example/Sender.java     |  128 --
 .../org/hornetq/jms/example/TXRestartSoak.java  |  179 --
 hornetq-bootstrap/pom.xml                       |   38 +-
 .../org/hornetq/cli/banner.txt                  |    8 +
 .../org/hornetq/cli/ConfigurationException.java |   21 +
 .../src/main/java/org/hornetq/cli/HornetQ.java  |   76 +
 .../java/org/hornetq/cli/commands/Action.java   |   20 +
 .../org/hornetq/cli/commands/ActionContext.java |   37 +
 .../org/hornetq/cli/commands/HelpAction.java    |   26 +
 .../main/java/org/hornetq/cli/commands/Run.java |  148 ++
 .../java/org/hornetq/cli/commands/Stop.java     |   45 +
 .../java/org/hornetq/factory/BrokerFactory.java |   52 +
 .../hornetq/factory/BrokerFactoryHandler.java   |   22 +
 .../java/org/hornetq/factory/CoreFactory.java   |   47 +
 .../org/hornetq/factory/CoreFactoryHandler.java |   22 +
 .../hornetq/factory/FileCoreFactoryHandler.java |   29 +
 .../hornetq/factory/FileJmsFactoryHandler.java  |   32 +
 .../java/org/hornetq/factory/JmsFactory.java    |   46 +
 .../org/hornetq/factory/JmsFactoryHandler.java  |   22 +
 .../hornetq/factory/SecurityManagerFactory.java |   38 +
 .../factory/XmlBrokerFactoryHandler.java        |   34 +
 .../bootstrap/HornetQBootstrapLogger.java       |    4 +
 .../bootstrap/HornetQBootstrapServer.java       |  284 ---
 .../services/org/hornetq/broker/core/file       |   13 +
 .../services/org/hornetq/broker/jms/file        |   13 +
 .../META-INF/services/org/hornetq/broker/xml    |   13 +
 .../main/java/org/hornetq/utils/ByteUtil.java   |   82 +
 .../java/org/hornetq/utils/FactoryFinder.java   |  166 ++
 .../org/hornetq/utils/HornetQThreadFactory.java |   42 +-
 .../java/org/hornetq/utils/TypedProperties.java |   67 +-
 .../main/java/org/hornetq/utils/UTF8Util.java   |    4 +-
 .../java/org/hornetq/utils/ByteUtilTest.java    |   52 +
 .../api/core/BroadcastEndpointFactory.java      |    4 +-
 .../api/core/BroadcastGroupConfiguration.java   |   34 +-
 .../api/core/DiscoveryGroupConfiguration.java   |   68 +-
 .../java/org/hornetq/api/core/Interceptor.java  |    2 +-
 .../JGroupsBroadcastGroupConfiguration.java     |   82 +-
 .../main/java/org/hornetq/api/core/Message.java |   22 +-
 .../api/core/TransportConfiguration.java        |   13 +-
 .../api/core/TransportConfigurationHelper.java  |   26 +
 .../core/UDPBroadcastGroupConfiguration.java    |   86 +-
 .../hornetq/api/core/client/ClientConsumer.java |    5 +-
 .../hornetq/api/core/client/ClientMessage.java  |  125 +-
 .../hornetq/api/core/client/ClientSession.java  |    5 +-
 .../api/core/client/ClientSessionFactory.java   |    3 +-
 .../hornetq/api/core/client/ServerLocator.java  |  110 +-
 .../core/management/AddressSettingsInfo.java    |   34 +-
 .../core/management/CoreNotificationType.java   |   54 +
 .../core/management/HornetQServerControl.java   |   26 +-
 .../api/core/management/ManagementHelper.java   |    4 +
 .../api/core/management/NotificationType.java   |   34 +-
 .../api/core/management/ObjectNameBuilder.java  |   84 +-
 .../api/core/management/QueueControl.java       |   20 +
 .../impl/ResetLimitWrappedHornetQBuffer.java    |   12 +-
 .../core/client/HornetQClientLogger.java        |    4 +
 .../core/client/HornetQClientMessageBundle.java |    5 +-
 .../core/client/impl/ClientConsumerImpl.java    |   43 +-
 .../client/impl/ClientConsumerInternal.java     |    6 +-
 .../client/impl/ClientLargeMessageImpl.java     |    4 +-
 .../core/client/impl/ClientMessageImpl.java     |  184 +-
 .../core/client/impl/ClientMessageInternal.java |    6 +-
 .../impl/ClientProducerCreditManager.java       |    3 +-
 .../impl/ClientProducerCreditManagerImpl.java   |    7 +-
 .../core/client/impl/ClientProducerCredits.java |    3 +-
 .../client/impl/ClientProducerCreditsImpl.java  |    9 +-
 .../core/client/impl/ClientProducerImpl.java    |    2 +-
 .../client/impl/ClientSessionFactoryImpl.java   |   88 +-
 .../impl/ClientSessionFactoryInternal.java      |    4 +-
 .../core/client/impl/ClientSessionImpl.java     |   83 +-
 .../core/client/impl/ClientSessionInternal.java |   12 +-
 .../core/client/impl/DelegatingSession.java     |   28 +-
 .../core/client/impl/HornetQXAResource.java     |   20 +
 .../core/client/impl/ServerLocatorImpl.java     |  171 +-
 .../core/client/impl/ServerLocatorInternal.java |   14 +-
 .../org/hornetq/core/client/impl/Topology.java  |    7 +-
 .../hornetq/core/cluster/DiscoveryGroup.java    |    6 +-
 .../hornetq/core/message/impl/MessageImpl.java  |   69 +-
 .../core/message/impl/MessageInternal.java      |    2 -
 .../org/hornetq/core/protocol/core/Channel.java |    5 +
 .../core/protocol/core/impl/ChannelImpl.java    |    7 +-
 .../core/impl/HornetQClientProtocolManager.java |  121 +-
 .../HornetQClientProtocolManagerFactory.java    |   18 +-
 .../core/impl/HornetQConsumerContext.java       |   54 +
 .../core/impl/HornetQSessionContext.java        |   53 +-
 .../core/impl/RemotingConnectionImpl.java       |  215 +--
 .../protocol/core/impl/wireformat/Ping.java     |    6 +-
 .../impl/wireformat/SessionSendMessage.java     |    6 +-
 .../impl/TransportConfigurationUtil.java        |   92 +
 .../impl/netty/HornetQAMQPFrameDecoder.java     |   41 +
 .../remoting/impl/netty/NettyConnection.java    |   67 +-
 .../remoting/impl/netty/NettyConnector.java     |   57 +-
 .../impl/netty/NettyConnectorFactory.java       |   11 +-
 .../core/remoting/impl/ssl/SSLSupport.java      |   30 +-
 .../org/hornetq/reader/BytesMessageUtil.java    |  233 +++
 .../java/org/hornetq/reader/MapMessageUtil.java |   59 +
 .../java/org/hornetq/reader/MessageUtil.java    |  201 ++
 .../org/hornetq/reader/StreamMessageUtil.java   |  300 +++
 .../org/hornetq/reader/TextMessageUtil.java     |   47 +
 .../java/org/hornetq/reader/package-info.java   |   21 +
 .../protocol/AbstractRemotingConnection.java    |  219 +++
 .../spi/core/protocol/ConnectionEntry.java      |    5 +
 .../spi/core/protocol/RemotingConnection.java   |    4 +
 .../spi/core/remoting/AbstractConnector.java    |   10 -
 .../core/remoting/ClientProtocolManager.java    |   18 +-
 .../remoting/ClientProtocolManagerFactory.java  |    7 +-
 .../hornetq/spi/core/remoting/Connection.java   |   34 +-
 .../hornetq/spi/core/remoting/Connector.java    |    2 -
 .../spi/core/remoting/ConnectorFactory.java     |    7 +-
 .../spi/core/remoting/ConsumerContext.java      |   22 +
 .../core/remoting/ProtocolResponseHandler.java  |   37 -
 .../spi/core/remoting/SessionContext.java       |   17 +-
 .../core/remoting/TopologyResponseHandler.java  |   37 +
 .../java/org/hornetq/utils/FutureLatch.java     |   14 +-
 hornetq-dto/pom.xml                             |  147 ++
 .../java/org/hornetq/dto/BasicSecurityDTO.java  |   23 +
 .../main/java/org/hornetq/dto/BrokerDTO.java    |   40 +
 .../src/main/java/org/hornetq/dto/CoreDTO.java  |   28 +
 .../src/main/java/org/hornetq/dto/JmsDTO.java   |   29 +
 .../main/java/org/hornetq/dto/NamingDTO.java    |   35 +
 .../main/java/org/hornetq/dto/SecurityDTO.java  |   26 +
 .../src/main/java/org/hornetq/dto/XmlUtil.java  |  106 ++
 .../main/java/org/hornetq/dto/package-info.java |   19 +
 .../main/resources/org/hornetq/dto/jaxb.index   |   19 +
 .../api/jms/management/JMSQueueControl.java     |    8 +
 .../api/jms/management/JMSServerControl.java    |   12 +
 .../hornetq/jms/client/HornetQBytesMessage.java |  155 +-
 .../hornetq/jms/client/HornetQConnection.java   |    3 +-
 .../hornetq/jms/client/HornetQMapMessage.java   |   17 +-
 .../org/hornetq/jms/client/HornetQMessage.java  |  133 +-
 .../jms/client/HornetQObjectMessage.java        |    2 +-
 .../org/hornetq/jms/client/HornetQQueue.java    |    2 +-
 .../jms/client/HornetQStreamMessage.java        |  270 +--
 .../hornetq/jms/client/HornetQTextMessage.java  |   15 +-
 hornetq-jms-server/pom.xml                      |    2 +-
 .../jms/bridge/HornetQJMSBridgeLogger.java      |  101 +
 .../hornetq/jms/bridge/impl/JMSBridgeImpl.java  |  305 +--
 .../management/impl/JMSQueueControlImpl.java    |    5 +
 .../management/impl/JMSServerControlImpl.java   |  179 +-
 .../management/impl/JMSTopicControlImpl.java    |   10 +-
 .../jms/server/HornetQJMSServerLogger.java      |   57 +-
 .../hornetq/jms/server/JMSServerManager.java    |    4 +
 .../config/ConnectionFactoryConfiguration.java  |   75 +-
 .../jms/server/config/JMSConfiguration.java     |   10 +-
 .../server/config/JMSQueueConfiguration.java    |    8 +
 .../jms/server/config/TopicConfiguration.java   |    4 +
 .../ConnectionFactoryConfigurationImpl.java     |  144 +-
 .../config/impl/JMSConfigurationImpl.java       |   50 +-
 .../config/impl/JMSQueueConfigurationImpl.java  |   42 +-
 .../config/impl/TopicConfigurationImpl.java     |   21 +-
 .../server/impl/JMSServerConfigParserImpl.java  |   93 +-
 .../jms/server/impl/JMSServerManagerImpl.java   |  254 ++-
 .../jms/server/impl/StandaloneNamingServer.java |    6 +
 .../server/management/JMSNotificationType.java  |   41 +
 .../journal/impl/AIOSequentialFileFactory.java  |    6 +-
 .../journal/impl/JournalFilesRepository.java    |   28 +-
 hornetq-protocols/hornetq-amqp-protocol/pom.xml |   35 +-
 .../HornetQAMQPProtocolMessageBundle.java       |   82 -
 .../proton/HornetQProtonRemotingConnection.java |  146 ++
 .../core/protocol/proton/ProtonConsumer.java    |  314 ----
 .../protocol/proton/ProtonDeliveryHandler.java  |   31 -
 .../core/protocol/proton/ProtonProducer.java    |  142 --
 .../protocol/proton/ProtonProtocolManager.java  |  292 +--
 .../proton/ProtonRemotingConnection.java        |  670 -------
 .../core/protocol/proton/ProtonSession.java     |  327 ----
 .../core/protocol/proton/ProtonUtils.java       |  633 -------
 .../protocol/proton/TransactionHandler.java     |   83 -
 .../proton/converter/HornetQJMSVendor.java      |  155 ++
 .../converter/ProtonMessageConverter.java       |   78 +
 .../converter/jms/ServerJMSBytesMessage.java    |  239 +++
 .../converter/jms/ServerJMSMapMessage.java      |  326 ++++
 .../proton/converter/jms/ServerJMSMessage.java  |  435 +++++
 .../converter/jms/ServerJMSStreamMessage.java   |  417 +++++
 .../converter/jms/ServerJMSTextMessage.java     |  112 ++
 .../proton/converter/jms/package-info.java      |   21 +
 .../proton/exceptions/HornetQAMQPException.java |   40 -
 .../HornetQAMQPIllegalStateException.java       |   28 -
 .../HornetQAMQPInternalErrorException.java      |   28 -
 .../HornetQAMQPInvalidFieldException.java       |   28 -
 .../HornetQAMQPNotImplementedException.java     |   28 -
 .../plug/HornetQProtonConnectionCallback.java   |  125 ++
 .../plug/ProtonSessionIntegrationCallback.java  |  341 ++++
 .../core/protocol/proton/plug/package-info.java |   18 +
 .../protocol/proton/sasl/HornetQPlainSASL.java  |   50 +
 .../core/protocol/proton/TestConversions.java   |  841 +++++++++
 .../hornetq-openwire-protocol/pom.xml           |   49 +
 .../protocol/openwire/AMQConnectorImpl.java     |  121 ++
 .../protocol/openwire/AMQTransactionImpl.java   |   74 +
 .../core/protocol/openwire/BrokerState.java     |   23 +
 .../protocol/openwire/DataInputWrapper.java     |  257 +++
 .../openwire/NotEnoughBytesException.java       |   21 +
 .../protocol/openwire/OpenWireConnection.java   | 1765 ++++++++++++++++++
 .../openwire/OpenWireMessageConverter.java      |  787 ++++++++
 .../openwire/OpenWireProtocolManager.java       |  756 ++++++++
 .../OpenWireProtocolManagerFactory.java         |   46 +
 .../core/protocol/openwire/OpenWireUtil.java    |   57 +
 .../core/protocol/openwire/SendingResult.java   |   63 +
 .../amq/AMQAbstractDeadLetterStrategy.java      |  107 ++
 .../openwire/amq/AMQBrokerStoppedException.java |   41 +
 .../openwire/amq/AMQConnectionContext.java      |  393 ++++
 .../protocol/openwire/amq/AMQConnector.java     |   70 +
 .../openwire/amq/AMQConnectorStatistics.java    |  116 ++
 .../core/protocol/openwire/amq/AMQConsumer.java |  390 ++++
 .../openwire/amq/AMQConsumerBrokerExchange.java |   89 +
 .../openwire/amq/AMQDeadLetterStrategy.java     |   65 +
 .../protocol/openwire/amq/AMQDestination.java   |  240 +++
 .../openwire/amq/AMQDestinationStatistics.java  |  228 +++
 .../AMQMapTransportConnectionStateRegister.java |  147 ++
 .../amq/AMQMessageAuthorizationPolicy.java      |   28 +
 .../protocol/openwire/amq/AMQMessageStore.java  |   18 +
 .../openwire/amq/AMQPersistenceAdapter.java     |   58 +
 .../core/protocol/openwire/amq/AMQProducer.java |   33 +
 .../openwire/amq/AMQProducerBrokerExchange.java |  264 +++
 .../openwire/amq/AMQSecurityContext.java        |   91 +
 .../openwire/amq/AMQServerConsumer.java         |  183 ++
 .../protocol/openwire/amq/AMQServerSession.java |  451 +++++
 .../openwire/amq/AMQServerSessionFactory.java   |   50 +
 .../core/protocol/openwire/amq/AMQSession.java  |  590 ++++++
 .../amq/AMQSharedDeadLetterStrategy.java        |   55 +
 ...QSingleTransportConnectionStateRegister.java |  183 ++
 .../openwire/amq/AMQSlowConsumerStrategy.java   |   39 +
 .../protocol/openwire/amq/AMQSubscription.java  |  241 +++
 .../openwire/amq/AMQSubscriptionRecovery.java   |   42 +
 .../protocol/openwire/amq/AMQTransaction.java   |  249 +++
 .../openwire/amq/AMQTransactionFactory.java     |   29 +
 .../amq/AMQTransportConnectionState.java        |   86 +
 .../AMQTransportConnectionStateRegister.java    |   58 +
 .../protocol/openwire/amq/BrowserListener.java  |   18 +
 .../core/protocol/openwire/amq/MessageInfo.java |   47 +
 ...etq.spi.core.protocol.ProtocolManagerFactory |    1 +
 hornetq-protocols/hornetq-proton-plug/pom.xml   |   80 +
 .../plug/AMQPClientConnectionContext.java       |   34 +
 .../proton/plug/AMQPClientReceiverContext.java  |   29 +
 .../proton/plug/AMQPClientSenderContext.java    |   25 +
 .../proton/plug/AMQPClientSessionContext.java   |   27 +
 .../org/proton/plug/AMQPConnectionCallback.java |   41 +
 .../org/proton/plug/AMQPConnectionContext.java  |   68 +
 .../plug/AMQPConnectionContextFactory.java      |   26 +
 .../plug/AMQPServerConnectionContext.java       |   22 +
 .../org/proton/plug/AMQPSessionCallback.java    |   85 +
 .../org/proton/plug/AMQPSessionContext.java     |   35 +
 .../main/java/org/proton/plug/ClientSASL.java   |   24 +
 .../main/java/org/proton/plug/SASLResult.java   |   25 +
 .../main/java/org/proton/plug/ServerSASL.java   |   25 +
 .../plug/context/AbstractConnectionContext.java |  282 +++
 .../context/AbstractProtonContextSender.java    |  154 ++
 .../context/AbstractProtonReceiverContext.java  |   67 +
 .../context/AbstractProtonSessionContext.java   |  189 ++
 .../plug/context/ProtonDeliveryHandler.java     |   31 +
 .../plug/context/ProtonInitializable.java       |   83 +
 .../proton/plug/context/ProtonPlugSender.java   |   27 +
 .../plug/context/ProtonTransactionHandler.java  |  134 ++
 .../client/ProtonClientConnectionContext.java   |   97 +
 .../ProtonClientConnectionContextFactory.java   |   39 +
 .../context/client/ProtonClientContext.java     |   82 +
 .../client/ProtonClientReceiverContext.java     |   89 +
 .../client/ProtonClientSessionContext.java      |   91 +
 .../server/ProtonServerConnectionContext.java   |   76 +
 .../ProtonServerConnectionContextFactory.java   |   38 +
 .../server/ProtonServerReceiverContext.java     |  159 ++
 .../server/ProtonServerSenderContext.java       |  283 +++
 .../server/ProtonServerSessionContext.java      |  124 ++
 .../plug/exceptions/HornetQAMQPException.java   |   45 +
 .../HornetQAMQPIllegalStateException.java       |   28 +
 .../HornetQAMQPInternalErrorException.java      |   33 +
 .../HornetQAMQPInvalidFieldException.java       |   28 +
 .../HornetQAMQPNotImplementedException.java     |   28 +
 .../exceptions/HornetQAMQPTimeoutException.java |   29 +
 .../org/proton/plug/handler/EventHandler.java   |   80 +
 .../java/org/proton/plug/handler/Events.java    |  109 ++
 .../org/proton/plug/handler/ProtonHandler.java  |  134 ++
 .../plug/handler/impl/DefaultEventHandler.java  |  167 ++
 .../plug/handler/impl/ProtonHandlerImpl.java    |  423 +++++
 .../HornetQAMQPProtocolMessageBundle.java       |   83 +
 .../proton/plug/sasl/AnonymousServerSASL.java   |   41 +
 .../org/proton/plug/sasl/ClientSASLPlain.java   |   62 +
 .../org/proton/plug/sasl/PlainSASLResult.java   |   51 +
 .../org/proton/plug/sasl/ServerSASLPlain.java   |   75 +
 .../java/org/proton/plug/util/ByteUtil.java     |  152 ++
 .../java/org/proton/plug/util/CodecCache.java   |   56 +
 .../org/proton/plug/util/CreditsSemaphore.java  |  134 ++
 .../java/org/proton/plug/util/DebugInfo.java    |   23 +
 .../java/org/proton/plug/util/DeliveryUtil.java |   49 +
 .../org/proton/plug/util/FutureRunnable.java    |   70 +
 .../org/proton/plug/util/NettyWritable.java     |  120 ++
 .../proton/plug/util/ProtonServerMessage.java   |  596 ++++++
 .../org/proton/plug/util/ReusableLatch.java     |  156 ++
 .../org/proton/plug/test/AbstractJMSTest.java   |  135 ++
 .../java/org/proton/plug/test/Constants.java    |   23 +
 .../java/org/proton/plug/test/ProtonTest.java   |  372 ++++
 .../plug/test/invm/InVMTestConnector.java       |   38 +
 .../proton/plug/test/invm/ProtonINVMSPI.java    |  209 +++
 .../plug/test/minimalclient/AMQPClientSPI.java  |  121 ++
 .../plug/test/minimalclient/Connector.java      |   27 +
 .../test/minimalclient/SimpleAMQPConnector.java |   84 +
 .../plug/test/minimalserver/DumbServer.java     |   59 +
 .../minimalserver/MinimalConnectionSPI.java     |  151 ++
 .../plug/test/minimalserver/MinimalServer.java  |  184 ++
 .../test/minimalserver/MinimalSessionSPI.java   |  219 +++
 .../SimpleServerThreadFactory.java              |   90 +
 .../proton/plug/test/sasl/PlainSASLTest.java    |   39 +
 .../plug/test/util/CreditsSemaphoreTest.java    |  149 ++
 .../plug/test/util/ReusableLatchTest.java       |  335 ++++
 .../test/util/SimpleServerAbstractTest.java     |   79 +
 .../core/protocol/stomp/StompDecoder.java       |    2 +
 .../hornetq/core/protocol/stomp/StompFrame.java |   42 +-
 .../protocol/stomp/StompProtocolManager.java    |   22 +-
 .../core/protocol/stomp/StompSession.java       |   25 +-
 .../stomp/v11/StompFrameHandlerV11.java         |   32 +-
 .../core/protocol/stomp/v11/StompFrameV11.java  |    4 +-
 .../stomp/v12/StompFrameHandlerV12.java         |   32 +-
 .../core/protocol/stomp/v12/StompFrameV12.java  |   49 +-
 hornetq-protocols/pom.xml                       |    4 +-
 hornetq-ra/pom.xml                              |   15 +
 .../hornetq/ra/HornetQRAManagedConnection.java  |   10 +-
 .../java/org/hornetq/ra/HornetQRASession.java   |   16 +
 .../hornetq/ra/HornetQRASessionFactoryImpl.java |    4 +-
 .../org/hornetq/ra/HornetQRAXAResource.java     |    9 +-
 .../org/hornetq/ra/HornetQResourceAdapter.java  |   55 +-
 .../hornetq/ra/HornetQXAResourceWrapper.java    |  143 ++
 .../hornetq/ra/inflow/HornetQActivation.java    |   27 +-
 .../ra/inflow/HornetQActivationSpec.java        |   49 +-
 .../ra/inflow/HornetQMessageHandler.java        |   23 +-
 .../java/org/hornetq/rest/test/Embedded.java    |    8 +-
 .../test/PersistentPushQueueConsumerTest.java   |    8 +-
 .../test/PersistentPushTopicConsumerTest.java   |    8 +-
 .../java/org/hornetq/rest/test/RawAckTest.java  |    8 +-
 .../selector/filter/BinaryExpression.java       |   34 +-
 .../selector/filter/ConstantExpression.java     |   27 +-
 .../selector/filter/UnaryExpression.java        |   28 +-
 .../hornetq/selector/SelectorParserTest.java    |   20 +-
 .../java/org/hornetq/selector/SelectorTest.java |   32 +-
 hornetq-server/pom.xml                          |    5 -
 .../core/config/BridgeConfiguration.java        |  184 +-
 .../config/ClusterConnectionConfiguration.java  |  306 ++-
 .../org/hornetq/core/config/Configuration.java  |  266 ++-
 .../hornetq/core/config/ConfigurationUtils.java |  110 +-
 .../config/ConnectorServiceConfiguration.java   |   34 +-
 .../core/config/CoreQueueConfiguration.java     |   28 +-
 .../core/config/DivertConfiguration.java        |   58 +-
 .../core/config/HAPolicyConfiguration.java      |   30 +
 .../core/config/ScaleDownConfiguration.java     |   93 +
 .../config/ha/ColocatedPolicyConfiguration.java |  149 ++
 .../config/ha/LiveOnlyPolicyConfiguration.java  |   46 +
 .../config/ha/ReplicaPolicyConfiguration.java   |  124 ++
 .../ha/ReplicatedPolicyConfiguration.java       |   68 +
 .../SharedStoreMasterPolicyConfiguration.java   |   55 +
 .../ha/SharedStoreSlavePolicyConfiguration.java |   96 +
 .../core/config/impl/ConfigurationImpl.java     |  639 ++++---
 .../hornetq/core/config/impl/Validators.java    |   14 +
 .../deployers/impl/FileConfigurationParser.java |  694 ++++---
 .../impl/HornetQServerControlImpl.java          |  279 ++-
 .../core/management/impl/QueueControlImpl.java  |   47 +
 .../core/messagecounter/MessageCounter.java     |    6 +-
 .../org/hornetq/core/paging/PagingManager.java  |   20 +-
 .../org/hornetq/core/paging/PagingStore.java    |    2 +-
 .../cursor/impl/PageCursorProviderImpl.java     |    4 +-
 .../paging/cursor/impl/PagePositionImpl.java    |   12 +-
 .../impl/PageSubscriptionCounterImpl.java       |    2 +-
 .../cursor/impl/PageSubscriptionImpl.java       |    5 +-
 .../core/paging/impl/PagingStoreImpl.java       |    4 +-
 .../core/persistence/StorageManager.java        |   23 +-
 .../impl/journal/DescribeJournal.java           |   26 +-
 .../impl/journal/JournalStorageManager.java     |   75 +-
 .../impl/journal/LargeServerMessageInSync.java  |    7 +-
 .../impl/nullpm/NullStorageManager.java         |    6 +-
 .../org/hornetq/core/postoffice/QueueInfo.java  |   23 +-
 .../core/postoffice/impl/BindingsImpl.java      |   29 +
 .../postoffice/impl/DuplicateIDCacheImpl.java   |   17 +-
 .../core/postoffice/impl/PostOfficeImpl.java    |   47 +-
 .../postoffice/impl/SimpleAddressManager.java   |    4 +-
 .../hornetq/core/protocol/ProtocolHandler.java  |   33 +-
 .../protocol/core/impl/CoreProtocolManager.java |   45 +-
 .../protocol/core/impl/CoreSessionCallback.java |   26 +-
 .../core/impl/HornetQPacketHandler.java         |   17 +-
 .../impl/wireformat/BackupRequestMessage.java   |   43 +-
 .../wireformat/ReplicationSyncFileMessage.java  |    2 +-
 .../core/remoting/impl/invm/InVMAcceptor.java   |    6 +-
 .../core/remoting/impl/invm/InVMConnection.java |   40 +-
 .../core/remoting/impl/invm/InVMConnector.java  |   23 +-
 .../impl/invm/InVMConnectorFactory.java         |   14 +-
 .../remoting/impl/invm/TransportConstants.java  |    3 +
 .../core/remoting/impl/netty/NettyAcceptor.java |    7 +-
 .../server/impl/RemotingServiceImpl.java        |   97 +-
 .../core/replication/ReplicatedJournal.java     |    4 +-
 .../replication/ReplicatedLargeMessage.java     |   20 +-
 .../core/replication/ReplicationEndpoint.java   |   13 +-
 .../core/replication/ReplicationManager.java    |   29 +-
 .../hornetq/core/security/SecurityStore.java    |    2 +
 .../core/security/impl/SecurityStoreImpl.java   |   14 +-
 .../hornetq/core/server/ActivateCallback.java   |   15 +
 .../core/server/HornetQMessageBundle.java       |   12 +
 .../org/hornetq/core/server/HornetQServer.java  |   49 +-
 .../core/server/HornetQServerLogger.java        |   39 +-
 .../org/hornetq/core/server/NodeManager.java    |   11 -
 .../java/org/hornetq/core/server/Queue.java     |   43 +-
 .../org/hornetq/core/server/ServerConsumer.java |   28 +-
 .../org/hornetq/core/server/ServerMessage.java  |    2 +-
 .../org/hornetq/core/server/ServerSession.java  |    4 +-
 .../core/server/ServerSessionFactory.java       |   41 +
 .../core/server/cluster/BackupManager.java      |   11 +-
 .../core/server/cluster/ClusterControl.java     |    4 +-
 .../core/server/cluster/ClusterController.java  |   99 +-
 .../core/server/cluster/ClusterManager.java     |   40 +-
 ...HornetQServerSideProtocolManagerFactory.java |   55 +
 .../core/server/cluster/ha/BackupPolicy.java    |   61 +
 .../server/cluster/ha/ColocatedHAManager.java   |  313 ++++
 .../core/server/cluster/ha/ColocatedPolicy.java |  187 ++
 .../core/server/cluster/ha/HAManager.java       |  560 +-----
 .../core/server/cluster/ha/HAPolicy.java        |  342 +---
 .../server/cluster/ha/HAPolicyTemplate.java     |  118 --
 .../core/server/cluster/ha/LiveOnlyPolicy.java  |   85 +
 .../core/server/cluster/ha/ReplicaPolicy.java   |  136 ++
 .../server/cluster/ha/ReplicatedPolicy.java     |  167 ++
 .../core/server/cluster/ha/ScaleDownPolicy.java |  164 ++
 .../cluster/ha/SharedStoreMasterPolicy.java     |  111 ++
 .../cluster/ha/SharedStoreSlavePolicy.java      |  110 ++
 .../server/cluster/ha/StandaloneHAManager.java  |   56 +
 .../core/server/cluster/impl/BridgeImpl.java    |   14 +-
 .../server/cluster/impl/BroadcastGroupImpl.java |    6 +-
 .../cluster/impl/ClusterConnectionBridge.java   |  110 +-
 .../cluster/impl/ClusterConnectionImpl.java     |   23 +-
 .../core/server/cluster/qourum/Quorum.java      |    2 +-
 .../group/impl/GroupHandlingAbstract.java       |    4 +-
 .../impl/GroupingHandlerConfiguration.java      |  102 +-
 .../server/group/impl/LocalGroupingHandler.java |   20 +-
 .../group/impl/RemoteGroupingHandler.java       |    9 +-
 .../hornetq/core/server/impl/Activation.java    |  118 ++
 .../impl/BackupRecoveryJournalLoader.java       |    6 +-
 .../core/server/impl/ColocatedActivation.java   |  331 ++++
 .../core/server/impl/ConnectorsService.java     |   64 +-
 .../hornetq/core/server/impl/DivertImpl.java    |    4 +-
 .../core/server/impl/HornetQServerImpl.java     | 1568 +++-------------
 .../core/server/impl/LiveActivation.java        |   17 +
 .../core/server/impl/LiveOnlyActivation.java    |  197 ++
 .../NamedLiveNodeLocatorForReplication.java     |    2 +-
 .../server/impl/PostOfficeJournalLoader.java    |    2 +-
 .../org/hornetq/core/server/impl/QueueImpl.java |  431 +++--
 .../hornetq/core/server/impl/RefsOperation.java |  218 +++
 .../core/server/impl/ReplicationError.java      |    2 +-
 .../core/server/impl/ScaleDownHandler.java      |   86 +-
 .../core/server/impl/ServerConsumerImpl.java    |  104 +-
 .../core/server/impl/ServerMessageImpl.java     |   31 +-
 .../core/server/impl/ServerSessionImpl.java     |  284 ++-
 .../core/server/impl/ServiceRegistry.java       |  128 ++
 .../impl/SharedNothingBackupActivation.java     |  498 +++++
 .../impl/SharedNothingLiveActivation.java       |  486 +++++
 .../impl/SharedStoreBackupActivation.java       |  276 +++
 .../server/impl/SharedStoreLiveActivation.java  |  100 +
 .../management/impl/ManagementServiceImpl.java  |    4 +-
 .../core/settings/impl/AddressSettings.java     |  118 +-
 .../org/hornetq/core/settings/impl/Match.java   |   11 +-
 .../core/settings/impl/SlowConsumerPolicy.java  |   24 +
 .../hornetq/core/transaction/Transaction.java   |    4 +
 .../core/transaction/TransactionFactory.java    |   25 +
 .../impl/BindingsTransactionImpl.java           |    7 +
 .../core/transaction/impl/TransactionImpl.java  |   15 +-
 .../spi/core/protocol/MessageConverter.java     |   27 +
 .../spi/core/protocol/ProtocolManager.java      |    7 +
 .../spi/core/protocol/SessionCallback.java      |   12 +-
 .../org/hornetq/security/basic-security         |   13 +
 .../resources/schema/hornetq-configuration.xsd  |  508 ++++-
 .../core/config/impl/ConfigurationImplTest.java |    9 +-
 .../impl/DefaultsFileConfigurationTest.java     |   31 +-
 .../impl/FileConfigurationParserTest.java       |    2 -
 .../core/config/impl/FileConfigurationTest.java |   47 +-
 .../config/impl/HAPolicyConfigurationTest.java  |  434 +++++
 .../group/impl/ClusteredResetMockTest.java      |    3 +-
 .../core/server/impl/EmbeddedServerTest.java    |   10 +-
 .../impl/ScheduledDeliveryHandlerTest.java      |   73 +-
 .../core/settings/AddressSettingsTest.java      |  146 ++
 .../hornetq/core/settings/RepositoryTest.java   |  281 +++
 .../tests/util/ColocatedHornetQServer.java      |    4 +-
 .../tests/util/InVMNodeManagerServer.java       |    3 +-
 .../org/hornetq/tests/util/ServiceTestBase.java |   33 +-
 .../tests/util/SingleServerTestBase.java        |    4 +-
 .../org/hornetq/tests/util/UnitTestCase.java    |  164 +-
 .../resources/ConfigurationTest-full-config.xml |   45 +-
 .../resources/colocated-hapolicy-config.xml     |   34 +
 .../resources/colocated-hapolicy-config2.xml    |   28 +
 .../resources/live-only-hapolicy-config.xml     |   16 +
 .../resources/live-only-hapolicy-config2.xml    |   22 +
 .../resources/live-only-hapolicy-config3.xml    |   11 +
 .../resources/live-only-hapolicy-config4.xml    |    7 +
 .../resources/live-only-hapolicy-config5.xml    |    6 +
 .../test/resources/replica-hapolicy-config.xml  |   24 +
 .../test/resources/replica-hapolicy-config2.xml |   25 +
 .../test/resources/replica-hapolicy-config3.xml |   16 +
 .../resources/replicated-hapolicy-config.xml    |   15 +
 .../shared-store-master-hapolicy-config.xml     |   14 +
 .../shared-store-slave-hapolicy-config.xml      |   22 +
 .../shared-store-slave-hapolicy-config2.xml     |   24 +
 .../shared-store-slave-hapolicy-config3.xml     |   15 +
 .../src/main/java/org/hornetq/tools/Main.java   |   26 +-
 .../java/org/hornetq/tools/TransferQueue.java   |  243 +++
 .../org/hornetq/tools/XmlDataConstants.java     |    2 +
 .../java/org/hornetq/tools/XmlDataExporter.java |   14 +-
 .../java/org/hornetq/tools/XmlDataImporter.java |   13 +-
 hornetq_doap.rdf                                |   76 +
 .../hornetq-aerogear-integration/pom.xml        |    2 +-
 .../aerogear/AeroGearConnectorService.java      |   22 +-
 .../integration/aerogear/AeroGearConstants.java |    6 +
 .../hornetq-jboss-as-integration/pom.xml        |    2 +-
 .../twitter/impl/IncomingTweetsHandler.java     |    2 +-
 integration/hornetq-vertx-integration/pom.xml   |    6 +-
 .../vertx/IncomingVertxEventHandler.java        |    2 +-
 pom.xml                                         |  127 +-
 tests/byteman-tests/pom.xml                     |    4 +-
 .../hornetq/byteman/tests/BMFailoverTest.java   |  135 +-
 .../BridgeServerLocatorConfigurationTest.java   |   27 +-
 .../byteman/tests/ClusteredGroupingTest.java    |    4 +-
 .../tests/HornetQMessageHandlerTest.java        |    7 +-
 .../tests/JMSBridgeReconnectionTest.java        |  159 ++
 .../byteman/tests/OrphanedConsumerTest.java     |  298 +++
 .../hornetq/byteman/tests/PagingLeakTest.java   |  270 +++
 .../byteman/tests/ScaleDownFailoverTest.java    |   29 +-
 .../byteman/tests/ScaleDownFailureTest.java     |   15 +-
 .../byteman/tests/StartStopDeadlockTest.java    |   19 +-
 .../byteman/tests/StompInternalStateTest.java   |   14 +-
 tests/config/logging.properties.trace           |   68 +
 tests/integration-tests/pom.xml                 |   45 +-
 .../integration/DuplicateDetectionTest.java     |   82 +-
 .../tests/integration/String64KLimitTest.java   |    5 +-
 .../aerogear/AeroGearBasicServerTest.java       |   26 +-
 .../integration/client/AcknowledgeTest.java     |   42 +-
 .../integration/client/CommitRollbackTest.java  |   12 +-
 .../ConcurrentCreateDeleteProduceTest.java      |    7 +-
 .../integration/client/ConsumerCloseTest.java   |    6 +-
 .../integration/client/ConsumerStuckTest.java   |  305 +++
 .../tests/integration/client/ConsumerTest.java  |   33 +-
 .../integration/client/CoreClientTest.java      |    8 +-
 .../client/CreateQueueIdempotentTest.java       |    6 +-
 .../client/DeadLetterAddressTest.java           |   12 +-
 .../integration/client/ExpiryAddressTest.java   |   26 +-
 .../client/ExpiryLargeMessageTest.java          |    4 +-
 .../integration/client/FailureDeadlockTest.java |    6 +-
 .../integration/client/HangConsumerTest.java    |   45 +-
 .../integration/client/HeuristicXATest.java     |   32 +-
 .../integration/client/HornetQCrashTest.java    |    8 +-
 .../client/IncompatibleVersionTest.java         |    6 +-
 .../client/InterruptedLargeMessageTest.java     |    2 +-
 .../integration/client/JournalCrashTest.java    |   10 +-
 .../integration/client/LargeMessageTest.java    |   22 +-
 .../client/MessageExpirationTest.java           |    4 +-
 .../MessageGroupingConnectionFactoryTest.java   |    8 +-
 .../integration/client/MessageGroupingTest.java |    8 +-
 .../integration/client/MessagePriorityTest.java |    6 +-
 .../tests/integration/client/NIOvsOIOTest.java  |    5 +-
 .../integration/client/NettyConsumerTest.java   |   29 -
 .../client/NewDeadLetterAddressTest.java        |    8 +-
 .../tests/integration/client/OrderTest.java     |   62 +-
 .../integration/client/PagingOrderTest.java     |   70 +-
 .../integration/client/PagingSyncTest.java      |    5 +-
 .../tests/integration/client/PagingTest.java    |  260 ++-
 .../integration/client/ProducerCloseTest.java   |    6 +-
 .../integration/client/QueueBrowserTest.java    |    4 +-
 .../client/ReceiveImmediateTest.java            |    2 +-
 .../client/RedeliveryConsumerTest.java          |    4 +-
 .../tests/integration/client/RequestorTest.java |    4 +-
 .../integration/client/SessionCloseTest.java    |    6 +-
 ...onClosedOnRemotingConnectionFailureTest.java |    6 +-
 .../integration/client/SessionFactoryTest.java  |   38 +-
 .../tests/integration/client/SessionTest.java   |   37 +-
 .../integration/client/SlowConsumerTest.java    |  361 ++++
 .../integration/client/TemporaryQueueTest.java  |    7 +
 .../client/TransactionalSendTest.java           |   16 +-
 .../integration/client/WildCardRoutingTest.java |   13 +-
 .../integration/clientcrash/ClientTestBase.java |    4 +-
 .../integration/clientcrash/CrashClient.java    |    2 +-
 .../integration/clientcrash/CrashClient2.java   |    2 +-
 .../integration/clientcrash/GracefulClient.java |    2 +-
 .../cluster/ClusterControllerTest.java          |   97 +
 .../cluster/bridge/BridgeFailoverTest.java      |   24 +-
 .../cluster/bridge/BridgeReconnectTest.java     |  107 +-
 .../cluster/bridge/BridgeStartTest.java         |  174 +-
 .../integration/cluster/bridge/BridgeTest.java  |  404 ++--
 .../cluster/bridge/BridgeTestBase.java          |   61 +-
 .../BridgeWithDiscoveryGroupStartTest.java      |   81 +-
 .../bridge/NettyBridgeReconnectTest.java        |   28 -
 .../cluster/bridge/NettyBridgeStartTest.java    |   31 -
 .../cluster/bridge/NettyBridgeTest.java         |   30 -
 .../NettyBridgeWithDiscoveryGroupStartTest.java |   29 -
 .../cluster/distribution/ClusterTestBase.java   |  290 +--
 .../distribution/ClusterWithBackupTest.java     |    6 +-
 .../distribution/ClusteredGroupingTest.java     |   14 +-
 .../distribution/MessageRedistributionTest.java |   12 +-
 .../SimpleSymmetricClusterTest.java             |    6 +-
 .../distribution/SymmetricClusterTest.java      |  191 ++
 .../SymmetricClusterWithBackupTest.java         |   22 +-
 .../AutomaticColocatedQuorumVoteTest.java       |  123 +-
 .../cluster/failover/BackupSyncJournalTest.java |   34 +-
 .../failover/BackupSyncLargeMessageTest.java    |    2 +
 ...ColocatedFailoverCheckPairingsNettyTest.java |  113 --
 .../ColocatedFailoverCheckPairingsTest.java     |  160 --
 .../cluster/failover/ColocatedFailoverTest.java | 1403 --------------
 .../cluster/failover/FailBackAutoTest.java      |   51 +-
 .../cluster/failover/FailBackManualTest.java    |   72 +-
 .../cluster/failover/FailoverListenerTest.java  |   43 +-
 .../cluster/failover/FailoverTest.java          |   43 +-
 .../cluster/failover/FailoverTestBase.java      |   86 +-
 .../failover/GroupingFailoverTestBase.java      |   34 +-
 .../failover/LiveToLiveFailoverTest.java        |   76 +-
 ...ultipleLivesMultipleBackupsFailoverTest.java |   97 +-
 .../MultipleServerFailoverTestBase.java         |   96 +-
 .../cluster/failover/PagingFailoverTest.java    |    2 +-
 .../cluster/failover/QuorumFailOverTest.java    |   22 +-
 .../failover/QuorumVoteServerConnectTest.java   |    2 +-
 .../failover/ReplicatedDistributionTest.java    |    4 +-
 .../failover/ReplicatedFailoverTest.java        |   56 +-
 ...eplicatedFailoverUsingNodeGroupNameTest.java |   15 +-
 ...dMultipleServerFailoverExtraBackupsTest.java |   14 +-
 .../ReplicatedMultipleServerFailoverTest.java   |   54 -
 .../ReplicatedWithDelayFailoverTest.java        |    6 +
 .../cluster/failover/SecurityFailoverTest.java  |   43 +-
 .../SingleLiveMultipleBackupsFailoverTest.java  |   75 +-
 .../StaticClusterWithBackupFailoverTest.java    |    6 +-
 .../ha/HAAutomaticBackupSharedStore.java        |   19 +-
 .../reattach/MultiThreadRandomReattachTest.java |    6 +-
 .../NettyMultiThreadRandomReattachTest.java     |   10 +-
 .../cluster/reattach/RandomReattachTest.java    |    7 +-
 .../HAClientTopologyWithDiscoveryTest.java      |    7 +-
 .../cluster/topology/IsolatedTopologyTest.java  |  108 +-
 .../cluster/topology/NonHATopologyTest.java     |   11 +-
 .../cluster/util/BackupSyncDelay.java           |   12 +-
 .../cluster/util/MultiServerTestBase.java       |   93 +-
 .../integration/discovery/DiscoveryTest.java    |   55 +-
 .../tests/integration/divert/DivertTest.java    |  437 +++--
 .../divert/PersistentDivertTest.java            |   80 +-
 .../integration/embedded/ValidateAIOTest.java   |    6 +-
 .../http/CoreClientOverHttpTest.java            |    8 +-
 .../tests/integration/jms/FloodServerTest.java  |    6 +-
 .../jms/HornetQConnectionFactoryTest.java       |   30 +-
 .../ManualReconnectionToSingleServerTest.java   |   24 +-
 .../integration/jms/bridge/BridgeTestBase.java  |   35 +-
 .../jms/bridge/ClusteredBridgeTestBase.java     |   37 +-
 .../jms/bridge/JMSBridgeReconnectionTest.java   |  228 ++-
 .../jms/client/ExpiryMessageTest.java           |    7 +-
 .../integration/jms/client/StoreConfigTest.java |   18 +-
 .../jms/client/TopicCleanupTest.java            |    4 +-
 .../jms/cluster/BindingsClusterTest.java        |    5 +-
 .../jms/cluster/JMSFailoverListenerTest.java    |  113 +-
 .../jms/cluster/JMSFailoverTest.java            |   78 +-
 .../jms/cluster/JMSReconnectTest.java           |   18 +-
 .../jms/cluster/ReplicatedJMSFailoverTest.java  |   52 +-
 .../ConnectionFactorySerializationTest.java     |   14 +-
 ...tionFactoryWithJGroupsSerializationTest.java |  192 ++
 .../jms/connection/ExceptionListenerTest.java   |    7 +-
 .../integration/jms/consumer/ConsumerTest.java  |   52 +-
 .../jms/divert/DivertAndACKClientTest.java      |   13 +-
 .../JmsProducerCompletionListenerTest.java      |    3 +-
 .../server/ColocatedJMSServerStartStopTest.java |  166 --
 .../jms/server/JMSServerDeployerTest.java       |   23 +-
 .../jms/server/config/JMSConfigurationTest.java |   30 +-
 .../config/JMSServerConfigParserTest.java       |    7 +-
 .../ConnectionFactoryControlTest.java           |   65 +-
 .../server/management/JMSQueueControlTest.java  |  167 +-
 .../management/JMSQueueControlUsingJMSTest.java |   14 +
 .../management/JMSServerControl2Test.java       |  298 ++-
 .../management/JMSServerControlRestartTest.java |   12 +-
 .../server/management/JMSServerControlTest.java |  140 +-
 .../JMSServerControlUsingJMSTest.java           |   10 +
 .../jms/server/management/JMSUtil.java          |   20 +-
 .../jms/server/management/TopicControlTest.java |   76 +-
 .../management/TopicControlUsingJMSTest.java    |    7 +-
 .../journal/NIOJournalCompactTest.java          |   14 +-
 .../management/AcceptorControlTest.java         |   25 +-
 .../management/AddressControlTest.java          |    6 +-
 .../management/AddressControlUsingCoreTest.java |    6 +-
 .../management/BridgeControlTest.java           |   84 +-
 .../management/BridgeControlUsingCoreTest.java  |   73 +-
 .../management/BroadcastGroupControlTest.java   |   32 +-
 .../ClusterConnectionControl2Test.java          |   82 +-
 .../ClusterConnectionControlTest.java           |  109 +-
 .../management/DivertControlTest.java           |   47 +-
 .../management/HornetQServerControlTest.java    |  124 +-
 .../HornetQServerControlUsingCoreTest.java      |   39 +-
 .../integration/management/JMXDomainTest.java   |  133 +-
 .../management/ManagementActivationTest.java    |    5 +-
 .../management/ManagementServiceImplTest.java   |   24 +-
 .../management/ManagementTestBase.java          |   24 +
 .../ManagementWithPagingServerTest.java         |    7 +-
 .../management/ManagementWithStompTest.java     |   12 +-
 .../management/NotificationTest.java            |   16 +-
 .../management/QueueControlTest.java            |  246 ++-
 .../management/QueueControlUsingCoreTest.java   |   23 +
 ...tyManagementWithConfiguredAdminUserTest.java |    6 +-
 ...yManagementWithDefaultConfigurationTest.java |    8 +-
 ...ManagementWithModifiedConfigurationTest.java |    8 +-
 .../management/SecurityNotificationTest.java    |   14 +-
 .../integration/openwire/BasicOpenWireTest.java |  249 +++
 .../integration/openwire/BasicSecurityTest.java |  256 +++
 .../integration/openwire/OpenWireTestBase.java  |  190 ++
 .../integration/openwire/OpenWireUtilTest.java  |   37 +
 .../openwire/SimpleOpenWireTest.java            |  280 +++
 .../openwire/amq/JMSConsumer10Test.java         |  108 ++
 .../openwire/amq/JMSConsumer11Test.java         |  115 ++
 .../openwire/amq/JMSConsumer12Test.java         |   92 +
 .../openwire/amq/JMSConsumer13Test.java         |   85 +
 .../openwire/amq/JMSConsumer1Test.java          |  121 ++
 .../openwire/amq/JMSConsumer2Test.java          |  240 +++
 .../openwire/amq/JMSConsumer3Test.java          |  113 ++
 .../openwire/amq/JMSConsumer4Test.java          |  103 +
 .../openwire/amq/JMSConsumer5Test.java          |  135 ++
 .../openwire/amq/JMSConsumer6Test.java          |  146 ++
 .../openwire/amq/JMSConsumer7Test.java          |  162 ++
 .../openwire/amq/JMSConsumer8Test.java          |  159 ++
 .../openwire/amq/JMSConsumer9Test.java          |  141 ++
 .../amq/JMSDurableTopicRedeliverTest.java       |   95 +
 .../openwire/amq/JMSIndividualAckTest.java      |  151 ++
 .../openwire/amq/JMSMessageTest.java            |  639 +++++++
 .../openwire/amq/JMSQueueRedeliverTest.java     |   33 +
 .../openwire/amq/JMSUsecase1Test.java           |  122 ++
 .../openwire/amq/JMSUsecaseTest.java            |   88 +
 .../openwire/amq/JmsAutoAckListenerTest.java    |   67 +
 .../openwire/amq/JmsAutoAckTest.java            |   65 +
 .../openwire/amq/JmsClientAckTest.java          |  144 ++
 .../amq/JmsConnectionStartStopTest.java         |  185 ++
 .../amq/JmsConsumerResetActiveListenerTest.java |  165 ++
 .../amq/JmsCreateConsumerInOnMessageTest.java   |   99 +
 .../JmsDurableQueueWildcardSendReceiveTest.java |   43 +
 .../amq/JmsDurableTopicSelectorTest.java        |   33 +
 .../amq/JmsDurableTopicSendReceiveTest.java     |  101 +
 .../amq/JmsDurableTopicTransactionTest.java     |   39 +
 .../JmsDurableTopicWildcardSendReceiveTest.java |   44 +
 .../openwire/amq/JmsQueueBrowserTest.java       |  506 +++++
 .../openwire/amq/JmsQueueRequestReplyTest.java  |   38 +
 .../openwire/amq/JmsResourceProvider.java       |  265 +++
 .../openwire/amq/JmsSendReceiveTestSupport.java |  245 +++
 .../openwire/amq/JmsTopicRedeliverTest.java     |  154 ++
 .../openwire/amq/JmsTopicRequestReplyTest.java  |  273 +++
 .../openwire/amq/JmsTopicSelectorTest.java      |  230 +++
 .../openwire/amq/JmsTopicSendReceiveTest.java   |  119 ++
 ...sTopicSendReceiveWithTwoConnectionsTest.java |  110 ++
 .../openwire/amq/JmsTopicTransactionTest.java   |   36 +
 .../amq/JmsTopicWildcardSendReceiveTest.java    |  255 +++
 .../openwire/amq/JmsTransactionTestSupport.java |  760 ++++++++
 .../amq/MessageListenerRedeliveryTest.java      |  457 +++++
 .../amq/ProducerFlowControlSendFailTest.java    |  217 +++
 .../openwire/amq/ProducerFlowControlTest.java   |  410 ++++
 .../amq/ReconnectWithSameClientIDTest.java      |   97 +
 .../openwire/amq/RedeliveryPolicyTest.java      |  637 +++++++
 .../integration/openwire/amq/TimeStampTest.java |   91 +
 .../openwire/amq/TransactionContextTest.java    |  153 ++
 .../openwire/interop/GeneralInteropTest.java    |  669 +++++++
 .../tests/integration/openwire/util/Wait.java   |   56 +
 .../paging/MultipleProducersPagingTest.java     |   29 +-
 .../paging/PageCountSyncOnNonTXTest.java        |    2 +-
 .../integration/paging/PagingReceiveTest.java   |    4 +-
 .../PagingWithFailoverAndCountersTest.java      |    4 +-
 .../paging/SpawnedServerSupport.java            |   65 +-
 ...nnectionFactoryConfigurationStorageTest.java |   17 +-
 .../persistence/JMSDynamicConfigTest.java       |    5 +-
 .../persistence/XmlImportExportTest.java        |  205 +-
 .../tests/integration/proton/ProtonTest.java    |  782 ++++++--
 .../integration/ra/DummyTransactionManager.java |    9 +-
 .../integration/ra/HornetQClusteredTest.java    |    3 +-
 .../ra/HornetQMessageHandlerTest.java           |  226 +++
 .../ra/HornetQMessageHandlerXATest.java         |  131 ++
 .../ra/HornetQRAClusteredTestBase.java          |   55 +-
 .../tests/integration/ra/HornetQRATestBase.java |    1 +
 .../integration/ra/OutgoingConnectionTest.java  |   19 +
 .../integration/remoting/BatchDelayTest.java    |    6 +-
 .../integration/remoting/DirectDeliverTest.java |    6 +-
 .../tests/integration/remoting/PingTest.java    |   10 +-
 .../remoting/SynchronousCloseTest.java          |    4 +-
 .../replication/ReplicationTest.java            |   27 +-
 .../scheduling/DelayedMessageTest.java          |    6 +-
 .../MultipliedDelayedMessageTest.java           |    6 +-
 .../scheduling/ScheduledMessageTest.java        |   14 +-
 .../security/NettySecurityClientTest.java       |    5 +-
 .../integration/security/SecurityTest.java      |   34 +-
 .../integration/security/SimpleClient.java      |    2 +-
 .../integration/server/ExpiryRunnerTest.java    |    8 +-
 .../integration/server/FileLockTimeoutTest.java |    8 +-
 .../integration/server/LVQRecoveryTest.java     |    4 +-
 .../tests/integration/server/LVQTest.java       |    6 +-
 .../integration/server/PredefinedQueueTest.java |   56 +-
 .../integration/server/ScaleDown3NodeTest.java  |   48 +-
 .../tests/integration/server/ScaleDownTest.java |   37 +-
 .../server/SuppliedThreadPoolTest.java          |  118 ++
 .../ssl/CoreClientOverOneWaySSLTest.java        |   87 +-
 .../ssl/CoreClientOverTwoWaySSLTest.java        |   59 +-
 .../tests/integration/stomp/ExtraStompTest.java |   46 +-
 .../tests/integration/stomp/StompTestBase.java  |   24 +-
 .../integration/stomp/StompWebSocketTest.java   |   18 +-
 .../stomp/util/StompFrameFactoryV11.java        |  105 +-
 .../stomp/util/StompFrameFactoryV12.java        |  131 +-
 .../integration/stomp/v11/StompV11Test.java     |   43 +-
 .../integration/stomp/v11/StompV11TestBase.java |   21 +-
 .../integration/stomp/v12/StompV12Test.java     |   43 +-
 .../integration/tools/TransferMessageTest.java  |  433 +++++
 .../NettyConnectorWithHTTPUpgradeTest.java      |   55 +-
 .../tests/integration/twitter/TwitterTest.java  |  100 +-
 .../integration/vertx/HornetQVertxUnitTest.java |   82 +-
 .../integration/xa/BasicXaRecoveryTest.java     |   10 +-
 .../tests/integration/xa/BasicXaTest.java       |   41 +-
 .../tests/integration/xa/XaTimeoutTest.java     |    8 +-
 .../largemessage/LargeMessageTestBase.java      |    2 +-
 .../tests/util/JMSClusteredTestBase.java        |   38 +-
 .../org/hornetq/tests/util/JMSTestBase.java     |   44 +-
 .../tests/util/ReplicatedBackupUtils.java       |   36 +-
 tests/jms-tests/pom.xml                         |    7 +-
 .../jms/tests/HornetQServerTestCase.java        |   23 +-
 .../jms/tests/message/MessageHeaderTest.java    |    6 +-
 .../jms/tests/tools/ConfigurationHelper.java    |   69 -
 .../tests/tools/container/LocalTestServer.java  |   49 +-
 .../jms/tests/tools/container/Server.java       |    2 +-
 .../src/test/resources/hornetq-beans.xml        |   60 -
 .../jms-tests/src/test/resources/test-beans.xml |   60 -
 tests/joram-tests/pom.xml                       |    2 +-
 .../java/org/hornetq/jms/SpawnedJMSServer.java  |    9 +-
 tests/performance-tests/pom.xml                 |    2 +-
 tests/soak-tests/pom.xml                        |    2 +-
 .../soak/client/ClientNonDivertedSoakTest.java  |    5 +-
 .../tests/soak/client/ClientSoakTest.java       |   33 +-
 .../soak/client/SimpleSendReceiveSoakTest.java  |    5 +-
 tests/stress-tests/pom.xml                      |    2 +-
 .../stress/journal/CompactingStressTest.java    |   14 +-
 .../stress/journal/LargeJournalStressTest.java  |   14 +-
 .../journal/MultiThreadConsumerStressTest.java  |   16 +-
 .../NIOMultiThreadCompactorStressTest.java      |   24 +-
 .../journal/XmlImportExportStressTest.java      |   19 +-
 .../stress/paging/PageCursorStressTest.java     |   11 +-
 .../tests/stress/paging/PageStressTest.java     |   14 +-
 .../tests/stress/stomp/StompStressTest.java     |   19 +-
 tests/timing-tests/pom.xml                      |    2 +-
 .../jms/bridge/impl/JMSBridgeImplTest.java      |    8 +-
 tests/unit-tests/pom.xml                        |    6 +-
 .../client/impl/LargeMessageBufferTest.java     |   16 +-
 .../core/config/impl/ConnectorsServiceTest.java |   95 +
 .../config/impl/fakes/FakeConnectorService.java |   45 +
 .../impl/fakes/FakeConnectorServiceFactory.java |   65 +
 .../core/postoffice/impl/BindingsImplTest.java  |    8 +
 .../unit/core/postoffice/impl/FakeQueue.java    |   41 +-
 .../impl/invm/InVMConnectorFactoryTest.java     |   54 +
 .../impl/netty/NettyConnectorFactoryTest.java   |   54 +
 .../remoting/impl/netty/NettyConnectorTest.java |    8 +-
 .../core/remoting/impl/ssl/SSLSupportTest.java  |   55 +-
 .../server/impl/RemotingServiceImplTest.java    |  142 ++
 .../server/impl/fake/FakeInterceptor.java       |   33 +
 .../impl/ClusterConnectionBridgeTest.java       |  110 ++
 .../group/impl/SystemPropertyOverrideTest.java  |    5 +-
 .../unit/core/server/impl/QueueImplTest.java    |  113 +-
 .../core/settings/impl/AddressSettingsTest.java |  143 --
 .../unit/core/settings/impl/RepositoryTest.java |  271 ---
 .../tests/unit/microcontainer/DummyBean.java    |   31 -
 .../HornetQBootstrapServerTest.java             |   95 -
 .../ra/ConnectionFactoryPropertiesTest.java     |    3 +-
 .../ra/HornetQResourceAdapterConfigTest.java    |    6 +
 .../tests/unit/ra/ResourceAdapterTest.java      |   37 +-
 .../tests/unit/xa/XAResourceWrapperTest.java    |   43 +
 .../test/resources/client-side-keystore.jceks   |  Bin 0 -> 1256 bytes
 .../src/test/resources/client-side-keystore.jks |  Bin 0 -> 1300 bytes
 .../test/resources/client-side-truststore.jceks |  Bin 0 -> 877 bytes
 .../test/resources/client-side-truststore.jks   |  Bin 0 -> 1515 bytes
 .../src/test/resources/client-side.keystore     |  Bin 1300 -> 0 bytes
 .../src/test/resources/client-side.truststore   |  Bin 670 -> 0 bytes
 .../test/resources/server-side-keystore.jceks   |  Bin 0 -> 1257 bytes
 .../src/test/resources/server-side-keystore.jks |  Bin 0 -> 2627 bytes
 .../test/resources/server-side-truststore.jceks |  Bin 0 -> 876 bytes
 .../test/resources/server-side-truststore.jks   |  Bin 0 -> 893 bytes
 .../src/test/resources/server-side.keystore     |  Bin 1375 -> 0 bytes
 .../src/test/resources/server-side.truststore   |  Bin 893 -> 0 bytes
 1065 files changed, 60911 insertions(+), 22942 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
index d37b3a5..7e91952 100644
--- a/README.md
+++ b/README.md
@@ -156,16 +156,30 @@ Do not use the [maven-eclipse-plugin] to copy the files as it conflicts with [m2
 [maven-eclipse-plugin]: https://maven.apache.org/plugins/maven-eclipse-plugin/
 [m2e]: http://eclipse.org/m2e/
 
-## GitHub procedures
+## Committing Changes
 
-The best way to submit changes to HornetQ is through pull requests on
-GitHub. After review a pull request should either get merged or be
-rejected.
+### GitHub
 
-When a pull request needs to be reworked, say you have missed
-something, the pull request is then closed. When you finished
-addressing the required changes you should reopen your original pull
-request and it will then be re-evaluated. At that point if the request
-is approved we will then merge it.
+We follow the GitHub workflow for all code changes in HornetQ. For information on the GitHub workflow please see:
+https://guides.github.com/introduction/flow/index.html
 
-Make sure you always rebase your branch on master before submitting pull requests.
+### Commit Messages
+
+We follow the 50/72 git commit message format.  A HornetQ commit message should be formatted in the following manner:
+
+* Add the HornetQ JIRA or Bugzilla reference (if one exists) followed by a brief description of the change in the first line.
+* Insert a single blank line after the first line.
+* Provide a detailed description of the change in the following lines, breaking paragraphs where needed.
+* The first line should be limited to 50 characters
+* Subsequent lines should be wrapped at 72 characters.
+
+An example correctly formatted commit message:
+
+```
+HORNETQ-1234 Add new commit msg format to README
+
+Adds a description of the new commit message format as well as examples
+of well formatted commit messages to the README.md.  This is required 
+to enable developers to quickly identify what the commit is intended to 
+do and why the commit was added.
+```

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/distribution/hornetq/pom.xml
----------------------------------------------------------------------
diff --git a/distribution/hornetq/pom.xml b/distribution/hornetq/pom.xml
index 644b6b4..c725c7e 100644
--- a/distribution/hornetq/pom.xml
+++ b/distribution/hornetq/pom.xml
@@ -28,11 +28,86 @@
 
    <properties>
       <schemaLocation>${project.build.directory}/${project.artifactId}-${project.version}-bin/${project.artifactId}-${project.version}/schema</schemaLocation>
-      <standalone>src/main/resources/config/stand-alone</standalone>
-      <as6>src/main/resources/config/jboss-as-6</as6>
+      <configLocation>src/main/resources/config</configLocation>
    </properties>
 
    <dependencies>
+     <!-- HornetQ artifacts -->
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-server</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-dto</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-bootstrap</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-jms-server</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-jms-client</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-tools</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-jboss-as-integration</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-ra</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-service-sar</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-spring-integration</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-twitter-integration</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-vertx-integration</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq.rest</groupId>
+        <artifactId>hornetq-rest</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>hornetq-aerogear-integration</artifactId>
+        <version>${project.version}</version>
+     </dependency>
+     <dependency>
+        <groupId>org.hornetq</groupId>
+        <artifactId>jnp-client</artifactId>
+        <version>${project.version}</version>
+     </dependency>
       <dependency>
          <groupId>org.hornetq</groupId>
          <artifactId>hornetq-core-client</artifactId>
@@ -49,17 +124,64 @@
            <version>${project.version}</version>
        </dependency>
        <dependency>
-           <groupId>org.apache.qpid</groupId>
-           <artifactId>proton-api</artifactId>
+           <groupId>org.hornetq</groupId>
+           <artifactId>hornetq-openwire-protocol</artifactId>
+           <version>${project.version}</version>
        </dependency>
        <dependency>
-           <groupId>org.apache.qpid</groupId>
-           <artifactId>proton-j-impl</artifactId>
+           <groupId>org.hornetq</groupId>
+           <artifactId>hornetq-native</artifactId>
+           <version>${project.version}</version>
        </dependency>
+
+      <!-- dependencies -->
        <dependency>
            <groupId>org.apache.qpid</groupId>
            <artifactId>proton-jms</artifactId>
        </dependency>
+       <dependency>
+           <groupId>io.airlift</groupId>
+           <artifactId>airline</artifactId>
+       </dependency>
+       <dependency>
+           <groupId>org.apache.activemq</groupId>
+           <artifactId>activemq-client</artifactId>
+       </dependency>
+       <dependency>
+           <groupId>com.fasterxml.jackson.core</groupId>
+           <artifactId>jackson-databind</artifactId>
+           <version>${jackson-databind.version}</version>
+       </dependency>
+       <dependency>
+           <groupId>org.apache.activemq</groupId>
+           <artifactId>activemq-client</artifactId>
+       </dependency>
+
+       <!-- javadoc -->
+       <dependency>
+           <groupId>org.hornetq</groupId>
+           <artifactId>hornetq-core-client</artifactId>
+           <version>${project.version}</version>
+           <classifier>javadoc</classifier>
+       </dependency>
+     <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-server</artifactId>
+         <version>${project.version}</version>
+         <classifier>javadoc</classifier>
+     </dependency>
+     <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-jms-server</artifactId>
+         <version>${project.version}</version>
+         <classifier>javadoc</classifier>
+     </dependency>
+     <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-jms-client</artifactId>
+         <version>${project.version}</version>
+         <classifier>javadoc</classifier>
+     </dependency>
    </dependencies>
 
    <build>
@@ -107,70 +229,84 @@
             <configuration>
                <validationSets>
                   <validationSet>
-                     <dir>${standalone}/clustered</dir>
+                     <dir>${configLocation}/clustered</dir>
                      <systemId>${schemaLocation}/hornetq-configuration.xsd</systemId>
                      <includes>
                         <include>hornetq-configuration.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${standalone}/non-clustered</dir>
+                     <dir>${configLocation}/non-clustered</dir>
                      <systemId>${schemaLocation}/hornetq-configuration.xsd</systemId>
                      <includes>
                         <include>hornetq-configuration.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${as6}/clustered</dir>
+                     <dir>${configLocation}/replicated</dir>
                      <systemId>${schemaLocation}/hornetq-configuration.xsd</systemId>
                      <includes>
                         <include>hornetq-configuration.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${as6}/non-clustered</dir>
+                     <dir>${configLocation}/shared-store</dir>
                      <systemId>${schemaLocation}/hornetq-configuration.xsd</systemId>
                      <includes>
                         <include>hornetq-configuration.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${standalone}/clustered</dir>
+                     <dir>${configLocation}/clustered</dir>
                      <systemId>${schemaLocation}/hornetq-jms.xsd</systemId>
                      <includes>
                         <include>hornetq-jms.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${standalone}/non-clustered</dir>
+                     <dir>${configLocation}/non-clustered</dir>
                      <systemId>${schemaLocation}/hornetq-jms.xsd</systemId>
                      <includes>
                         <include>hornetq-jms.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${as6}/clustered</dir>
+                     <dir>${configLocation}/replicated</dir>
                      <systemId>${schemaLocation}/hornetq-jms.xsd</systemId>
                      <includes>
                         <include>hornetq-jms.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${as6}/non-clustered</dir>
+                     <dir>${configLocation}/shared-store</dir>
                      <systemId>${schemaLocation}/hornetq-jms.xsd</systemId>
                      <includes>
                         <include>hornetq-jms.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${standalone}/clustered</dir>
+                     <dir>${configLocation}/clustered</dir>
                      <systemId>${schemaLocation}/hornetq-users.xsd</systemId>
                      <includes>
                         <include>hornetq-users.xml</include>
                      </includes>
                   </validationSet>
                   <validationSet>
-                     <dir>${standalone}/non-clustered</dir>
+                     <dir>${configLocation}/non-clustered</dir>
+                     <systemId>${schemaLocation}/hornetq-users.xsd</systemId>
+                     <includes>
+                        <include>hornetq-users.xml</include>
+                     </includes>
+                  </validationSet>
+                  <validationSet>
+                     <dir>${configLocation}/replicated</dir>
+                     <systemId>${schemaLocation}/hornetq-users.xsd</systemId>
+                     <includes>
+                        <include>hornetq-users.xml</include>
+                     </includes>
+                  </validationSet>
+                  <validationSet>
+                     <dir>${configLocation}/shared-store</dir>
                      <systemId>${schemaLocation}/hornetq-users.xsd</systemId>
                      <includes>
                         <include>hornetq-users.xml</include>
@@ -179,7 +315,6 @@
                </validationSets>
             </configuration>
          </plugin>
-
       </plugins>
    </build>
 


[36/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonUtils.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonUtils.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonUtils.java
deleted file mode 100644
index c6b60f3..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonUtils.java
+++ /dev/null
@@ -1,633 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton;
-
-import java.nio.ByteBuffer;
-import java.util.Calendar;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.qpid.proton.amqp.Binary;
-import org.apache.qpid.proton.amqp.Symbol;
-import org.apache.qpid.proton.amqp.UnsignedByte;
-import org.apache.qpid.proton.amqp.UnsignedInteger;
-import org.apache.qpid.proton.amqp.messaging.AmqpValue;
-import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
-import org.apache.qpid.proton.amqp.messaging.Data;
-import org.apache.qpid.proton.amqp.messaging.DeliveryAnnotations;
-import org.apache.qpid.proton.amqp.messaging.Footer;
-import org.apache.qpid.proton.amqp.messaging.Header;
-import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
-import org.apache.qpid.proton.amqp.messaging.Properties;
-import org.apache.qpid.proton.amqp.messaging.Section;
-import org.apache.qpid.proton.codec.CompositeWritableBuffer;
-import org.apache.qpid.proton.codec.DroppingWritableBuffer;
-import org.apache.qpid.proton.codec.WritableBuffer;
-import org.apache.qpid.proton.jms.EncodedMessage;
-import org.apache.qpid.proton.message.Message;
-import org.apache.qpid.proton.message.MessageFormat;
-import org.apache.qpid.proton.message.impl.MessageImpl;
-import org.hornetq.api.core.SimpleString;
-import org.hornetq.core.server.ServerMessage;
-import org.hornetq.core.server.impl.ServerMessageImpl;
-import org.hornetq.utils.TypedProperties;
-
-import static org.hornetq.api.core.Message.TEXT_TYPE;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         4/11/13
- */
-public class ProtonUtils
-{
-   private static final String PREFIX = "HORNETQ_PROTON_";
-   private static final String MESSAGE_ANNOTATIONS = PREFIX + "MESSAGE_ANNOTATIONS_";
-   private static final String DELIVERY_ANNOTATIONS = PREFIX + "DELIVERY_ANNOTATIONS_";
-   private static final String FOOTER_VALUES = PREFIX + "FOOTER_VALUES";
-   private static final String MESSAGE_FORMAT = PREFIX + "MESSAGE_FORMAT";
-   private static final String PROTON_MESSAGE_FORMAT = PREFIX + "FORMAT";
-   private static final String PROTON_MESSAGE_SIZE = "PROTON_MESSAGE_SIZE";
-   private static final String MESSAGE_TYPE = PREFIX + "MESSAGE_TYPE";
-   private static final String FIRST_ACQUIRER = PREFIX + "FIRST_ACQUIRER";
-   private static final String USER_ID = PREFIX + "USER_ID";
-   private static final String SUBJECT = PREFIX + "SUBJECT";
-   private static final String REPLY_TO = PREFIX + "REPLY_TO";
-   private static final String CORRELATION_ID = PREFIX + "CORRELATION_ID";
-   private static final String CONTENT_TYPE = PREFIX + "CONTENT_TYPE";
-   private static final String CONTENT_ENCODING = PREFIX + "CONTENT_TYPE";
-   private static final String ABSOLUTE_EXPIRY_TIME = PREFIX + "ABSOLUTE_EXPIRY_TIME";
-   private static final String CREATION_TIME = PREFIX + "CREATION_TIME";
-   private static final String GROUP_ID = PREFIX + "GROUP_ID";
-   private static final String GROUP_SEQUENCE = PREFIX + "GROUP_SEQUENCE";
-   private static final String REPLY_TO_GROUP_ID = PREFIX + "REPLY_TO_GROUP_ID";
-
-   private static final SimpleString USER_ID_SS = new SimpleString(USER_ID);
-   private static final SimpleString SUBJECT_SS = new SimpleString(SUBJECT);
-   private static final SimpleString REPLY_TO_SS = new SimpleString(REPLY_TO);
-   private static final SimpleString CORRELATION_ID_SS = new SimpleString(CORRELATION_ID);
-   private static final SimpleString CONTENT_TYPE_SS = new SimpleString(CONTENT_TYPE);
-   private static final SimpleString CONTENT_ENCODING_SS = new SimpleString(CONTENT_ENCODING);
-   private static final SimpleString ABSOLUTE_EXPIRY_TIME_SS = new SimpleString(ABSOLUTE_EXPIRY_TIME);
-   private static final SimpleString CREATION_TIME_SS = new SimpleString(CREATION_TIME);
-   private static final SimpleString GROUP_ID_SS = new SimpleString(GROUP_ID);
-   private static final SimpleString GROUP_SEQUENCE_SS = new SimpleString(GROUP_SEQUENCE);
-   private static final SimpleString REPLY_TO_GROUP_ID_SS = new SimpleString(REPLY_TO_GROUP_ID);
-   private static final SimpleString PROTON_MESSAGE_SIZE_SS = new SimpleString(PROTON_MESSAGE_SIZE);
-
-   private static Set<String> SPECIAL_PROPS = new HashSet<String>();
-
-   static
-   {
-      SPECIAL_PROPS.add(MESSAGE_FORMAT);
-      SPECIAL_PROPS.add(MESSAGE_TYPE);
-      SPECIAL_PROPS.add(FIRST_ACQUIRER);
-      SPECIAL_PROPS.add(PROTON_MESSAGE_FORMAT);
-      SPECIAL_PROPS.add(PROTON_MESSAGE_SIZE);
-      SPECIAL_PROPS.add(MESSAGE_TYPE);
-      SPECIAL_PROPS.add(USER_ID);
-      SPECIAL_PROPS.add(SUBJECT);
-      SPECIAL_PROPS.add(REPLY_TO);
-      SPECIAL_PROPS.add(CORRELATION_ID);
-      SPECIAL_PROPS.add(CONTENT_TYPE);
-      SPECIAL_PROPS.add(CONTENT_ENCODING);
-      SPECIAL_PROPS.add(ABSOLUTE_EXPIRY_TIME);
-      SPECIAL_PROPS.add(CREATION_TIME);
-      SPECIAL_PROPS.add(GROUP_ID);
-      SPECIAL_PROPS.add(GROUP_SEQUENCE);
-      SPECIAL_PROPS.add(REPLY_TO_GROUP_ID);
-   }
-
-   public static class INBOUND
-   {
-      public static ServerMessageImpl transform(ProtonRemotingConnection connection, EncodedMessage encodedMessage) throws Exception
-      {
-         org.apache.qpid.proton.message.Message protonMessage = encodedMessage.decode();
-
-         Header header = protonMessage.getHeader();
-         if (header == null)
-         {
-            header = new Header();
-         }
-
-         ServerMessageImpl message = connection.createServerMessage();
-         TypedProperties properties = message.getProperties();
-
-         properties.putLongProperty(new SimpleString(MESSAGE_FORMAT), encodedMessage.getMessageFormat());
-         properties.putLongProperty(new SimpleString(PROTON_MESSAGE_FORMAT), getMessageFormat(protonMessage.getMessageFormat()));
-         properties.putIntProperty(new SimpleString(PROTON_MESSAGE_SIZE), encodedMessage.getLength());
-
-         populateSpecialProps(header, protonMessage, message, properties);
-         populateHeaderProperties(header, properties, message);
-         populateDeliveryAnnotations(protonMessage.getDeliveryAnnotations(), properties);
-         populateMessageAnnotations(protonMessage.getMessageAnnotations(), properties);
-         populateApplicationProperties(protonMessage.getApplicationProperties(), properties);
-         populateProperties(protonMessage.getProperties(), properties, message);
-         populateFooterProperties(protonMessage.getFooter(), properties);
-         message.setTimestamp(System.currentTimeMillis());
-
-         Section section = protonMessage.getBody();
-         if (section instanceof AmqpValue)
-         {
-            AmqpValue amqpValue = (AmqpValue) section;
-            Object value = amqpValue.getValue();
-            if (value instanceof String)
-            {
-               message.getBodyBuffer().writeNullableString((String) value);
-            }
-            else if (value instanceof Binary)
-            {
-               Binary binary = (Binary) value;
-               message.getBodyBuffer().writeBytes(binary.getArray());
-            }
-         }
-         else if (section instanceof Data)
-         {
-            message.getBodyBuffer().writeBytes(((Data) section).getValue().getArray());
-         }
-
-         return message;
-      }
-
-      private static void populateSpecialProps(Header header, Message protonMessage, ServerMessageImpl message, TypedProperties properties)
-      {
-         if (header.getFirstAcquirer() != null)
-         {
-            properties.putBooleanProperty(new SimpleString(FIRST_ACQUIRER), header.getFirstAcquirer());
-         }
-         properties.putIntProperty(new SimpleString(MESSAGE_TYPE), getMessageType(protonMessage));
-      }
-
-      private static void populateHeaderProperties(Header header, TypedProperties properties, ServerMessageImpl message)
-      {
-         if (header.getDurable() != null)
-         {
-            message.setDurable(header.getDurable());
-         }
-
-         if (header.getPriority() != null)
-         {
-            message.setPriority((byte) header.getPriority().intValue());
-         }
-
-         if (header.getTtl() != null)
-         {
-            message.setExpiration(header.getTtl().longValue());
-         }
-      }
-
-      private static void populateDeliveryAnnotations(DeliveryAnnotations deliveryAnnotations, TypedProperties properties)
-      {
-         if (deliveryAnnotations != null)
-         {
-            Map values = deliveryAnnotations.getValue();
-            Set keySet = values.keySet();
-            for (Object key : keySet)
-            {
-               Symbol symbol = (Symbol) key;
-               Object value = values.get(key);
-               properties.putSimpleStringProperty(new SimpleString(DELIVERY_ANNOTATIONS + symbol.toString()), new SimpleString(value.toString()));
-            }
-         }
-      }
-
-      private static void populateFooterProperties(Footer footer, TypedProperties properties)
-      {
-         if (footer != null)
-         {
-            Map values = footer.getValue();
-            Set keySet = values.keySet();
-            for (Object key : keySet)
-            {
-               Symbol symbol = (Symbol) key;
-               Object value = values.get(key);
-               properties.putSimpleStringProperty(new SimpleString(FOOTER_VALUES + symbol.toString()), new SimpleString(value.toString()));
-            }
-         }
-      }
-
-      private static void populateProperties(Properties amqpProperties, TypedProperties properties, ServerMessageImpl message)
-      {
-         if (amqpProperties == null)
-         {
-            return;
-         }
-         if (amqpProperties.getTo() != null)
-         {
-            message.setAddress(new SimpleString(amqpProperties.getTo()));
-         }
-         if (amqpProperties.getUserId() != null)
-         {
-            properties.putBytesProperty(USER_ID_SS, amqpProperties.getUserId().getArray());
-         }
-         if (amqpProperties.getSubject() != null)
-         {
-            properties.putSimpleStringProperty(SUBJECT_SS, new SimpleString(amqpProperties.getSubject()));
-         }
-         if (amqpProperties.getReplyTo() != null)
-         {
-            properties.putSimpleStringProperty(REPLY_TO_SS, new SimpleString(amqpProperties.getReplyTo()));
-         }
-         if (amqpProperties.getCorrelationId() != null)
-         {
-            properties.putSimpleStringProperty(CORRELATION_ID_SS, new SimpleString(amqpProperties.getCorrelationId().toString()));
-         }
-         if (amqpProperties.getContentType() != null)
-         {
-            properties.putSimpleStringProperty(CONTENT_TYPE_SS, new SimpleString(amqpProperties.getContentType().toString()));
-         }
-         if (amqpProperties.getContentEncoding() != null)
-         {
-            properties.putSimpleStringProperty(CONTENT_ENCODING_SS, new SimpleString(amqpProperties.getContentEncoding().toString()));
-         }
-         if (amqpProperties.getAbsoluteExpiryTime() != null)
-         {
-            properties.putLongProperty(ABSOLUTE_EXPIRY_TIME_SS, amqpProperties.getAbsoluteExpiryTime().getTime());
-         }
-         if (amqpProperties.getCreationTime() != null)
-         {
-            properties.putLongProperty(CREATION_TIME_SS, amqpProperties.getCreationTime().getTime());
-         }
-         if (amqpProperties.getGroupId() != null)
-         {
-            properties.putSimpleStringProperty(GROUP_ID_SS, new SimpleString(amqpProperties.getGroupId()));
-         }
-         if (amqpProperties.getGroupSequence() != null)
-         {
-            properties.putIntProperty(GROUP_SEQUENCE_SS, amqpProperties.getGroupSequence().intValue());
-         }
-         if (amqpProperties.getReplyToGroupId() != null)
-         {
-            message.getProperties().putSimpleStringProperty(REPLY_TO_GROUP_ID_SS, new SimpleString(amqpProperties.getReplyToGroupId()));
-         }
-      }
-
-      private static void populateApplicationProperties(ApplicationProperties applicationProperties, TypedProperties properties)
-      {
-         if (applicationProperties != null)
-         {
-            Map props = applicationProperties.getValue();
-            for (Object key : props.keySet())
-            {
-               Object val = props.get(key);
-               setProperty(key, val, properties);
-            }
-         }
-      }
-
-      private static void setProperty(Object key, Object val, TypedProperties properties)
-      {
-         if (val instanceof String)
-         {
-            properties.putSimpleStringProperty(new SimpleString((String) key), new SimpleString((String) val));
-         }
-         else if (val instanceof Boolean)
-         {
-            properties.putBooleanProperty(new SimpleString((String) key), (Boolean) val);
-         }
-         else if (val instanceof Double)
-         {
-            properties.putDoubleProperty(new SimpleString((String) key), (Double) val);
-         }
-         else if (val instanceof Float)
-         {
-            properties.putFloatProperty(new SimpleString((String) key), (Float) val);
-         }
-         else if (val instanceof Integer)
-         {
-            properties.putIntProperty(new SimpleString((String) key), (Integer) val);
-         }
-         else if (val instanceof Byte)
-         {
-            properties.putByteProperty(new SimpleString((String) key), (Byte) val);
-         }
-      }
-
-      public static void populateMessageAnnotations(MessageAnnotations messageAnnotations, TypedProperties properties)
-      {
-         if (messageAnnotations != null)
-         {
-            Map values = messageAnnotations.getValue();
-            Set keySet = values.keySet();
-            for (Object key : keySet)
-            {
-               Symbol symbol = (Symbol) key;
-               Object value = values.get(key);
-               properties.putSimpleStringProperty(new SimpleString(MESSAGE_ANNOTATIONS + symbol.toString()), new SimpleString(value.toString()));
-            }
-         }
-      }
-
-   }
-
-   public static class OUTBOUND
-   {
-      public static EncodedMessage transform(ServerMessage message, int deliveryCount)
-      {
-         long messageFormat = message.getLongProperty(MESSAGE_FORMAT);
-         Integer size = message.getIntProperty(PROTON_MESSAGE_SIZE_SS);
-
-         Header header = populateHeader(message, deliveryCount);
-         DeliveryAnnotations deliveryAnnotations = populateDeliveryAnnotations(message);
-         MessageAnnotations messageAnnotations = populateMessageAnnotations(message);
-         Properties props = populateProperties(message);
-         ApplicationProperties applicationProperties = populateApplicationProperties(message);
-         Section section = populateBody(message);
-         Footer footer = populateFooter(message);
-         Set<SimpleString> propertyNames = message.getPropertyNames();
-         for (SimpleString propertyName : propertyNames)
-         {
-            TypedProperties typedProperties = message.getTypedProperties();
-            String realName = propertyName.toString();
-            if (realName.startsWith(MESSAGE_ANNOTATIONS))
-            {
-
-               SimpleString value = (SimpleString) typedProperties.getProperty(propertyName);
-               Symbol symbol = Symbol.getSymbol(realName.replace(MESSAGE_ANNOTATIONS, ""));
-               messageAnnotations.getValue().put(symbol, value.toString());
-            }
-         }
-         MessageImpl protonMessage = new MessageImpl(header, deliveryAnnotations, messageAnnotations, props, applicationProperties, section, footer);
-         protonMessage.setMessageFormat(getMessageFormat(message.getLongProperty(new SimpleString(PROTON_MESSAGE_FORMAT))));
-         ByteBuffer buffer = ByteBuffer.wrap(new byte[size]);
-         final DroppingWritableBuffer overflow = new DroppingWritableBuffer();
-         int c = protonMessage.encode(new CompositeWritableBuffer(new WritableBuffer.ByteBufferWrapper(buffer), overflow));
-         if (overflow.position() > 0)
-         {
-            buffer = ByteBuffer.wrap(new byte[1024 * 4 + overflow.position()]);
-            c = protonMessage.encode(new WritableBuffer.ByteBufferWrapper(buffer));
-         }
-
-         return new EncodedMessage(messageFormat, buffer.array(), 0, c);
-      }
-
-      private static Header populateHeader(ServerMessage message, int deliveryCount)
-      {
-         Header header = new Header();
-         header.setDurable(message.isDurable());
-         header.setPriority(new UnsignedByte(message.getPriority()));
-         header.setDeliveryCount(new UnsignedInteger(deliveryCount));
-         header.setTtl(new UnsignedInteger((int) message.getExpiration()));
-         return header;
-      }
-
-      private static DeliveryAnnotations populateDeliveryAnnotations(ServerMessage message)
-      {
-         HashMap actualValues = new HashMap();
-         DeliveryAnnotations deliveryAnnotations = new DeliveryAnnotations(actualValues);
-         for (SimpleString name : message.getPropertyNames())
-         {
-            String sName = name.toString();
-            if (sName.startsWith(DELIVERY_ANNOTATIONS))
-            {
-               Object val = message.getTypedProperties().getProperty(name);
-               if (val instanceof SimpleString)
-               {
-                  actualValues.put(sName.subSequence(sName.indexOf(DELIVERY_ANNOTATIONS), sName.length()), val.toString());
-               }
-               else
-               {
-                  actualValues.put(sName.subSequence(sName.indexOf(DELIVERY_ANNOTATIONS), sName.length()), val);
-               }
-            }
-         }
-         //this is a proton jms thing, if not null it creates wrong type of message
-         return actualValues.size() > 0 ? deliveryAnnotations : null;
-      }
-
-      private static MessageAnnotations populateMessageAnnotations(ServerMessage message)
-      {
-         HashMap actualValues = new HashMap();
-         MessageAnnotations messageAnnotations = new MessageAnnotations(actualValues);
-         for (SimpleString name : message.getPropertyNames())
-         {
-            String sName = name.toString();
-            if (sName.startsWith(MESSAGE_ANNOTATIONS))
-            {
-               Object val = message.getTypedProperties().getProperty(name);
-               if (val instanceof SimpleString)
-               {
-                  actualValues.put(sName.subSequence(sName.indexOf(MESSAGE_ANNOTATIONS), sName.length()), val.toString());
-               }
-               else
-               {
-                  actualValues.put(sName.subSequence(sName.indexOf(MESSAGE_ANNOTATIONS), sName.length()), val);
-               }
-            }
-         }
-         return messageAnnotations;
-      }
-
-      private static Properties populateProperties(ServerMessage message)
-      {
-         Calendar calendar = Calendar.getInstance();
-         Properties properties = new Properties();
-         TypedProperties typedProperties = message.getTypedProperties();
-         properties.setMessageId(message.getMessageID());
-         if (message.getAddress() != null)
-         {
-            properties.setTo(message.getAddress().toString());
-         }
-         if (typedProperties.containsProperty(USER_ID_SS))
-         {
-            properties.setUserId(new Binary(typedProperties.getBytesProperty(USER_ID_SS)));
-         }
-         if (typedProperties.containsProperty(SUBJECT_SS))
-         {
-            properties.setSubject(typedProperties.getSimpleStringProperty(SUBJECT_SS).toString());
-         }
-         if (typedProperties.containsProperty(REPLY_TO_SS))
-         {
-            properties.setReplyTo(typedProperties.getSimpleStringProperty(REPLY_TO_SS).toString());
-         }
-         if (typedProperties.containsProperty(CORRELATION_ID_SS))
-         {
-            properties.setCorrelationId(typedProperties.getSimpleStringProperty(CORRELATION_ID_SS).toString());
-         }
-         if (typedProperties.containsProperty(CONTENT_TYPE_SS))
-         {
-            properties.setContentType(Symbol.getSymbol(typedProperties.getSimpleStringProperty(CONTENT_TYPE_SS).toString()));
-         }
-         if (typedProperties.containsProperty(CONTENT_ENCODING_SS))
-         {
-            properties.setContentEncoding(Symbol.getSymbol(typedProperties.getSimpleStringProperty(CONTENT_ENCODING_SS).toString()));
-         }
-         if (typedProperties.containsProperty(ABSOLUTE_EXPIRY_TIME_SS))
-         {
-            calendar.setTimeInMillis(typedProperties.getLongProperty(ABSOLUTE_EXPIRY_TIME_SS));
-            properties.setAbsoluteExpiryTime(calendar.getTime());
-         }
-         if (typedProperties.containsProperty(CREATION_TIME_SS))
-         {
-            calendar.setTimeInMillis(typedProperties.getLongProperty(CREATION_TIME_SS));
-            properties.setCreationTime(calendar.getTime());
-         }
-         if (typedProperties.containsProperty(GROUP_ID_SS))
-         {
-            properties.setGroupId(typedProperties.getSimpleStringProperty(GROUP_ID_SS).toString());
-         }
-         if (typedProperties.containsProperty(GROUP_SEQUENCE_SS))
-         {
-            properties.setGroupSequence(new UnsignedInteger(typedProperties.getIntProperty(GROUP_SEQUENCE_SS)));
-         }
-         if (typedProperties.containsProperty(REPLY_TO_GROUP_ID_SS))
-         {
-            properties.setReplyToGroupId(typedProperties.getSimpleStringProperty(REPLY_TO_GROUP_ID_SS).toString());
-         }
-         return properties;
-      }
-
-      private static ApplicationProperties populateApplicationProperties(ServerMessage message)
-      {
-         HashMap<String, Object> values = new HashMap<String, Object>();
-         for (SimpleString name : message.getPropertyNames())
-         {
-            setProperty(name, message.getTypedProperties().getProperty(name), values);
-         }
-         return new ApplicationProperties(values);
-      }
-
-      private static void setProperty(SimpleString name, Object property, HashMap<String, Object> values)
-      {
-         String s = name.toString();
-         if (SPECIAL_PROPS.contains(s) ||
-            s.startsWith(MESSAGE_ANNOTATIONS) ||
-            s.startsWith(DELIVERY_ANNOTATIONS) ||
-            s.startsWith(FOOTER_VALUES))
-         {
-            return;
-         }
-         if (property instanceof SimpleString)
-         {
-            values.put(s, property.toString());
-         }
-         else
-         {
-            values.put(s, property);
-         }
-      }
-
-      private static Footer populateFooter(ServerMessage message)
-      {
-         HashMap actualValues = new HashMap();
-         Footer footer = new Footer(actualValues);
-         for (SimpleString name : message.getPropertyNames())
-         {
-            String sName = name.toString();
-            if (sName.startsWith(FOOTER_VALUES))
-            {
-               Object val = message.getTypedProperties().getProperty(name);
-               if (val instanceof SimpleString)
-               {
-                  actualValues.put(sName.subSequence(sName.indexOf(FOOTER_VALUES), sName.length()), val.toString());
-               }
-               else
-               {
-                  actualValues.put(sName.subSequence(sName.indexOf(FOOTER_VALUES), sName.length()), val);
-               }
-            }
-         }
-         return footer;
-      }
-
-      private static Section populateBody(ServerMessage message)
-      {
-         // TODO: Depend on array() is most likely not a very good idea
-         Integer type = message.getIntProperty(MESSAGE_TYPE);
-         switch (type)
-         {
-            case 0:
-            case 1:
-               return new Data(new Binary(message.getBodyBuffer().copy().byteBuf().array()));
-            case 2:
-               return new AmqpValue(new Binary(message.getBodyBuffer().copy().byteBuf().array()));
-            case 3:
-               return new AmqpValue(message.getBodyBuffer().copy().readNullableString());
-            default:
-               return new Data(new Binary(message.getBodyBuffer().copy().byteBuf().array()));
-         }
-      }
-   }
-
-   private static long getMessageFormat(MessageFormat messageFormat)
-   {
-      switch (messageFormat)
-      {
-         case AMQP:
-            return 0;
-         case DATA:
-            return 1;
-         case JSON:
-            return 2;
-         case TEXT:
-            return 3;
-         default:
-            return 0;
-
-      }
-   }
-
-   private static MessageFormat getMessageFormat(long messageFormat)
-   {
-      switch ((int) messageFormat)
-      {
-         case 0:
-            return MessageFormat.AMQP;
-         case 1:
-            return MessageFormat.DATA;
-         case 2:
-            return MessageFormat.JSON;
-         case 3:
-            return MessageFormat.TEXT;
-         default:
-            return MessageFormat.AMQP;
-
-      }
-   }
-
-   private static int getMessageType(Message protonMessage)
-   {
-      Section section = protonMessage.getBody();
-      if (section instanceof AmqpValue)
-      {
-         AmqpValue amqpValue = (AmqpValue) section;
-         Object value = amqpValue.getValue();
-         if (value instanceof String)
-         {
-            return TEXT_TYPE;
-         }
-         else if (value instanceof byte[])
-         {
-            return org.hornetq.api.core.Message.BYTES_TYPE;
-         }
-         else if (value instanceof Map)
-         {
-            return org.hornetq.api.core.Message.MAP_TYPE;
-         }
-         else if (value instanceof Object)
-         {
-            return org.hornetq.api.core.Message.OBJECT_TYPE;
-         }
-         else
-         {
-            return org.hornetq.api.core.Message.DEFAULT_TYPE;
-         }
-      }
-      else
-      {
-         return org.hornetq.api.core.Message.DEFAULT_TYPE;
-      }
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/TransactionHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/TransactionHandler.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/TransactionHandler.java
deleted file mode 100644
index 32d5a7a..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/TransactionHandler.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.core.protocol.proton;
-
-import org.apache.qpid.proton.amqp.Symbol;
-import org.apache.qpid.proton.amqp.messaging.Rejected;
-import org.apache.qpid.proton.amqp.transaction.Coordinator;
-import org.apache.qpid.proton.amqp.transport.ErrorCondition;
-import org.apache.qpid.proton.engine.Delivery;
-import org.apache.qpid.proton.engine.Receiver;
-import org.hornetq.api.core.HornetQBuffer;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPException;
-
-/**
- * handles an amqp Coordinator to deal with transaction boundaries etc
- */
-public class TransactionHandler implements ProtonDeliveryHandler
-{
-   private final ProtonRemotingConnection connection;
-   private final Coordinator coordinator;
-   private final ProtonProtocolManager protonProtocolManager;
-   private final ProtonSession protonSession;
-   private final HornetQBuffer buffer;
-
-   public TransactionHandler(ProtonRemotingConnection connection, Coordinator coordinator, ProtonProtocolManager protonProtocolManager, ProtonSession protonSession)
-   {
-      this.connection = connection;
-      this.coordinator = coordinator;
-      this.protonProtocolManager = protonProtocolManager;
-      this.protonSession = protonSession;
-      buffer = connection.createBuffer(1024);
-   }
-
-   @Override
-   public void onMessage(Delivery delivery) throws HornetQAMQPException
-   {
-      Receiver receiver = null;
-      try
-      {
-         receiver = ((Receiver) delivery.getLink());
-
-         if (!delivery.isReadable())
-         {
-            return;
-         }
-
-         protonProtocolManager.handleTransaction(receiver, buffer, delivery, protonSession);
-
-      }
-      catch (Exception e)
-      {
-         e.printStackTrace();
-         Rejected rejected = new Rejected();
-         ErrorCondition condition = new ErrorCondition();
-         condition.setCondition(Symbol.valueOf("failed"));
-         condition.setDescription(e.getMessage());
-         rejected.setError(condition);
-         delivery.disposition(rejected);
-      }
-   }
-
-   @Override
-   public void checkState()
-   {
-      //noop
-   }
-
-   @Override
-   public void close() throws HornetQAMQPException
-   {
-      //noop
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/HornetQJMSVendor.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/HornetQJMSVendor.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/HornetQJMSVendor.java
new file mode 100644
index 0000000..3126b28
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/HornetQJMSVendor.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton.converter;
+
+import javax.jms.BytesMessage;
+import javax.jms.Destination;
+import javax.jms.MapMessage;
+import javax.jms.Message;
+import javax.jms.ObjectMessage;
+import javax.jms.StreamMessage;
+import javax.jms.TextMessage;
+
+import org.apache.qpid.proton.jms.JMSVendor;
+import org.hornetq.core.buffers.impl.ResetLimitWrappedHornetQBuffer;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSBytesMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSMapMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSStreamMessage;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSTextMessage;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.impl.ServerMessageImpl;
+import org.hornetq.utils.IDGenerator;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class HornetQJMSVendor extends JMSVendor
+{
+
+   private final IDGenerator serverGenerator;
+
+   HornetQJMSVendor(IDGenerator idGenerator)
+   {
+      this.serverGenerator = idGenerator;
+   }
+
+   @Override
+   public BytesMessage createBytesMessage()
+   {
+      return new ServerJMSBytesMessage(newMessage(org.hornetq.api.core.Message.BYTES_TYPE), 0);
+   }
+
+   @Override
+   public StreamMessage createStreamMessage()
+   {
+      return new ServerJMSStreamMessage(newMessage(org.hornetq.api.core.Message.STREAM_TYPE), 0);
+   }
+
+   @Override
+   public Message createMessage()
+   {
+      return new ServerJMSMessage(newMessage(org.hornetq.api.core.Message.DEFAULT_TYPE), 0 );
+   }
+
+   @Override
+   public TextMessage createTextMessage()
+   {
+      return new ServerJMSTextMessage(newMessage(org.hornetq.api.core.Message.TEXT_TYPE), 0);
+   }
+
+   @Override
+   public ObjectMessage createObjectMessage()
+   {
+      return null;
+   }
+
+   @Override
+   public MapMessage createMapMessage()
+   {
+      return new ServerJMSMapMessage(newMessage(org.hornetq.api.core.Message.MAP_TYPE), 0);
+   }
+
+   @Override
+   public void setJMSXUserID(Message message, String s)
+   {
+   }
+
+   @Override
+   public Destination createDestination(String name)
+   {
+      return super.createDestination(name);
+   }
+
+   @Override
+   public <T extends Destination> T createDestination(String name, Class<T> kind)
+   {
+      return super.createDestination(name, kind);
+   }
+
+   @Override
+   public void setJMSXGroupID(Message message, String s)
+   {
+
+   }
+
+   @Override
+   public void setJMSXGroupSequence(Message message, int i)
+   {
+
+   }
+
+   @Override
+   public void setJMSXDeliveryCount(Message message, long l)
+   {
+
+   }
+
+
+   public ServerJMSMessage wrapMessage(int messageType, ServerMessage wrapped, int deliveryCount)
+   {
+      switch (messageType)
+      {
+         case org.hornetq.api.core.Message.STREAM_TYPE:
+            return new ServerJMSStreamMessage(wrapped, deliveryCount);
+         case org.hornetq.api.core.Message.BYTES_TYPE:
+            return new ServerJMSBytesMessage(wrapped, deliveryCount);
+         case org.hornetq.api.core.Message.MAP_TYPE:
+            return new ServerJMSMapMessage(wrapped, deliveryCount);
+         case org.hornetq.api.core.Message.TEXT_TYPE:
+            return new ServerJMSTextMessage(wrapped, deliveryCount);
+         default:
+            return new ServerJMSMessage(wrapped, deliveryCount);
+      }
+
+   }
+
+
+   @Override
+   public String toAddress(Destination destination)
+   {
+      return null;
+   }
+
+
+   private ServerMessageImpl newMessage(byte messageType)
+   {
+      ServerMessageImpl message = new ServerMessageImpl(serverGenerator.generateID(), 512);
+      message.setType(messageType);
+      ((ResetLimitWrappedHornetQBuffer)message.getBodyBuffer()).setMessage(null);
+      return message;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/ProtonMessageConverter.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/ProtonMessageConverter.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/ProtonMessageConverter.java
new file mode 100644
index 0000000..495c76a
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/ProtonMessageConverter.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton.converter;
+
+import org.apache.qpid.proton.jms.EncodedMessage;
+import org.apache.qpid.proton.jms.InboundTransformer;
+import org.apache.qpid.proton.jms.JMSMappingInboundTransformer;
+import org.apache.qpid.proton.jms.JMSMappingOutboundTransformer;
+import org.hornetq.core.protocol.proton.converter.jms.ServerJMSMessage;
+import org.hornetq.core.server.ServerMessage;
+import org.hornetq.spi.core.protocol.MessageConverter;
+import org.hornetq.utils.IDGenerator;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonMessageConverter implements MessageConverter
+{
+
+
+   HornetQJMSVendor hornetQJMSVendor;
+
+   public ProtonMessageConverter(IDGenerator idGenerator)
+   {
+      hornetQJMSVendor = new HornetQJMSVendor(idGenerator);
+      inboundTransformer = new JMSMappingInboundTransformer(hornetQJMSVendor);
+      outboundTransformer = new JMSMappingOutboundTransformer(hornetQJMSVendor);
+   }
+
+   private final InboundTransformer inboundTransformer;
+   private final JMSMappingOutboundTransformer outboundTransformer;
+
+   @Override
+   public ServerMessage inbound(Object messageSource) throws Exception
+   {
+      ServerJMSMessage jmsMessage = inboundJMSType((EncodedMessage) messageSource);
+
+      return (ServerMessage)jmsMessage.getInnerMessage();
+   }
+
+   /**
+    * Just create the JMS Part of the inbound (for testing)
+    * @param messageSource
+    * @return
+    * @throws Exception
+    */
+   public ServerJMSMessage inboundJMSType(EncodedMessage messageSource) throws Exception
+   {
+      EncodedMessage encodedMessageSource = messageSource;
+      ServerJMSMessage transformedMessage = (ServerJMSMessage)inboundTransformer.transform(encodedMessageSource);
+
+      transformedMessage.encode();
+
+      return transformedMessage;
+   }
+
+
+   @Override
+   public Object outbound(ServerMessage messageOutbound, int deliveryCount) throws Exception
+   {
+      ServerJMSMessage jmsMessage = hornetQJMSVendor.wrapMessage(messageOutbound.getType(), messageOutbound, deliveryCount);
+      jmsMessage.decode();
+
+      return outboundTransformer.convert(jmsMessage);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java
new file mode 100644
index 0000000..840fb35
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSBytesMessage.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton.converter.jms;
+
+import javax.jms.BytesMessage;
+import javax.jms.JMSException;
+
+import org.hornetq.core.message.impl.MessageImpl;
+import org.hornetq.core.message.impl.MessageInternal;
+
+import static org.hornetq.reader.BytesMessageUtil.bytesMessageReset;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadBoolean;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadByte;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadBytes;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadChar;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadDouble;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadFloat;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadInt;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadLong;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadShort;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadUTF;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadUnsignedByte;
+import static org.hornetq.reader.BytesMessageUtil.bytesReadUnsignedShort;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteBoolean;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteByte;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteBytes;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteChar;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteDouble;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteFloat;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteInt;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteLong;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteObject;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteShort;
+import static org.hornetq.reader.BytesMessageUtil.bytesWriteUTF;
+
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ServerJMSBytesMessage extends ServerJMSMessage implements BytesMessage
+{
+   public ServerJMSBytesMessage(MessageInternal message, int deliveryCount)
+   {
+      super(message, deliveryCount);
+   }
+
+   @Override
+   public long getBodyLength() throws JMSException
+   {
+      return message.getEndOfBodyPosition() - MessageImpl.BODY_OFFSET;
+   }
+
+   @Override
+   public boolean readBoolean() throws JMSException
+   {
+      return bytesReadBoolean(message);
+   }
+
+   @Override
+   public byte readByte() throws JMSException
+   {
+      return bytesReadByte(message);
+   }
+
+   @Override
+   public int readUnsignedByte() throws JMSException
+   {
+      return bytesReadUnsignedByte(message);
+   }
+
+   @Override
+   public short readShort() throws JMSException
+   {
+      return bytesReadShort(message);
+   }
+
+   @Override
+   public int readUnsignedShort() throws JMSException
+   {
+      return bytesReadUnsignedShort(message);
+   }
+
+   @Override
+   public char readChar() throws JMSException
+   {
+      return bytesReadChar(message);
+   }
+
+   @Override
+   public int readInt() throws JMSException
+   {
+      return bytesReadInt(message);
+   }
+
+   @Override
+   public long readLong() throws JMSException
+   {
+      return bytesReadLong(message);
+   }
+
+   @Override
+   public float readFloat() throws JMSException
+   {
+      return bytesReadFloat(message);
+   }
+
+   @Override
+   public double readDouble() throws JMSException
+   {
+      return bytesReadDouble(message);
+   }
+
+   @Override
+   public String readUTF() throws JMSException
+   {
+      return bytesReadUTF(message);
+   }
+
+   @Override
+   public int readBytes(byte[] value) throws JMSException
+   {
+      return bytesReadBytes(message, value);
+   }
+
+   @Override
+   public int readBytes(byte[] value, int length) throws JMSException
+   {
+      return bytesReadBytes(message, value, length);
+   }
+
+   @Override
+   public void writeBoolean(boolean value) throws JMSException
+   {
+      bytesWriteBoolean(message, value);
+
+   }
+
+   @Override
+   public void writeByte(byte value) throws JMSException
+   {
+      bytesWriteByte(message, value);
+   }
+
+   @Override
+   public void writeShort(short value) throws JMSException
+   {
+      bytesWriteShort(message, value);
+   }
+
+   @Override
+   public void writeChar(char value) throws JMSException
+   {
+      bytesWriteChar(message, value);
+   }
+
+   @Override
+   public void writeInt(int value) throws JMSException
+   {
+      bytesWriteInt(message, value);
+   }
+
+   @Override
+   public void writeLong(long value) throws JMSException
+   {
+      bytesWriteLong(message, value);
+   }
+
+   @Override
+   public void writeFloat(float value) throws JMSException
+   {
+      bytesWriteFloat(message, value);
+   }
+
+   @Override
+   public void writeDouble(double value) throws JMSException
+   {
+      bytesWriteDouble(message, value);
+   }
+
+   @Override
+   public void writeUTF(String value) throws JMSException
+   {
+      bytesWriteUTF(message, value);
+   }
+
+   @Override
+   public void writeBytes(byte[] value) throws JMSException
+   {
+      bytesWriteBytes(message, value);
+   }
+
+   @Override
+   public void writeBytes(byte[] value, int offset, int length) throws JMSException
+   {
+      bytesWriteBytes(message, value, offset, length);
+   }
+
+   @Override
+   public void writeObject(Object value) throws JMSException
+   {
+      if (!bytesWriteObject(message, value))
+      {
+         throw new JMSException("Can't make conversion of " + value + " to any known type");
+      }
+   }
+
+   public void encode() throws Exception
+   {
+      super.encode();
+      // this is to make sure we encode the body-length before it's persisted
+      getBodyLength();
+   }
+
+
+   public void decode() throws Exception
+   {
+      super.decode();
+
+   }
+
+   @Override
+   public void reset() throws JMSException
+   {
+      bytesMessageReset(message);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMapMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMapMessage.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMapMessage.java
new file mode 100644
index 0000000..4373098
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMapMessage.java
@@ -0,0 +1,326 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.proton.converter.jms;
+
+import javax.jms.JMSException;
+import javax.jms.MapMessage;
+import javax.jms.MessageFormatException;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.hornetq.api.core.HornetQPropertyConversionException;
+import org.hornetq.api.core.Message;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.message.impl.MessageInternal;
+import org.hornetq.utils.TypedProperties;
+
+import static org.hornetq.reader.MapMessageUtil.readBodyMap;
+import static org.hornetq.reader.MapMessageUtil.writeBodyMap;
+
+/**
+ * HornetQ implementation of a JMS MapMessage.
+ *
+ * @author Norbert Lataille (Norbert.Lataille@m4x.org)
+ * @author <a href="mailto:adrian@jboss.org">Adrian Brock</a>
+ * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:ovidiu@feodorov.com">Ovidiu Feodorov</a>
+ * @author <a href="mailto:ataylor@redhat.com">Andy Taylor</a>
+ * @version $Revision: 3412 $
+ */
+public final class ServerJMSMapMessage extends ServerJMSMessage implements MapMessage
+{
+   // Constants -----------------------------------------------------
+
+   public static final byte TYPE = Message.MAP_TYPE;
+
+   // Attributes ----------------------------------------------------
+
+   private final TypedProperties map = new TypedProperties();
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   /*
+    * This constructor is used to construct messages prior to sending
+    */
+   public ServerJMSMapMessage(MessageInternal message, int deliveryCount)
+   {
+      super(message, deliveryCount);
+
+   }
+
+   // MapMessage implementation -------------------------------------
+
+   public void setBoolean(final String name, final boolean value) throws JMSException
+   {
+      map.putBooleanProperty(new SimpleString(name), value);
+   }
+
+   public void setByte(final String name, final byte value) throws JMSException
+   {
+      map.putByteProperty(new SimpleString(name), value);
+   }
+
+   public void setShort(final String name, final short value) throws JMSException
+   {
+      map.putShortProperty(new SimpleString(name), value);
+   }
+
+   public void setChar(final String name, final char value) throws JMSException
+   {
+      map.putCharProperty(new SimpleString(name), value);
+   }
+
+   public void setInt(final String name, final int value) throws JMSException
+   {
+      map.putIntProperty(new SimpleString(name), value);
+   }
+
+   public void setLong(final String name, final long value) throws JMSException
+   {
+      map.putLongProperty(new SimpleString(name), value);
+   }
+
+   public void setFloat(final String name, final float value) throws JMSException
+   {
+      map.putFloatProperty(new SimpleString(name), value);
+   }
+
+   public void setDouble(final String name, final double value) throws JMSException
+   {
+      map.putDoubleProperty(new SimpleString(name), value);
+   }
+
+   public void setString(final String name, final String value) throws JMSException
+   {
+      map.putSimpleStringProperty(new SimpleString(name), value == null ? null : new SimpleString(value));
+   }
+
+   public void setBytes(final String name, final byte[] value) throws JMSException
+   {
+      map.putBytesProperty(new SimpleString(name), value);
+   }
+
+   public void setBytes(final String name, final byte[] value, final int offset, final int length) throws JMSException
+   {
+      if (offset + length > value.length)
+      {
+         throw new JMSException("Invalid offset/length");
+      }
+      byte[] newBytes = new byte[length];
+      System.arraycopy(value, offset, newBytes, 0, length);
+      map.putBytesProperty(new SimpleString(name), newBytes);
+   }
+
+   public void setObject(final String name, final Object value) throws JMSException
+   {
+      try
+      {
+         TypedProperties.setObjectProperty(new SimpleString(name), value, map);
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public boolean getBoolean(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getBooleanProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public byte getByte(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getByteProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public short getShort(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getShortProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public char getChar(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getCharProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public int getInt(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getIntProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public long getLong(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getLongProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public float getFloat(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getFloatProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public double getDouble(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getDoubleProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public String getString(final String name) throws JMSException
+   {
+      try
+      {
+         SimpleString str = map.getSimpleStringProperty(new SimpleString(name));
+         if (str == null)
+         {
+            return null;
+         }
+         else
+         {
+            return str.toString();
+         }
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public byte[] getBytes(final String name) throws JMSException
+   {
+      try
+      {
+         return map.getBytesProperty(new SimpleString(name));
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+   }
+
+   public Object getObject(final String name) throws JMSException
+   {
+      Object val = map.getProperty(new SimpleString(name));
+
+      if (val instanceof SimpleString)
+      {
+         val = ((SimpleString) val).toString();
+      }
+
+      return val;
+   }
+
+   public Enumeration getMapNames() throws JMSException
+   {
+      Set<SimpleString> simplePropNames = map.getPropertyNames();
+      Set<String> propNames = new HashSet<String>(simplePropNames.size());
+
+      for (SimpleString str : simplePropNames)
+      {
+         propNames.add(str.toString());
+      }
+
+      return Collections.enumeration(propNames);
+   }
+
+   public boolean itemExists(final String name) throws JMSException
+   {
+      return map.containsProperty(new SimpleString(name));
+   }
+
+
+   @Override
+   public void clearBody() throws JMSException
+   {
+      super.clearBody();
+
+      map.clear();
+   }
+
+
+   public void encode() throws Exception
+   {
+      super.encode();
+      writeBodyMap(message, map);
+   }
+
+   public void decode() throws Exception
+   {
+      super.decode();
+      readBodyMap(message, map);
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMessage.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMessage.java
new file mode 100644
index 0000000..2c5e6e2
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSMessage.java
@@ -0,0 +1,435 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.proton.converter.jms;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import java.util.Collections;
+import java.util.Enumeration;
+
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.message.impl.MessageInternal;
+import org.hornetq.jms.client.HornetQDestination;
+import org.hornetq.jms.client.HornetQQueue;
+import org.hornetq.reader.MessageUtil;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ServerJMSMessage implements Message
+{
+   protected final MessageInternal message;
+
+   protected int deliveryCount;
+
+   public MessageInternal getInnerMessage()
+   {
+      return message;
+   }
+
+
+   public ServerJMSMessage(MessageInternal message, int deliveryCount)
+   {
+      this.message = message;
+      this.deliveryCount = deliveryCount;
+   }
+
+
+   @Override
+   public final String getJMSMessageID() throws JMSException
+   {
+      return null;
+   }
+
+   @Override
+   public final void setJMSMessageID(String id) throws JMSException
+   {
+   }
+
+   @Override
+   public final long getJMSTimestamp() throws JMSException
+   {
+      return message.getTimestamp();
+   }
+
+   @Override
+   public final void setJMSTimestamp(long timestamp) throws JMSException
+   {
+      message.setTimestamp(timestamp);
+   }
+
+
+   @Override
+   public final byte[] getJMSCorrelationIDAsBytes() throws JMSException
+   {
+      return MessageUtil.getJMSCorrelationIDAsBytes(message);
+   }
+
+   @Override
+   public final void setJMSCorrelationIDAsBytes(byte[] correlationID) throws JMSException
+   {
+      try
+      {
+         MessageUtil.setJMSCorrelationIDAsBytes(message, correlationID);
+      }
+      catch (HornetQException e)
+      {
+         throw new JMSException(e.getMessage());
+      }
+   }
+
+   @Override
+   public final void setJMSCorrelationID(String correlationID) throws JMSException
+   {
+      MessageUtil.setJMSCorrelationID(message, correlationID);
+   }
+
+   @Override
+   public final String getJMSCorrelationID() throws JMSException
+   {
+      return MessageUtil.getJMSCorrelationID(message);
+   }
+
+   @Override
+   public final Destination getJMSReplyTo() throws JMSException
+   {
+      SimpleString reply = MessageUtil.getJMSReplyTo(message);
+      if (reply != null)
+      {
+         return HornetQDestination.fromAddress(reply.toString());
+      }
+      else
+      {
+         return null;
+      }
+   }
+
+   @Override
+   public final void setJMSReplyTo(Destination replyTo) throws JMSException
+   {
+      MessageUtil.setJMSReplyTo(message, replyTo == null ? null : ((HornetQDestination) replyTo).getSimpleAddress());
+
+   }
+
+   public final Destination getJMSDestination() throws JMSException
+   {
+      SimpleString sdest = message.getAddress();
+
+      if (sdest == null)
+      {
+         return null;
+      }
+      else
+      {
+         if (!sdest.toString().startsWith("jms."))
+         {
+            return new HornetQQueue(sdest.toString(), sdest.toString());
+         }
+         else
+         {
+            return HornetQDestination.fromAddress(sdest.toString());
+         }
+      }
+   }
+
+   @Override
+   public final void setJMSDestination(Destination destination) throws JMSException
+   {
+      if (destination == null)
+      {
+         message.setAddress(null);
+      }
+      else
+      {
+         message.setAddress(((HornetQDestination) destination).getSimpleAddress());
+      }
+
+   }
+
+   @Override
+   public final int getJMSDeliveryMode() throws JMSException
+   {
+      return message.isDurable() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT;
+   }
+
+   @Override
+   public final void setJMSDeliveryMode(int deliveryMode) throws JMSException
+   {
+      if (deliveryMode == DeliveryMode.PERSISTENT)
+      {
+         message.setDurable(true);
+      }
+      else if (deliveryMode == DeliveryMode.NON_PERSISTENT)
+      {
+         message.setDurable(false);
+      }
+      else
+      {
+         throw new JMSException("Invalid mode " + deliveryMode);
+      }
+   }
+
+   @Override
+   public final boolean getJMSRedelivered() throws JMSException
+   {
+      return false;
+   }
+
+   @Override
+   public final void setJMSRedelivered(boolean redelivered) throws JMSException
+   {
+      // no op
+   }
+
+   @Override
+   public final String getJMSType() throws JMSException
+   {
+      return MessageUtil.getJMSType(message);
+   }
+
+   @Override
+   public final void setJMSType(String type) throws JMSException
+   {
+      MessageUtil.setJMSType(message, type);
+   }
+
+   @Override
+   public final long getJMSExpiration() throws JMSException
+   {
+      return message.getExpiration();
+   }
+
+   @Override
+   public final void setJMSExpiration(long expiration) throws JMSException
+   {
+      message.setExpiration(expiration);
+   }
+
+   @Override
+   public final long getJMSDeliveryTime() throws JMSException
+   {
+      // no op
+      return 0;
+   }
+
+   @Override
+   public final void setJMSDeliveryTime(long deliveryTime) throws JMSException
+   {
+      // no op
+   }
+
+   @Override
+   public final int getJMSPriority() throws JMSException
+   {
+      return message.getPriority();
+   }
+
+   @Override
+   public final void setJMSPriority(int priority) throws JMSException
+   {
+      message.setPriority((byte) priority);
+   }
+
+   @Override
+   public final void clearProperties() throws JMSException
+   {
+      MessageUtil.clearProperties(message);
+
+   }
+
+   @Override
+   public final boolean propertyExists(String name) throws JMSException
+   {
+      return MessageUtil.propertyExists(message, name);
+   }
+
+   @Override
+   public final boolean getBooleanProperty(String name) throws JMSException
+   {
+      return message.getBooleanProperty(name);
+   }
+
+   @Override
+   public final byte getByteProperty(String name) throws JMSException
+   {
+      return message.getByteProperty(name);
+   }
+
+   @Override
+   public final short getShortProperty(String name) throws JMSException
+   {
+      return message.getShortProperty(name);
+   }
+
+   @Override
+   public final int getIntProperty(String name) throws JMSException
+   {
+      if (MessageUtil.JMSXDELIVERYCOUNT.equals(name))
+      {
+         return deliveryCount;
+      }
+
+      return message.getIntProperty(name);
+   }
+
+   @Override
+   public final long getLongProperty(String name) throws JMSException
+   {
+      if (MessageUtil.JMSXDELIVERYCOUNT.equals(name))
+      {
+         return deliveryCount;
+      }
+
+      return message.getLongProperty(name);
+   }
+
+   @Override
+   public final float getFloatProperty(String name) throws JMSException
+   {
+      return message.getFloatProperty(name);
+   }
+
+   @Override
+   public final double getDoubleProperty(String name) throws JMSException
+   {
+      return message.getDoubleProperty(name);
+   }
+
+   @Override
+   public final String getStringProperty(String name) throws JMSException
+   {
+      if (MessageUtil.JMSXDELIVERYCOUNT.equals(name))
+      {
+         return String.valueOf(deliveryCount);
+      }
+
+
+      return message.getStringProperty(name);
+   }
+
+   @Override
+   public final Object getObjectProperty(String name) throws JMSException
+   {
+      Object val = message.getObjectProperty(name);
+      if (val instanceof SimpleString)
+      {
+         val = ((SimpleString)val).toString();
+      }
+      return val;
+   }
+
+   @Override
+   public final Enumeration getPropertyNames() throws JMSException
+   {
+      return Collections.enumeration(MessageUtil.getPropertyNames(message));
+   }
+
+   @Override
+   public final void setBooleanProperty(String name, boolean value) throws JMSException
+   {
+      message.putBooleanProperty(name, value);
+   }
+
+   @Override
+   public final void setByteProperty(String name, byte value) throws JMSException
+   {
+      message.putByteProperty(name, value);
+   }
+
+   @Override
+   public final void setShortProperty(String name, short value) throws JMSException
+   {
+      message.putShortProperty(name, value);
+   }
+
+   @Override
+   public final void setIntProperty(String name, int value) throws JMSException
+   {
+      message.putIntProperty(name, value);
+   }
+
+   @Override
+   public final void setLongProperty(String name, long value) throws JMSException
+   {
+      message.putLongProperty(name, value);
+   }
+
+   @Override
+   public final void setFloatProperty(String name, float value) throws JMSException
+   {
+      message.putFloatProperty(name, value);
+   }
+
+   @Override
+   public final void setDoubleProperty(String name, double value) throws JMSException
+   {
+      message.putDoubleProperty(name, value);
+   }
+
+   @Override
+   public final void setStringProperty(String name, String value) throws JMSException
+   {
+      message.putStringProperty(name, value);
+   }
+
+   @Override
+   public final void setObjectProperty(String name, Object value) throws JMSException
+   {
+      message.putObjectProperty(name, value);
+   }
+
+   @Override
+   public final void acknowledge() throws JMSException
+   {
+      // no op
+   }
+
+   @Override
+   public void clearBody() throws JMSException
+   {
+      message.getBodyBuffer().clear();
+   }
+
+   @Override
+   public final <T> T getBody(Class<T> c) throws JMSException
+   {
+      // no op.. jms2 not used on the conversion
+      return null;
+   }
+
+   /**
+    * Encode the body into the internal message
+    */
+   public void encode() throws Exception
+   {
+      message.getBodyBuffer().resetReaderIndex();
+   }
+
+
+   public void decode() throws Exception
+   {
+      message.getBodyBuffer().resetReaderIndex();
+   }
+
+   @Override
+   public final boolean isBodyAssignableTo(Class c) throws JMSException
+   {
+      // no op.. jms2 not used on the conversion
+      return false;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java
new file mode 100644
index 0000000..14a5954
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSStreamMessage.java
@@ -0,0 +1,417 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.proton.converter.jms;
+
+import javax.jms.JMSException;
+import javax.jms.MessageEOFException;
+import javax.jms.MessageFormatException;
+import javax.jms.StreamMessage;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.Message;
+import org.hornetq.api.core.Pair;
+import org.hornetq.core.message.impl.MessageInternal;
+import org.hornetq.utils.DataConstants;
+
+import static org.hornetq.reader.MessageUtil.getBodyBuffer;
+import static org.hornetq.reader.StreamMessageUtil.streamReadBoolean;
+import static org.hornetq.reader.StreamMessageUtil.streamReadByte;
+import static org.hornetq.reader.StreamMessageUtil.streamReadBytes;
+import static org.hornetq.reader.StreamMessageUtil.streamReadChar;
+import static org.hornetq.reader.StreamMessageUtil.streamReadDouble;
+import static org.hornetq.reader.StreamMessageUtil.streamReadFloat;
+import static org.hornetq.reader.StreamMessageUtil.streamReadInteger;
+import static org.hornetq.reader.StreamMessageUtil.streamReadLong;
+import static org.hornetq.reader.StreamMessageUtil.streamReadObject;
+import static org.hornetq.reader.StreamMessageUtil.streamReadShort;
+import static org.hornetq.reader.StreamMessageUtil.streamReadString;
+
+public final class ServerJMSStreamMessage extends ServerJMSMessage implements StreamMessage
+{
+   public static final byte TYPE = Message.STREAM_TYPE;
+
+   private int bodyLength = 0;
+
+
+   public ServerJMSStreamMessage(MessageInternal message, int deliveryCount)
+   {
+      super(message, deliveryCount);
+
+   }
+
+   // StreamMessage implementation ----------------------------------
+
+   public boolean readBoolean() throws JMSException
+   {
+      try
+      {
+         return streamReadBoolean(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public byte readByte() throws JMSException
+   {
+      try
+      {
+         return streamReadByte(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public short readShort() throws JMSException
+   {
+
+      try
+      {
+         return streamReadShort(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public char readChar() throws JMSException
+   {
+
+      try
+      {
+         return streamReadChar(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public int readInt() throws JMSException
+   {
+
+      try
+      {
+         return streamReadInteger(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public long readLong() throws JMSException
+   {
+
+      try
+      {
+         return streamReadLong(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public float readFloat() throws JMSException
+   {
+
+      try
+      {
+         return streamReadFloat(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public double readDouble() throws JMSException
+   {
+
+      try
+      {
+         return streamReadDouble(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public String readString() throws JMSException
+   {
+
+      try
+      {
+         return streamReadString(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   /**
+    * len here is used to control how many more bytes to read
+    */
+   private int len = 0;
+
+   public int readBytes(final byte[] value) throws JMSException
+   {
+
+      try
+      {
+         Pair<Integer, Integer> pairRead = streamReadBytes(message, len, value);
+
+         len = pairRead.getA();
+         return pairRead.getB();
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public Object readObject() throws JMSException
+   {
+
+      if (getBodyBuffer(message).readerIndex() >= message.getEndOfBodyPosition())
+      {
+         throw new MessageEOFException("");
+      }
+      try
+      {
+         return streamReadObject(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
+      }
+      catch (IndexOutOfBoundsException e)
+      {
+         throw new MessageEOFException("");
+      }
+   }
+
+   public void writeBoolean(final boolean value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.BOOLEAN);
+      getBuffer().writeBoolean(value);
+   }
+
+   public void writeByte(final byte value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.BYTE);
+      getBuffer().writeByte(value);
+   }
+
+   public void writeShort(final short value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.SHORT);
+      getBuffer().writeShort(value);
+   }
+
+   public void writeChar(final char value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.CHAR);
+      getBuffer().writeShort((short) value);
+   }
+
+   public void writeInt(final int value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.INT);
+      getBuffer().writeInt(value);
+   }
+
+   public void writeLong(final long value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.LONG);
+      getBuffer().writeLong(value);
+   }
+
+   public void writeFloat(final float value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.FLOAT);
+      getBuffer().writeInt(Float.floatToIntBits(value));
+   }
+
+   public void writeDouble(final double value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.DOUBLE);
+      getBuffer().writeLong(Double.doubleToLongBits(value));
+   }
+
+   public void writeString(final String value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.STRING);
+      getBuffer().writeNullableString(value);
+   }
+
+   public void writeBytes(final byte[] value) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.BYTES);
+      getBuffer().writeInt(value.length);
+      getBuffer().writeBytes(value);
+   }
+
+   public void writeBytes(final byte[] value, final int offset, final int length) throws JMSException
+   {
+
+      getBuffer().writeByte(DataConstants.BYTES);
+      getBuffer().writeInt(length);
+      getBuffer().writeBytes(value, offset, length);
+   }
+
+   public void writeObject(final Object value) throws JMSException
+   {
+      if (value instanceof String)
+      {
+         writeString((String) value);
+      }
+      else if (value instanceof Boolean)
+      {
+         writeBoolean((Boolean) value);
+      }
+      else if (value instanceof Byte)
+      {
+         writeByte((Byte) value);
+      }
+      else if (value instanceof Short)
+      {
+         writeShort((Short) value);
+      }
+      else if (value instanceof Integer)
+      {
+         writeInt((Integer) value);
+      }
+      else if (value instanceof Long)
+      {
+         writeLong((Long) value);
+      }
+      else if (value instanceof Float)
+      {
+         writeFloat((Float) value);
+      }
+      else if (value instanceof Double)
+      {
+         writeDouble((Double) value);
+      }
+      else if (value instanceof byte[])
+      {
+         writeBytes((byte[]) value);
+      }
+      else if (value instanceof Character)
+      {
+         writeChar((Character) value);
+      }
+      else if (value == null)
+      {
+         writeString(null);
+      }
+      else
+      {
+         throw new MessageFormatException("Invalid object type: " + value.getClass());
+      }
+   }
+
+   public void reset() throws JMSException
+   {
+      getBuffer().resetReaderIndex();
+   }
+
+   // HornetQRAMessage overrides ----------------------------------------
+
+   @Override
+   public void clearBody() throws JMSException
+   {
+      super.clearBody();
+
+      getBuffer().clear();
+   }
+
+   private HornetQBuffer getBuffer()
+   {
+      return message.getBodyBuffer();
+   }
+
+
+   public void decode() throws Exception
+   {
+      super.decode();
+   }
+
+   /**
+    * Encode the body into the internal message
+    */
+   public void encode() throws Exception
+   {
+      super.encode();
+      bodyLength = message.getEndOfBodyPosition();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSTextMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSTextMessage.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSTextMessage.java
new file mode 100644
index 0000000..5455e6e
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/ServerJMSTextMessage.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.proton.converter.jms;
+
+import javax.jms.JMSException;
+import javax.jms.TextMessage;
+
+import org.hornetq.api.core.Message;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.message.impl.MessageInternal;
+
+import static org.hornetq.reader.TextMessageUtil.readBodyText;
+import static org.hornetq.reader.TextMessageUtil.writeBodyText;
+
+
+/**
+ * HornetQ implementation of a JMS TextMessage.
+ * <br>
+ * This class was ported from SpyTextMessage in JBossMQ.
+ *
+ * @author Norbert Lataille (Norbert.Lataille@m4x.org)
+ * @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
+ * @author <a href="mailto:adrian@jboss.org">Adrian Brock</a>
+ * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:ovidiu@feodorov.com">Ovidiu Feodorov</a>
+ * @author <a href="mailto:ataylor@redhat.com">Andy Taylor</a>
+ * @version $Revision: 3412 $
+ */
+public class ServerJMSTextMessage extends ServerJMSMessage implements TextMessage
+{
+   // Constants -----------------------------------------------------
+
+   public static final byte TYPE = Message.TEXT_TYPE;
+
+   // Attributes ----------------------------------------------------
+
+   // We cache it locally - it's more performant to cache as a SimpleString, the AbstractChannelBuffer write
+   // methods are more efficient for a SimpleString
+   private SimpleString text;
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   /*
+    * This constructor is used to construct messages prior to sending
+    */
+   public ServerJMSTextMessage(MessageInternal message, int deliveryCount)
+   {
+      super(message, deliveryCount);
+
+   }
+   // TextMessage implementation ------------------------------------
+
+   public void setText(final String text) throws JMSException
+   {
+      if (text != null)
+      {
+         this.text = new SimpleString(text);
+      }
+      else
+      {
+         this.text = null;
+      }
+
+      writeBodyText(message, this.text);
+   }
+
+   public String getText()
+   {
+      if (text != null)
+      {
+         return text.toString();
+      }
+      else
+      {
+         return null;
+      }
+   }
+
+   @Override
+   public void clearBody() throws JMSException
+   {
+      super.clearBody();
+
+      text = null;
+   }
+
+
+   public void encode() throws Exception
+   {
+      super.encode();
+      writeBodyText(message, text);
+   }
+
+   public void decode() throws Exception
+   {
+      super.decode();
+      text = readBodyText(message);
+   }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/package-info.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/package-info.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/package-info.java
new file mode 100644
index 0000000..acc5a0d
--- /dev/null
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/converter/jms/package-info.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+
+/**
+ * This package contains incomplete JMS implementations just to be used with converting amqp to hornetq and
+ * vice versa
+ * @author Clebert Suconic
+ */
+
+package org.hornetq.core.protocol.proton.converter.jms;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPException.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPException.java
deleted file mode 100644
index 03f797d..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPException.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton.exceptions;
-
-import org.apache.qpid.proton.amqp.Symbol;
-import org.hornetq.api.core.HornetQException;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         6/6/13
- */
-public class HornetQAMQPException extends HornetQException
-{
-
-   private static final String ERROR_PREFIX = "amqp:";
-
-   public Symbol getAmqpError()
-   {
-      return amqpError;
-   }
-
-   private final Symbol amqpError;
-
-   public HornetQAMQPException(Symbol amqpError, String message)
-   {
-      super(message);
-      this.amqpError = amqpError;
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPIllegalStateException.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPIllegalStateException.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPIllegalStateException.java
deleted file mode 100644
index 0792f88..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/exceptions/HornetQAMQPIllegalStateException.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton.exceptions;
-
-import org.apache.qpid.proton.amqp.transport.AmqpError;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         6/6/13
- */
-public class HornetQAMQPIllegalStateException extends HornetQAMQPException
-{
-   public HornetQAMQPIllegalStateException(String message)
-   {
-      super(AmqpError.ILLEGAL_STATE, message);
-   }
-}


[25/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/impl/ConfigurationImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/impl/ConfigurationImpl.java b/hornetq-server/src/main/java/org/hornetq/core/config/impl/ConfigurationImpl.java
index 98c0d85..5d7f57c 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/impl/ConfigurationImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/impl/ConfigurationImpl.java
@@ -29,16 +29,19 @@ import org.hornetq.api.core.BroadcastGroupConfiguration;
 import org.hornetq.api.core.DiscoveryGroupConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.core.config.BackupStrategy;
 import org.hornetq.core.config.BridgeConfiguration;
 import org.hornetq.core.config.ClusterConnectionConfiguration;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.ConnectorServiceConfiguration;
 import org.hornetq.core.config.CoreQueueConfiguration;
 import org.hornetq.core.config.DivertConfiguration;
+import org.hornetq.core.config.HAPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicaPolicyConfiguration;
+import org.hornetq.core.config.ha.ReplicatedPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.security.Role;
 import org.hornetq.core.server.JournalType;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.core.server.group.impl.GroupingHandlerConfiguration;
 import org.hornetq.core.settings.impl.AddressSettings;
 
@@ -200,21 +203,15 @@ public class ConfigurationImpl implements Configuration
 
    protected List<ConnectorServiceConfiguration> connectorServiceConfigurations = new ArrayList<ConnectorServiceConfiguration>();
 
-   private boolean checkForLiveServer = HornetQDefaultConfiguration.isDefaultCheckForLiveServer();
-
    private boolean maskPassword = HornetQDefaultConfiguration.isDefaultMaskPassword();
 
    private transient String passwordCodec;
 
    private boolean resolveProtocols = HornetQDefaultConfiguration.isDefaultResolveProtocols();
 
-   private Set<Configuration> backupServerConfigurations = new HashSet<>();
-
-   private BackupStrategy backupStrategy;
-
    private long journalLockAcquisitionTimeout = HornetQDefaultConfiguration.getDefaultJournalLockAcquisitionTimeout();
 
-   private HAPolicy haPolicy = new HAPolicy();
+   private HAPolicyConfiguration haPolicyConfiguration;
 
    // Public -------------------------------------------------------------------------
 
@@ -223,32 +220,15 @@ public class ConfigurationImpl implements Configuration
       return !getClusterConfigurations().isEmpty();
    }
 
-   @Deprecated
-   public boolean isAllowAutoFailBack()
-   {
-      return haPolicy.isAllowAutoFailBack();
-   }
-
-   @Deprecated
-   public void setAllowAutoFailBack(boolean allowAutoFailBack)
-   {
-      haPolicy.setAllowAutoFailBack(allowAutoFailBack);
-   }
-
-   @Deprecated
-   public boolean isBackup()
-   {
-      return haPolicy.isBackup();
-   }
-
    public boolean isFileDeploymentEnabled()
    {
       return fileDeploymentEnabled;
    }
 
-   public void setFileDeploymentEnabled(final boolean enable)
+   public ConfigurationImpl setFileDeploymentEnabled(final boolean enable)
    {
       fileDeploymentEnabled = enable;
+      return this;
    }
 
    public boolean isPersistenceEnabled()
@@ -256,9 +236,10 @@ public class ConfigurationImpl implements Configuration
       return persistenceEnabled;
    }
 
-   public void setPersistenceEnabled(final boolean enable)
+   public ConfigurationImpl setPersistenceEnabled(final boolean enable)
    {
       persistenceEnabled = enable;
+      return this;
    }
 
    public long getFileDeployerScanPeriod()
@@ -266,9 +247,10 @@ public class ConfigurationImpl implements Configuration
       return fileDeploymentScanPeriod;
    }
 
-   public void setFileDeployerScanPeriod(final long period)
+   public ConfigurationImpl setFileDeployerScanPeriod(final long period)
    {
       fileDeploymentScanPeriod = period;
+      return this;
    }
 
    /**
@@ -279,27 +261,10 @@ public class ConfigurationImpl implements Configuration
       return persistDeliveryCountBeforeDelivery;
    }
 
-   public void setPersistDeliveryCountBeforeDelivery(final boolean persistDeliveryCountBeforeDelivery)
+   public ConfigurationImpl setPersistDeliveryCountBeforeDelivery(final boolean persistDeliveryCountBeforeDelivery)
    {
       this.persistDeliveryCountBeforeDelivery = persistDeliveryCountBeforeDelivery;
-   }
-
-   @Deprecated
-   public void setBackup(final boolean backup)
-   {
-      // this is done via the haPolicy now
-   }
-
-   @Deprecated
-   public boolean isSharedStore()
-   {
-      return haPolicy.isSharedStore();
-   }
-
-   @Deprecated
-   public void setSharedStore(final boolean sharedStore)
-   {
-      // this is done via the haPolicy now
+      return this;
    }
 
    public int getScheduledThreadPoolMaxSize()
@@ -307,9 +272,10 @@ public class ConfigurationImpl implements Configuration
       return scheduledThreadPoolMaxSize;
    }
 
-   public void setScheduledThreadPoolMaxSize(final int maxSize)
+   public ConfigurationImpl setScheduledThreadPoolMaxSize(final int maxSize)
    {
       scheduledThreadPoolMaxSize = maxSize;
+      return this;
    }
 
    public int getThreadPoolMaxSize()
@@ -317,9 +283,10 @@ public class ConfigurationImpl implements Configuration
       return threadPoolMaxSize;
    }
 
-   public void setThreadPoolMaxSize(final int maxSize)
+   public ConfigurationImpl setThreadPoolMaxSize(final int maxSize)
    {
       threadPoolMaxSize = maxSize;
+      return this;
    }
 
    public long getSecurityInvalidationInterval()
@@ -327,9 +294,10 @@ public class ConfigurationImpl implements Configuration
       return securityInvalidationInterval;
    }
 
-   public void setSecurityInvalidationInterval(final long interval)
+   public ConfigurationImpl setSecurityInvalidationInterval(final long interval)
    {
       securityInvalidationInterval = interval;
+      return this;
    }
 
    public long getConnectionTTLOverride()
@@ -337,9 +305,10 @@ public class ConfigurationImpl implements Configuration
       return connectionTTLOverride;
    }
 
-   public void setConnectionTTLOverride(final long ttl)
+   public ConfigurationImpl setConnectionTTLOverride(final long ttl)
    {
       connectionTTLOverride = ttl;
+      return this;
    }
 
    public boolean isAsyncConnectionExecutionEnabled()
@@ -347,9 +316,10 @@ public class ConfigurationImpl implements Configuration
       return asyncConnectionExecutionEnabled;
    }
 
-   public void setEnabledAsyncConnectionExecution(final boolean enabled)
+   public ConfigurationImpl setEnabledAsyncConnectionExecution(final boolean enabled)
    {
       asyncConnectionExecutionEnabled = enabled;
+      return this;
    }
 
    @Deprecated
@@ -361,9 +331,10 @@ public class ConfigurationImpl implements Configuration
 
    @Deprecated
    @Override
-   public void setInterceptorClassNames(final List<String> interceptors)
+   public ConfigurationImpl setInterceptorClassNames(final List<String> interceptors)
    {
       setIncomingInterceptorClassNames(interceptors);
+      return this;
    }
 
    public List<String> getIncomingInterceptorClassNames()
@@ -371,9 +342,10 @@ public class ConfigurationImpl implements Configuration
       return incomingInterceptorClassNames;
    }
 
-   public void setIncomingInterceptorClassNames(final List<String> interceptors)
+   public ConfigurationImpl setIncomingInterceptorClassNames(final List<String> interceptors)
    {
       incomingInterceptorClassNames = interceptors;
+      return this;
    }
 
    public List<String> getOutgoingInterceptorClassNames()
@@ -381,9 +353,10 @@ public class ConfigurationImpl implements Configuration
       return outgoingInterceptorClassNames;
    }
 
-   public void setOutgoingInterceptorClassNames(final List<String> interceptors)
+   public ConfigurationImpl setOutgoingInterceptorClassNames(final List<String> interceptors)
    {
       outgoingInterceptorClassNames = interceptors;
+      return this;
    }
 
    public Set<TransportConfiguration> getAcceptorConfigurations()
@@ -391,9 +364,22 @@ public class ConfigurationImpl implements Configuration
       return acceptorConfigs;
    }
 
-   public void setAcceptorConfigurations(final Set<TransportConfiguration> infos)
+   public ConfigurationImpl setAcceptorConfigurations(final Set<TransportConfiguration> infos)
    {
       acceptorConfigs = infos;
+      return this;
+   }
+
+   public ConfigurationImpl addAcceptorConfiguration(final TransportConfiguration infos)
+   {
+      acceptorConfigs.add(infos);
+      return this;
+   }
+
+   public ConfigurationImpl clearAcceptorConfigurations()
+   {
+      acceptorConfigs.clear();
+      return this;
    }
 
    public Map<String, TransportConfiguration> getConnectorConfigurations()
@@ -401,9 +387,16 @@ public class ConfigurationImpl implements Configuration
       return connectorConfigs;
    }
 
-   public void setConnectorConfigurations(final Map<String, TransportConfiguration> infos)
+   public ConfigurationImpl setConnectorConfigurations(final Map<String, TransportConfiguration> infos)
    {
       connectorConfigs = infos;
+      return this;
+   }
+
+   public ConfigurationImpl addConnectorConfiguration(final String key, final TransportConfiguration info)
+   {
+      connectorConfigs.put(key, info);
+      return this;
    }
 
    public GroupingHandlerConfiguration getGroupingHandlerConfiguration()
@@ -411,9 +404,10 @@ public class ConfigurationImpl implements Configuration
       return groupingHandlerConfiguration;
    }
 
-   public void setGroupingHandlerConfiguration(final GroupingHandlerConfiguration groupingHandlerConfiguration)
+   public ConfigurationImpl setGroupingHandlerConfiguration(final GroupingHandlerConfiguration groupingHandlerConfiguration)
    {
       this.groupingHandlerConfiguration = groupingHandlerConfiguration;
+      return this;
    }
 
    public List<BridgeConfiguration> getBridgeConfigurations()
@@ -421,9 +415,16 @@ public class ConfigurationImpl implements Configuration
       return bridgeConfigurations;
    }
 
-   public void setBridgeConfigurations(final List<BridgeConfiguration> configs)
+   public ConfigurationImpl setBridgeConfigurations(final List<BridgeConfiguration> configs)
    {
       bridgeConfigurations = configs;
+      return this;
+   }
+
+   public ConfigurationImpl addBridgeConfiguration(final BridgeConfiguration config)
+   {
+      bridgeConfigurations.add(config);
+      return this;
    }
 
    public List<BroadcastGroupConfiguration> getBroadcastGroupConfigurations()
@@ -431,9 +432,16 @@ public class ConfigurationImpl implements Configuration
       return broadcastGroupConfigurations;
    }
 
-   public void setBroadcastGroupConfigurations(final List<BroadcastGroupConfiguration> configs)
+   public ConfigurationImpl setBroadcastGroupConfigurations(final List<BroadcastGroupConfiguration> configs)
    {
       broadcastGroupConfigurations = configs;
+      return this;
+   }
+
+   public ConfigurationImpl addBroadcastGroupConfiguration(final BroadcastGroupConfiguration config)
+   {
+      broadcastGroupConfigurations.add(config);
+      return this;
    }
 
    public List<ClusterConnectionConfiguration> getClusterConfigurations()
@@ -441,9 +449,22 @@ public class ConfigurationImpl implements Configuration
       return clusterConfigurations;
    }
 
-   public void setClusterConfigurations(final List<ClusterConnectionConfiguration> configs)
+   public ConfigurationImpl setClusterConfigurations(final List<ClusterConnectionConfiguration> configs)
    {
       clusterConfigurations = configs;
+      return this;
+   }
+
+   public ConfigurationImpl addClusterConfiguration(final ClusterConnectionConfiguration config)
+   {
+      clusterConfigurations.add(config);
+      return this;
+   }
+
+   public ConfigurationImpl clearClusterConfigurations()
+   {
+      clusterConfigurations.clear();
+      return this;
    }
 
    public List<DivertConfiguration> getDivertConfigurations()
@@ -451,9 +472,16 @@ public class ConfigurationImpl implements Configuration
       return divertConfigurations;
    }
 
-   public void setDivertConfigurations(final List<DivertConfiguration> configs)
+   public ConfigurationImpl setDivertConfigurations(final List<DivertConfiguration> configs)
    {
       divertConfigurations = configs;
+      return this;
+   }
+
+   public ConfigurationImpl addDivertConfiguration(final DivertConfiguration config)
+   {
+      divertConfigurations.add(config);
+      return this;
    }
 
    public List<CoreQueueConfiguration> getQueueConfigurations()
@@ -461,9 +489,16 @@ public class ConfigurationImpl implements Configuration
       return queueConfigurations;
    }
 
-   public void setQueueConfigurations(final List<CoreQueueConfiguration> configs)
+   public ConfigurationImpl setQueueConfigurations(final List<CoreQueueConfiguration> configs)
    {
       queueConfigurations = configs;
+      return this;
+   }
+
+   public ConfigurationImpl addQueueConfiguration(final CoreQueueConfiguration config)
+   {
+      queueConfigurations.add(config);
+      return this;
    }
 
    public Map<String, DiscoveryGroupConfiguration> getDiscoveryGroupConfigurations()
@@ -471,9 +506,16 @@ public class ConfigurationImpl implements Configuration
       return discoveryGroupConfigurations;
    }
 
-   public void setDiscoveryGroupConfigurations(final Map<String, DiscoveryGroupConfiguration> discoveryGroupConfigurations)
+   public ConfigurationImpl setDiscoveryGroupConfigurations(final Map<String, DiscoveryGroupConfiguration> discoveryGroupConfigurations)
    {
       this.discoveryGroupConfigurations = discoveryGroupConfigurations;
+      return this;
+   }
+
+   public ConfigurationImpl addDiscoveryGroupConfiguration(final String key, DiscoveryGroupConfiguration discoveryGroupConfiguration)
+   {
+      this.discoveryGroupConfigurations.put(key, discoveryGroupConfiguration);
+      return this;
    }
 
    public int getIDCacheSize()
@@ -481,9 +523,10 @@ public class ConfigurationImpl implements Configuration
       return idCacheSize;
    }
 
-   public void setIDCacheSize(final int idCacheSize)
+   public ConfigurationImpl setIDCacheSize(final int idCacheSize)
    {
       this.idCacheSize = idCacheSize;
+      return this;
    }
 
    public boolean isPersistIDCache()
@@ -491,9 +534,10 @@ public class ConfigurationImpl implements Configuration
       return persistIDCache;
    }
 
-   public void setPersistIDCache(final boolean persist)
+   public ConfigurationImpl setPersistIDCache(final boolean persist)
    {
       persistIDCache = persist;
+      return this;
    }
 
    public String getBindingsDirectory()
@@ -501,9 +545,10 @@ public class ConfigurationImpl implements Configuration
       return bindingsDirectory;
    }
 
-   public void setBindingsDirectory(final String dir)
+   public ConfigurationImpl setBindingsDirectory(final String dir)
    {
       bindingsDirectory = dir;
+      return this;
    }
 
 
@@ -514,9 +559,10 @@ public class ConfigurationImpl implements Configuration
    }
 
    @Override
-   public void setPageMaxConcurrentIO(int maxIO)
+   public ConfigurationImpl setPageMaxConcurrentIO(int maxIO)
    {
       this.maxConcurrentPageIO = maxIO;
+      return this;
    }
 
 
@@ -525,9 +571,10 @@ public class ConfigurationImpl implements Configuration
       return journalDirectory;
    }
 
-   public void setJournalDirectory(final String dir)
+   public ConfigurationImpl setJournalDirectory(final String dir)
    {
       journalDirectory = dir;
+      return this;
    }
 
    public JournalType getJournalType()
@@ -535,9 +582,10 @@ public class ConfigurationImpl implements Configuration
       return journalType;
    }
 
-   public void setPagingDirectory(final String dir)
+   public ConfigurationImpl setPagingDirectory(final String dir)
    {
       pagingDirectory = dir;
+      return this;
    }
 
    public String getPagingDirectory()
@@ -545,9 +593,10 @@ public class ConfigurationImpl implements Configuration
       return pagingDirectory;
    }
 
-   public void setJournalType(final JournalType type)
+   public ConfigurationImpl setJournalType(final JournalType type)
    {
       journalType = type;
+      return this;
    }
 
    public boolean isJournalSyncTransactional()
@@ -555,9 +604,10 @@ public class ConfigurationImpl implements Configuration
       return journalSyncTransactional;
    }
 
-   public void setJournalSyncTransactional(final boolean sync)
+   public ConfigurationImpl setJournalSyncTransactional(final boolean sync)
    {
       journalSyncTransactional = sync;
+      return this;
    }
 
    public boolean isJournalSyncNonTransactional()
@@ -565,9 +615,10 @@ public class ConfigurationImpl implements Configuration
       return journalSyncNonTransactional;
    }
 
-   public void setJournalSyncNonTransactional(final boolean sync)
+   public ConfigurationImpl setJournalSyncNonTransactional(final boolean sync)
    {
       journalSyncNonTransactional = sync;
+      return this;
    }
 
    public int getJournalFileSize()
@@ -575,9 +626,10 @@ public class ConfigurationImpl implements Configuration
       return journalFileSize;
    }
 
-   public void setJournalFileSize(final int size)
+   public ConfigurationImpl setJournalFileSize(final int size)
    {
       journalFileSize = size;
+      return this;
    }
 
    public int getJournalMinFiles()
@@ -585,9 +637,10 @@ public class ConfigurationImpl implements Configuration
       return journalMinFiles;
    }
 
-   public void setJournalMinFiles(final int files)
+   public ConfigurationImpl setJournalMinFiles(final int files)
    {
       journalMinFiles = files;
+      return this;
    }
 
    public boolean isLogJournalWriteRate()
@@ -595,9 +648,10 @@ public class ConfigurationImpl implements Configuration
       return logJournalWriteRate;
    }
 
-   public void setLogJournalWriteRate(final boolean logJournalWriteRate)
+   public ConfigurationImpl setLogJournalWriteRate(final boolean logJournalWriteRate)
    {
       this.logJournalWriteRate = logJournalWriteRate;
+      return this;
    }
 
    public int getJournalPerfBlastPages()
@@ -605,9 +659,10 @@ public class ConfigurationImpl implements Configuration
       return journalPerfBlastPages;
    }
 
-   public void setJournalPerfBlastPages(final int journalPerfBlastPages)
+   public ConfigurationImpl setJournalPerfBlastPages(final int journalPerfBlastPages)
    {
       this.journalPerfBlastPages = journalPerfBlastPages;
+      return this;
    }
 
    public boolean isRunSyncSpeedTest()
@@ -615,9 +670,10 @@ public class ConfigurationImpl implements Configuration
       return runSyncSpeedTest;
    }
 
-   public void setRunSyncSpeedTest(final boolean run)
+   public ConfigurationImpl setRunSyncSpeedTest(final boolean run)
    {
       runSyncSpeedTest = run;
+      return this;
    }
 
    public boolean isCreateBindingsDir()
@@ -625,9 +681,10 @@ public class ConfigurationImpl implements Configuration
       return createBindingsDir;
    }
 
-   public void setCreateBindingsDir(final boolean create)
+   public ConfigurationImpl setCreateBindingsDir(final boolean create)
    {
       createBindingsDir = create;
+      return this;
    }
 
    public boolean isCreateJournalDir()
@@ -635,9 +692,10 @@ public class ConfigurationImpl implements Configuration
       return createJournalDir;
    }
 
-   public void setCreateJournalDir(final boolean create)
+   public ConfigurationImpl setCreateJournalDir(final boolean create)
    {
       createJournalDir = create;
+      return this;
    }
 
    public boolean isWildcardRoutingEnabled()
@@ -645,9 +703,10 @@ public class ConfigurationImpl implements Configuration
       return wildcardRoutingEnabled;
    }
 
-   public void setWildcardRoutingEnabled(final boolean enabled)
+   public ConfigurationImpl setWildcardRoutingEnabled(final boolean enabled)
    {
       wildcardRoutingEnabled = enabled;
+      return this;
    }
 
    public long getTransactionTimeout()
@@ -655,9 +714,10 @@ public class ConfigurationImpl implements Configuration
       return transactionTimeout;
    }
 
-   public void setTransactionTimeout(final long timeout)
+   public ConfigurationImpl setTransactionTimeout(final long timeout)
    {
       transactionTimeout = timeout;
+      return this;
    }
 
    public long getTransactionTimeoutScanPeriod()
@@ -665,9 +725,10 @@ public class ConfigurationImpl implements Configuration
       return transactionTimeoutScanPeriod;
    }
 
-   public void setTransactionTimeoutScanPeriod(final long period)
+   public ConfigurationImpl setTransactionTimeoutScanPeriod(final long period)
    {
       transactionTimeoutScanPeriod = period;
+      return this;
    }
 
    public long getMessageExpiryScanPeriod()
@@ -675,9 +736,10 @@ public class ConfigurationImpl implements Configuration
       return messageExpiryScanPeriod;
    }
 
-   public void setMessageExpiryScanPeriod(final long messageExpiryScanPeriod)
+   public ConfigurationImpl setMessageExpiryScanPeriod(final long messageExpiryScanPeriod)
    {
       this.messageExpiryScanPeriod = messageExpiryScanPeriod;
+      return this;
    }
 
    public int getMessageExpiryThreadPriority()
@@ -685,9 +747,10 @@ public class ConfigurationImpl implements Configuration
       return messageExpiryThreadPriority;
    }
 
-   public void setMessageExpiryThreadPriority(final int messageExpiryThreadPriority)
+   public ConfigurationImpl setMessageExpiryThreadPriority(final int messageExpiryThreadPriority)
    {
       this.messageExpiryThreadPriority = messageExpiryThreadPriority;
+      return this;
    }
 
    public boolean isSecurityEnabled()
@@ -695,9 +758,10 @@ public class ConfigurationImpl implements Configuration
       return securityEnabled;
    }
 
-   public void setSecurityEnabled(final boolean enabled)
+   public ConfigurationImpl setSecurityEnabled(final boolean enabled)
    {
       securityEnabled = enabled;
+      return this;
    }
 
    public boolean isJMXManagementEnabled()
@@ -705,9 +769,10 @@ public class ConfigurationImpl implements Configuration
       return jmxManagementEnabled;
    }
 
-   public void setJMXManagementEnabled(final boolean enabled)
+   public ConfigurationImpl setJMXManagementEnabled(final boolean enabled)
    {
       jmxManagementEnabled = enabled;
+      return this;
    }
 
    public String getJMXDomain()
@@ -715,9 +780,10 @@ public class ConfigurationImpl implements Configuration
       return jmxDomain;
    }
 
-   public void setJMXDomain(final String domain)
+   public ConfigurationImpl setJMXDomain(final String domain)
    {
       jmxDomain = domain;
+      return this;
    }
 
    public String getLargeMessagesDirectory()
@@ -725,9 +791,10 @@ public class ConfigurationImpl implements Configuration
       return largeMessagesDirectory;
    }
 
-   public void setLargeMessagesDirectory(final String directory)
+   public ConfigurationImpl setLargeMessagesDirectory(final String directory)
    {
       largeMessagesDirectory = directory;
+      return this;
    }
 
    public boolean isMessageCounterEnabled()
@@ -735,9 +802,10 @@ public class ConfigurationImpl implements Configuration
       return messageCounterEnabled;
    }
 
-   public void setMessageCounterEnabled(final boolean enabled)
+   public ConfigurationImpl setMessageCounterEnabled(final boolean enabled)
    {
       messageCounterEnabled = enabled;
+      return this;
    }
 
    public long getMessageCounterSamplePeriod()
@@ -745,9 +813,10 @@ public class ConfigurationImpl implements Configuration
       return messageCounterSamplePeriod;
    }
 
-   public void setMessageCounterSamplePeriod(final long period)
+   public ConfigurationImpl setMessageCounterSamplePeriod(final long period)
    {
       messageCounterSamplePeriod = period;
+      return this;
    }
 
    public int getMessageCounterMaxDayHistory()
@@ -755,9 +824,10 @@ public class ConfigurationImpl implements Configuration
       return messageCounterMaxDayHistory;
    }
 
-   public void setMessageCounterMaxDayHistory(final int maxDayHistory)
+   public ConfigurationImpl setMessageCounterMaxDayHistory(final int maxDayHistory)
    {
       messageCounterMaxDayHistory = maxDayHistory;
+      return this;
    }
 
    public SimpleString getManagementAddress()
@@ -765,9 +835,10 @@ public class ConfigurationImpl implements Configuration
       return managementAddress;
    }
 
-   public void setManagementAddress(final SimpleString address)
+   public ConfigurationImpl setManagementAddress(final SimpleString address)
    {
       managementAddress = address;
+      return this;
    }
 
    public SimpleString getManagementNotificationAddress()
@@ -775,9 +846,10 @@ public class ConfigurationImpl implements Configuration
       return managementNotificationAddress;
    }
 
-   public void setManagementNotificationAddress(final SimpleString address)
+   public ConfigurationImpl setManagementNotificationAddress(final SimpleString address)
    {
       managementNotificationAddress = address;
+      return this;
    }
 
    public String getClusterUser()
@@ -785,9 +857,10 @@ public class ConfigurationImpl implements Configuration
       return clusterUser;
    }
 
-   public void setClusterUser(final String user)
+   public ConfigurationImpl setClusterUser(final String user)
    {
       clusterUser = user;
+      return this;
    }
 
    public String getClusterPassword()
@@ -800,14 +873,16 @@ public class ConfigurationImpl implements Configuration
       return failoverOnServerShutdown;
    }
 
-   public void setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
+   public ConfigurationImpl setFailoverOnServerShutdown(boolean failoverOnServerShutdown)
    {
       this.failoverOnServerShutdown = failoverOnServerShutdown;
+      return this;
    }
 
-   public void setClusterPassword(final String theclusterPassword)
+   public ConfigurationImpl setClusterPassword(final String theclusterPassword)
    {
       clusterPassword = theclusterPassword;
+      return this;
    }
 
    public int getJournalCompactMinFiles()
@@ -820,14 +895,16 @@ public class ConfigurationImpl implements Configuration
       return journalCompactPercentage;
    }
 
-   public void setJournalCompactMinFiles(final int minFiles)
+   public ConfigurationImpl setJournalCompactMinFiles(final int minFiles)
    {
       journalCompactMinFiles = minFiles;
+      return this;
    }
 
-   public void setJournalCompactPercentage(final int percentage)
+   public ConfigurationImpl setJournalCompactPercentage(final int percentage)
    {
       journalCompactPercentage = percentage;
+      return this;
    }
 
    public long getServerDumpInterval()
@@ -835,9 +912,10 @@ public class ConfigurationImpl implements Configuration
       return serverDumpInterval;
    }
 
-   public void setServerDumpInterval(final long intervalInMilliseconds)
+   public ConfigurationImpl setServerDumpInterval(final long intervalInMilliseconds)
    {
       serverDumpInterval = intervalInMilliseconds;
+      return this;
    }
 
    public int getMemoryWarningThreshold()
@@ -845,9 +923,10 @@ public class ConfigurationImpl implements Configuration
       return memoryWarningThreshold;
    }
 
-   public void setMemoryWarningThreshold(final int memoryWarningThreshold)
+   public ConfigurationImpl setMemoryWarningThreshold(final int memoryWarningThreshold)
    {
       this.memoryWarningThreshold = memoryWarningThreshold;
+      return this;
    }
 
    public long getMemoryMeasureInterval()
@@ -855,9 +934,10 @@ public class ConfigurationImpl implements Configuration
       return memoryMeasureInterval;
    }
 
-   public void setMemoryMeasureInterval(final long memoryMeasureInterval)
+   public ConfigurationImpl setMemoryMeasureInterval(final long memoryMeasureInterval)
    {
       this.memoryMeasureInterval = memoryMeasureInterval;
+      return this;
    }
 
    public int getJournalMaxIO_AIO()
@@ -865,9 +945,10 @@ public class ConfigurationImpl implements Configuration
       return journalMaxIO_AIO;
    }
 
-   public void setJournalMaxIO_AIO(final int journalMaxIO)
+   public ConfigurationImpl setJournalMaxIO_AIO(final int journalMaxIO)
    {
       journalMaxIO_AIO = journalMaxIO;
+      return this;
    }
 
    public int getJournalBufferTimeout_AIO()
@@ -875,9 +956,10 @@ public class ConfigurationImpl implements Configuration
       return journalBufferTimeout_AIO;
    }
 
-   public void setJournalBufferTimeout_AIO(final int journalBufferTimeout)
+   public ConfigurationImpl setJournalBufferTimeout_AIO(final int journalBufferTimeout)
    {
       journalBufferTimeout_AIO = journalBufferTimeout;
+      return this;
    }
 
    public int getJournalBufferSize_AIO()
@@ -885,9 +967,10 @@ public class ConfigurationImpl implements Configuration
       return journalBufferSize_AIO;
    }
 
-   public void setJournalBufferSize_AIO(final int journalBufferSize)
+   public ConfigurationImpl setJournalBufferSize_AIO(final int journalBufferSize)
    {
       journalBufferSize_AIO = journalBufferSize;
+      return this;
    }
 
    public int getJournalMaxIO_NIO()
@@ -895,9 +978,10 @@ public class ConfigurationImpl implements Configuration
       return journalMaxIO_NIO;
    }
 
-   public void setJournalMaxIO_NIO(final int journalMaxIO)
+   public ConfigurationImpl setJournalMaxIO_NIO(final int journalMaxIO)
    {
       journalMaxIO_NIO = journalMaxIO;
+      return this;
    }
 
    public int getJournalBufferTimeout_NIO()
@@ -905,9 +989,10 @@ public class ConfigurationImpl implements Configuration
       return journalBufferTimeout_NIO;
    }
 
-   public void setJournalBufferTimeout_NIO(final int journalBufferTimeout)
+   public ConfigurationImpl setJournalBufferTimeout_NIO(final int journalBufferTimeout)
    {
       journalBufferTimeout_NIO = journalBufferTimeout;
+      return this;
    }
 
    public int getJournalBufferSize_NIO()
@@ -915,9 +1000,10 @@ public class ConfigurationImpl implements Configuration
       return journalBufferSize_NIO;
    }
 
-   public void setJournalBufferSize_NIO(final int journalBufferSize)
+   public ConfigurationImpl setJournalBufferSize_NIO(final int journalBufferSize)
    {
       journalBufferSize_NIO = journalBufferSize;
+      return this;
    }
 
    @Override
@@ -927,9 +1013,17 @@ public class ConfigurationImpl implements Configuration
    }
 
    @Override
-   public void setAddressesSettings(final Map<String, AddressSettings> addressesSettings)
+   public ConfigurationImpl setAddressesSettings(final Map<String, AddressSettings> addressesSettings)
    {
       this.addressesSettings = addressesSettings;
+      return this;
+   }
+
+   @Override
+   public ConfigurationImpl addAddressesSetting(String key, AddressSettings addressesSetting)
+   {
+      this.addressesSettings.put(key, addressesSetting);
+      return this;
    }
 
    @Override
@@ -939,9 +1033,10 @@ public class ConfigurationImpl implements Configuration
    }
 
    @Override
-   public void setSecurityRoles(final Map<String, Set<Role>> securitySettings)
+   public ConfigurationImpl setSecurityRoles(final Map<String, Set<Role>> securitySettings)
    {
       this.securitySettings = securitySettings;
+      return this;
    }
 
    public List<ConnectorServiceConfiguration> getConnectorServiceConfigurations()
@@ -949,31 +1044,73 @@ public class ConfigurationImpl implements Configuration
       return this.connectorServiceConfigurations;
    }
 
-   @Deprecated
-   public long getFailbackDelay()
+   public boolean isCheckForLiveServer()
    {
-      return haPolicy.getFailbackDelay();
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         return ((ReplicatedPolicyConfiguration)haPolicyConfiguration).isCheckForLiveServer();
+      }
+      else
+      {
+         return false;
+      }
    }
 
-   @Deprecated
-   public void setFailbackDelay(long failbackDelay)
+   public ConfigurationImpl setCheckForLiveServer(boolean checkForLiveServer)
    {
-      this.haPolicy.setFailbackDelay(failbackDelay);
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ((ReplicatedPolicyConfiguration)haPolicyConfiguration).setCheckForLiveServer(checkForLiveServer);
+      }
+
+      return this;
    }
 
-   public boolean isCheckForLiveServer()
+   @Override
+   public String toString()
    {
-      return checkForLiveServer;
+      StringBuilder sb = new StringBuilder("HornetQ Configuration (");
+      sb.append("clustered=").append(isClustered()).append(",");
+      sb.append("journalDirectory=").append(journalDirectory).append(",");
+      sb.append("bindingsDirectory=").append(bindingsDirectory).append(",");
+      sb.append("largeMessagesDirectory=").append(largeMessagesDirectory).append(",");
+      sb.append("pagingDirectory=").append(pagingDirectory);
+      sb.append(")");
+      return sb.toString();
    }
 
-   public void setCheckForLiveServer(boolean checkForLiveServer)
+   public ConfigurationImpl setConnectorServiceConfigurations(final List<ConnectorServiceConfiguration> configs)
    {
-      this.checkForLiveServer = checkForLiveServer;
+      this.connectorServiceConfigurations = configs;
+      return this;
    }
 
-   public void setConnectorServiceConfigurations(final List<ConnectorServiceConfiguration> configs)
+   public ConfigurationImpl addConnectorServiceConfiguration(final ConnectorServiceConfiguration config)
    {
-      this.connectorServiceConfigurations = configs;
+      this.connectorServiceConfigurations.add(config);
+      return this;
+   }
+
+   public boolean isMaskPassword()
+   {
+      return maskPassword;
+   }
+
+   public ConfigurationImpl setMaskPassword(boolean maskPassword)
+   {
+      this.maskPassword = maskPassword;
+      return this;
+   }
+
+   public ConfigurationImpl setPasswordCodec(String codec)
+   {
+      passwordCodec = codec;
+      return this;
+   }
+
+   public String getPasswordCodec()
+   {
+      return passwordCodec;
    }
 
    @Override
@@ -983,103 +1120,210 @@ public class ConfigurationImpl implements Configuration
    }
 
    @Override
-   public void setName(String name)
+   public ConfigurationImpl setName(String name)
    {
       this.name = name;
+      return this;
    }
 
+
+   /*
+   * All these operations are now deprecated and may or my not work, best efforts is all we can do, an HA Policy needs to be used
+   * */
    @Deprecated
-   public String getBackupGroupName()
+   public ConfigurationImpl setBackup(final boolean backup)
    {
-      return haPolicy.getBackupGroupName();
+      return this;
    }
 
    @Deprecated
-   public void setBackupGroupName(String nodeGroupName)
+   public boolean isSharedStore()
    {
-      haPolicy.setBackupGroupName(nodeGroupName);
+      return haPolicyConfiguration instanceof SharedStoreMasterPolicyConfiguration || haPolicyConfiguration instanceof SharedStoreSlavePolicyConfiguration;
    }
 
-   @Override
-   public String toString()
+   @Deprecated
+   public ConfigurationImpl setSharedStore(final boolean sharedStore)
    {
-      StringBuilder sb = new StringBuilder("HornetQ Configuration (");
-      sb.append("clustered=").append(isClustered()).append(",");
-      sb.append("ha-policy-type=").append(haPolicy.getPolicyType()).append(",");
-      sb.append("journalDirectory=").append(journalDirectory).append(",");
-      sb.append("bindingsDirectory=").append(bindingsDirectory).append(",");
-      sb.append("largeMessagesDirectory=").append(largeMessagesDirectory).append(",");
-      sb.append("pagingDirectory=").append(pagingDirectory);
-      sb.append(")");
-      return sb.toString();
+      return this;
    }
 
-   public boolean isMaskPassword()
+   @Deprecated
+   public long getFailbackDelay()
    {
-      return maskPassword;
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         return hapc.getFailbackDelay();
+      }
+      else if (haPolicyConfiguration instanceof SharedStoreMasterPolicyConfiguration)
+      {
+         SharedStoreMasterPolicyConfiguration hapc = (SharedStoreMasterPolicyConfiguration) haPolicyConfiguration;
+         return hapc.getFailbackDelay();
+      }
+      else if (haPolicyConfiguration instanceof SharedStoreSlavePolicyConfiguration)
+      {
+         SharedStoreSlavePolicyConfiguration hapc = (SharedStoreSlavePolicyConfiguration) haPolicyConfiguration;
+         return hapc.getFailbackDelay();
+      }
+      return -1;
    }
 
-   public void setMaskPassword(boolean maskPassword)
+   @Deprecated
+   public ConfigurationImpl setFailbackDelay(long failbackDelay)
    {
-      this.maskPassword = maskPassword;
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         hapc.setFailbackDelay(failbackDelay);
+      }
+      else if (haPolicyConfiguration instanceof SharedStoreMasterPolicyConfiguration)
+      {
+         SharedStoreMasterPolicyConfiguration hapc = (SharedStoreMasterPolicyConfiguration) haPolicyConfiguration;
+         hapc.setFailbackDelay(failbackDelay);
+      }
+      else if (haPolicyConfiguration instanceof SharedStoreSlavePolicyConfiguration)
+      {
+         SharedStoreSlavePolicyConfiguration hapc = (SharedStoreSlavePolicyConfiguration) haPolicyConfiguration;
+         hapc.setFailbackDelay(failbackDelay);
+      }
+
+      return this;
    }
 
-   public void setPasswordCodec(String codec)
+   @Deprecated
+   public String getBackupGroupName()
    {
-      passwordCodec = codec;
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         return hapc.getGroupName();
+      }
+      else if (haPolicyConfiguration instanceof ReplicatedPolicyConfiguration)
+      {
+         ReplicatedPolicyConfiguration hapc = (ReplicatedPolicyConfiguration) haPolicyConfiguration;
+         return hapc.getGroupName();
+      }
+      return null;
    }
 
-   public String getPasswordCodec()
+   @Deprecated
+   public ConfigurationImpl setBackupGroupName(String nodeGroupName)
    {
-      return passwordCodec;
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         hapc.setGroupName(nodeGroupName);
+      }
+      else if (haPolicyConfiguration instanceof ReplicatedPolicyConfiguration)
+      {
+         ReplicatedPolicyConfiguration hapc = (ReplicatedPolicyConfiguration) haPolicyConfiguration;
+         hapc.setGroupName(nodeGroupName);
+      }
+      return this;
    }
 
    @Override
    @Deprecated
-   public void setReplicationClustername(String clusterName)
+   public ConfigurationImpl setReplicationClustername(String clusterName)
    {
-      this.haPolicy.setReplicationClustername(clusterName);
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         hapc.setClusterName(clusterName);
+      }
+      else if (haPolicyConfiguration instanceof ReplicatedPolicyConfiguration)
+      {
+         ReplicatedPolicyConfiguration hapc = (ReplicatedPolicyConfiguration) haPolicyConfiguration;
+         hapc.setClusterName(clusterName);
+      }
+      return this;
    }
 
    @Override
    @Deprecated
    public String getReplicationClustername()
    {
-      return haPolicy.getReplicationClustername();
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         return hapc.getClusterName();
+      }
+      else if (haPolicyConfiguration instanceof ReplicatedPolicyConfiguration)
+      {
+         ReplicatedPolicyConfiguration hapc = (ReplicatedPolicyConfiguration) haPolicyConfiguration;
+         return hapc.getClusterName();
+      }
+      return null;
    }
 
    @Override
    @Deprecated
-   public void setScaleDownClustername(String clusterName)
+   public ConfigurationImpl setMaxSavedReplicatedJournalSize(int maxSavedReplicatedJournalsSize)
    {
-      this.haPolicy.setScaleDownClustername(clusterName);
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         hapc.setMaxSavedReplicatedJournalsSize(maxSavedReplicatedJournalsSize);
+      }
+
+      return this;
    }
 
    @Override
    @Deprecated
-   public String getScaleDownClustername()
+   public int getMaxSavedReplicatedJournalsSize()
    {
-      return haPolicy.getScaleDownClustername();
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         return hapc.getMaxSavedReplicatedJournalsSize();
+      }
+      return -1;
    }
 
-   @Override
    @Deprecated
-   public void setMaxSavedReplicatedJournalSize(int maxSavedReplicatedJournalsSize)
+   public boolean isAllowFailBack()
    {
-      this.haPolicy.setMaxSavedReplicatedJournalSize(maxSavedReplicatedJournalsSize);
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         return hapc.isAllowFailBack();
+      }
+      else if (haPolicyConfiguration instanceof SharedStoreSlavePolicyConfiguration)
+      {
+         SharedStoreSlavePolicyConfiguration hapc = (SharedStoreSlavePolicyConfiguration) haPolicyConfiguration;
+         return hapc.isAllowFailBack();
+      }
+      return false;
    }
 
-   @Override
    @Deprecated
-   public int getMaxSavedReplicatedJournalsSize()
+   public void setAllowFailBack(boolean allowAutoFailBack)
    {
-      return haPolicy.getMaxSavedReplicatedJournalsSize();
+      if (haPolicyConfiguration instanceof ReplicaPolicyConfiguration)
+      {
+         ReplicaPolicyConfiguration hapc = (ReplicaPolicyConfiguration) haPolicyConfiguration;
+         hapc.setAllowFailBack(allowAutoFailBack);
+      }
+      else if (haPolicyConfiguration instanceof SharedStoreSlavePolicyConfiguration)
+      {
+         SharedStoreSlavePolicyConfiguration hapc = (SharedStoreSlavePolicyConfiguration) haPolicyConfiguration;
+         hapc.setAllowFailBack(allowAutoFailBack);
+      }
+   }
+
+   @Deprecated
+   public boolean isBackup()
+   {
+      return haPolicyConfiguration instanceof ReplicaPolicyConfiguration || haPolicyConfiguration instanceof SharedStoreSlavePolicyConfiguration;
    }
 
    @Override
-   public void setResolveProtocols(boolean resolveProtocols)
+   public ConfigurationImpl setResolveProtocols(boolean resolveProtocols)
    {
       this.resolveProtocols = resolveProtocols;
+      return this;
    }
 
    @Override
@@ -1095,13 +1339,10 @@ public class ConfigurationImpl implements Configuration
       int result = 1;
       result = prime * result + ((acceptorConfigs == null) ? 0 : acceptorConfigs.hashCode());
       result = prime * result + ((addressesSettings == null) ? 0 : addressesSettings.hashCode());
-      result = prime * result + (haPolicy.isAllowAutoFailBack() ? 1231 : 1237);
       result = prime * result + (asyncConnectionExecutionEnabled ? 1231 : 1237);
-      result = prime * result + (haPolicy.isBackup() ? 1231 : 1237);
       result = prime * result + ((bindingsDirectory == null) ? 0 : bindingsDirectory.hashCode());
       result = prime * result + ((bridgeConfigurations == null) ? 0 : bridgeConfigurations.hashCode());
       result = prime * result + ((broadcastGroupConfigurations == null) ? 0 : broadcastGroupConfigurations.hashCode());
-      result = prime * result + (checkForLiveServer ? 1231 : 1237);
       result = prime * result + ((clusterConfigurations == null) ? 0 : clusterConfigurations.hashCode());
       result = prime * result + ((clusterPassword == null) ? 0 : clusterPassword.hashCode());
       result = prime * result + ((clusterUser == null) ? 0 : clusterUser.hashCode());
@@ -1114,7 +1355,6 @@ public class ConfigurationImpl implements Configuration
       result = prime * result + (createJournalDir ? 1231 : 1237);
       result = prime * result + ((discoveryGroupConfigurations == null) ? 0 : discoveryGroupConfigurations.hashCode());
       result = prime * result + ((divertConfigurations == null) ? 0 : divertConfigurations.hashCode());
-      result = prime * result + (int)(haPolicy.getFailbackDelay() ^ (haPolicy.getFailbackDelay() >>> 32));
       result = prime * result + (failoverOnServerShutdown ? 1231 : 1237);
       result = prime * result + (fileDeploymentEnabled ? 1231 : 1237);
       result = prime * result + (int)(fileDeploymentScanPeriod ^ (fileDeploymentScanPeriod >>> 32));
@@ -1156,7 +1396,6 @@ public class ConfigurationImpl implements Configuration
       result = prime * result + (int)(messageExpiryScanPeriod ^ (messageExpiryScanPeriod >>> 32));
       result = prime * result + messageExpiryThreadPriority;
       result = prime * result + ((name == null) ? 0 : name.hashCode());
-      result = prime * result + ((haPolicy.getBackupGroupName() == null) ? 0 : haPolicy.getBackupGroupName().hashCode());
       result =
                prime * result +
                         ((outgoingInterceptorClassNames == null) ? 0 : outgoingInterceptorClassNames.hashCode());
@@ -1165,15 +1404,12 @@ public class ConfigurationImpl implements Configuration
       result = prime * result + (persistIDCache ? 1231 : 1237);
       result = prime * result + (persistenceEnabled ? 1231 : 1237);
       result = prime * result + ((queueConfigurations == null) ? 0 : queueConfigurations.hashCode());
-      result = prime * result + ((haPolicy.getReplicationClustername() == null) ? 0 : haPolicy.getReplicationClustername().hashCode());
-      result = prime * result + ((haPolicy.getScaleDownClustername() == null) ? 0 : haPolicy.getScaleDownClustername().hashCode());
       result = prime * result + (runSyncSpeedTest ? 1231 : 1237);
       result = prime * result + scheduledThreadPoolMaxSize;
       result = prime * result + (securityEnabled ? 1231 : 1237);
       result = prime * result + (int)(securityInvalidationInterval ^ (securityInvalidationInterval >>> 32));
       result = prime * result + ((securitySettings == null) ? 0 : securitySettings.hashCode());
       result = prime * result + (int)(serverDumpInterval ^ (serverDumpInterval >>> 32));
-      result = prime * result + (haPolicy.isSharedStore() ? 1231 : 1237);
       result = prime * result + threadPoolMaxSize;
       result = prime * result + (int)(transactionTimeout ^ (transactionTimeout >>> 32));
       result = prime * result + (int)(transactionTimeoutScanPeriod ^ (transactionTimeoutScanPeriod >>> 32));
@@ -1207,12 +1443,9 @@ public class ConfigurationImpl implements Configuration
       }
       else if (!addressesSettings.equals(other.addressesSettings))
          return false;
-      if (haPolicy.isAllowAutoFailBack() != other.getHAPolicy().isAllowAutoFailBack())
-         return false;
       if (asyncConnectionExecutionEnabled != other.asyncConnectionExecutionEnabled)
          return false;
-      if (haPolicy.isBackup() != other.getHAPolicy().isBackup())
-         return false;
+
       if (bindingsDirectory == null)
       {
          if (other.bindingsDirectory != null)
@@ -1234,8 +1467,6 @@ public class ConfigurationImpl implements Configuration
       }
       else if (!broadcastGroupConfigurations.equals(other.broadcastGroupConfigurations))
          return false;
-      if (checkForLiveServer != other.checkForLiveServer)
-         return false;
       if (clusterConfigurations == null)
       {
          if (other.clusterConfigurations != null)
@@ -1291,8 +1522,6 @@ public class ConfigurationImpl implements Configuration
       }
       else if (!divertConfigurations.equals(other.divertConfigurations))
          return false;
-      if (haPolicy.getFailbackDelay() != other.getHAPolicy().getFailbackDelay())
-         return false;
       if (failoverOnServerShutdown != other.failoverOnServerShutdown)
          return false;
       if (fileDeploymentEnabled != other.fileDeploymentEnabled)
@@ -1407,13 +1636,7 @@ public class ConfigurationImpl implements Configuration
       }
       else if (!name.equals(other.name))
          return false;
-      if (haPolicy.getBackupGroupName() == null)
-      {
-         if (other.getHAPolicy().getBackupGroupName() != null)
-            return false;
-      }
-      else if (!haPolicy.getBackupGroupName().equals(other.getHAPolicy().getBackupGroupName()))
-         return false;
+
       if (outgoingInterceptorClassNames == null)
       {
          if (other.outgoingInterceptorClassNames != null)
@@ -1441,20 +1664,6 @@ public class ConfigurationImpl implements Configuration
       }
       else if (!queueConfigurations.equals(other.queueConfigurations))
          return false;
-      if (haPolicy.getReplicationClustername() == null)
-      {
-         if (other.getHAPolicy().getReplicationClustername() != null)
-            return false;
-      }
-      else if (!haPolicy.getReplicationClustername().equals(other.getHAPolicy().getReplicationClustername()))
-         return false;
-      if (haPolicy.getScaleDownClustername() == null)
-      {
-         if (other.getHAPolicy().getScaleDownClustername() != null)
-            return false;
-      }
-      else if (!haPolicy.getScaleDownClustername().equals(other.getHAPolicy().getScaleDownClustername()))
-         return false;
       if (runSyncSpeedTest != other.runSyncSpeedTest)
          return false;
       if (scheduledThreadPoolMaxSize != other.scheduledThreadPoolMaxSize)
@@ -1472,8 +1681,6 @@ public class ConfigurationImpl implements Configuration
          return false;
       if (serverDumpInterval != other.serverDumpInterval)
          return false;
-      if (haPolicy.isSharedStore() != other.getHAPolicy().isSharedStore())
-         return false;
       if (threadPoolMaxSize != other.threadPoolMaxSize)
          return false;
       if (transactionTimeout != other.transactionTimeout)
@@ -1489,6 +1696,7 @@ public class ConfigurationImpl implements Configuration
       return true;
    }
 
+   @Override
    public Configuration copy() throws Exception
    {
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -1499,26 +1707,10 @@ public class ConfigurationImpl implements Configuration
    }
 
    @Override
-   public Set<Configuration> getBackupServerConfigurations()
-   {
-      return backupServerConfigurations;
-   }
-
-   @Override
-   public void setBackupStrategy(BackupStrategy backupStrategy)
-   {
-      this.backupStrategy = backupStrategy;
-   }
-
-   public BackupStrategy getBackupStrategy()
-   {
-      return backupStrategy;
-   }
-
-   @Override
-   public void setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout)
+   public ConfigurationImpl setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout)
    {
       this.journalLockAcquisitionTimeout = journalLockAcquisitionTimeout;
+      return this;
    }
 
    @Override
@@ -1528,14 +1720,15 @@ public class ConfigurationImpl implements Configuration
    }
 
    @Override
-   public HAPolicy getHAPolicy()
+   public HAPolicyConfiguration getHAPolicyConfiguration()
    {
-      return haPolicy;
+      return haPolicyConfiguration;
    }
 
    @Override
-   public void setHAPolicy(HAPolicy haPolicy)
+   public ConfigurationImpl setHAPolicyConfiguration(HAPolicyConfiguration haPolicyConfiguration)
    {
-      this.haPolicy = haPolicy;
+      this.haPolicyConfiguration = haPolicyConfiguration;
+      return this;
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/config/impl/Validators.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/config/impl/Validators.java b/hornetq-server/src/main/java/org/hornetq/core/config/impl/Validators.java
index 0cf8c2e..c8b2922 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/config/impl/Validators.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/config/impl/Validators.java
@@ -15,6 +15,7 @@ package org.hornetq.core.config.impl;
 import org.hornetq.core.server.HornetQMessageBundle;
 import org.hornetq.core.server.JournalType;
 import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
+import org.hornetq.core.settings.impl.SlowConsumerPolicy;
 
 /**
  * A Validators.
@@ -166,4 +167,17 @@ public final class Validators
          }
       }
    };
+
+   public static final Validator SLOW_CONSUMER_POLICY_TYPE = new Validator()
+   {
+      public void validate(final String name, final Object value)
+      {
+         String val = (String) value;
+         if (val == null || !val.equals(SlowConsumerPolicy.KILL.toString()) &&
+            !val.equals(SlowConsumerPolicy.NOTIFY.toString()))
+         {
+            throw HornetQMessageBundle.BUNDLE.invalidSlowConsumerPolicyType(val);
+         }
+      }
+   };
 }


[44/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/src/org/hornetq/jms/example/Sender.java
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/src/org/hornetq/jms/example/Sender.java b/examples/soak/tx-restarts/src/org/hornetq/jms/example/Sender.java
deleted file mode 100644
index dbdb5f2..0000000
--- a/examples/soak/tx-restarts/src/org/hornetq/jms/example/Sender.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.example;
-
-import javax.jms.BytesMessage;
-import javax.jms.DeliveryMode;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-
-
-/**
- * A Sender
- *
- * @author <a href="mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- *
- *
- */
-public class Sender extends ClientAbstract
-{
-
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   protected MessageProducer producer;
-   protected Queue queue;
-
-   protected long msgs = TXRestartSoak.MIN_MESSAGES_ON_QUEUE;
-   protected int pendingMsgs = 0;
-
-   protected final Receiver[] receivers;
-
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   // Public --------------------------------------------------------
-
-   public Sender(final Receiver[] receivers)
-   {
-      this.receivers = receivers;
-   }
-
-   @Override
-   protected void connectClients() throws Exception
-   {
-      queue = (Queue)ctx.lookup("/queue/inputQueue");
-      producer = sess.createProducer(queue);
-      producer.setDeliveryMode(DeliveryMode.PERSISTENT);
-   }
-
-   public void run()
-   {
-      super.run();
-      while (running)
-      {
-         try
-         {
-            beginTX();
-            for (int i = 0 ; i < 1000; i++)
-            {
-               BytesMessage msg = sess.createBytesMessage();
-               msg.setLongProperty("count", pendingMsgs + msgs);
-               msg.writeBytes(new byte[10 * 1024]);
-               producer.send(msg);
-               pendingMsgs++;
-            }
-            endTX();
-         }
-         catch (Exception e)
-         {
-            connect();
-         }
-      }
-   }
-
-   /* (non-Javadoc)
-    * @see org.hornetq.jms.example.ClientAbstract#onCommit()
-    */
-   @Override
-   protected void onCommit()
-   {
-      this.msgs += pendingMsgs;
-      for (Receiver rec : receivers)
-      {
-         rec.messageProduced(pendingMsgs);
-      }
-
-      pendingMsgs = 0;
-      System.out.println("commit on sender msgs = " + msgs );
-   }
-
-   /* (non-Javadoc)
-    * @see org.hornetq.jms.example.ClientAbstract#onRollback()
-    */
-   @Override
-   protected void onRollback()
-   {
-      pendingMsgs = 0;
-      System.out.println("Rolled back msgs=" + msgs);
-   }
-
-   public String toString()
-   {
-      return "Sender, msgs=" + msgs + ", pending=" + pendingMsgs;
-
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/examples/soak/tx-restarts/src/org/hornetq/jms/example/TXRestartSoak.java
----------------------------------------------------------------------
diff --git a/examples/soak/tx-restarts/src/org/hornetq/jms/example/TXRestartSoak.java b/examples/soak/tx-restarts/src/org/hornetq/jms/example/TXRestartSoak.java
deleted file mode 100644
index 3cbd306..0000000
--- a/examples/soak/tx-restarts/src/org/hornetq/jms/example/TXRestartSoak.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.jms.example;
-
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Logger;
-
-import javax.jms.BytesMessage;
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.naming.InitialContext;
-
-import org.hornetq.common.example.HornetQExample;
-
-/**
- *
- * This is used as a soak test to verify HornetQ's capability of persistent messages over restarts.
- *
- * This is used as a smoke test before releases.
- *
- * WARNING: This is not a sample on how you should handle XA.
- *          You are supposed to use a TransactionManager.
- *          This class is doing the job of a TransactionManager that fits for the purpose of this test only,
- *          however there are many more pitfalls to deal with Transactions.
- *
- *          This is just to stress and soak test Transactions with HornetQ.
- *
- *          And this is dealing with XA directly for the purpose testing only.
- *
- * @author <a href="mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- *
- *
- */
-public class TXRestartSoak extends HornetQExample
-{
-
-   public static final int MIN_MESSAGES_ON_QUEUE = 50000;
-
-   private static final Logger log = Logger.getLogger(TXRestartSoak.class.getName());
-
-   public static void main(final String[] args)
-   {
-      new TXRestartSoak().run(args);
-   }
-
-   private TXRestartSoak()
-   {
-      super();
-   }
-
-   /* (non-Javadoc)
-    * @see org.hornetq.common.example.HornetQExample#runExample()
-    */
-   @Override
-   public boolean runExample() throws Exception
-   {
-
-      Connection connection = null;
-      InitialContext initialContext = null;
-
-      try
-      {
-         // Step 1. Create an initial context to perform the JNDI lookup.
-         initialContext = getContext(0);
-
-         ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
-
-         // Step 4. Create the JMS objects
-         connection = cf.createConnection();
-
-         // Step 2. Perfom a lookup on the queue
-         Queue queue = (Queue)initialContext.lookup("/queue/inputQueue");
-
-         Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
-
-         MessageProducer producer = session.createProducer(queue);
-
-         for (int i = 0 ; i < MIN_MESSAGES_ON_QUEUE; i++)
-         {
-            BytesMessage msg = session.createBytesMessage();
-            msg.setLongProperty("count", i);
-            msg.writeBytes(new byte[10 * 1024]);
-            producer.send(msg);
-
-            if (i % 1000 == 0)
-            {
-               System.out.println("Sent " + i + " messages");
-               session.commit();
-            }
-         }
-
-         session.commit();
-
-         Receiver rec1 = new Receiver("/queue/diverted1");
-         Receiver rec2 = new Receiver("/queue/diverted2");
-
-         Sender send = new Sender(new Receiver[]{rec1, rec2});
-
-         send.start();
-         rec1.start();
-         rec2.start();
-
-         long timeEnd = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1);
-
-         if (runServer)
-         {
-            while (timeEnd > System.currentTimeMillis())
-            {
-               System.out.println("Letting the service run for 20 seconds");
-               Thread.sleep(TimeUnit.SECONDS.toMillis(20));
-               stopServers();
-
-               Thread.sleep(10000);
-
-               boolean disconnected = false;
-
-               if (send.getErrorsCount() != 0 || rec1.getErrorsCount() != 0 || rec2.getErrorsCount() != 0)
-               {
-                  System.out.println("There are sequence errors in some of the clients, please look at the logs");
-                  break;
-               }
-
-               while (!disconnected)
-               {
-                  disconnected = send.getConnection() == null && rec1.getConnection() == null && rec2.getConnection() == null;
-                  if (!disconnected)
-                  {
-                     System.out.println("NOT ALL THE CLIENTS ARE DISCONNECTED, NEED TO WAIT THEM");
-                  }
-                  Thread.sleep(1000);
-               }
-
-               startServers();
-            }
-         }
-         else
-         {
-            while (timeEnd > System.currentTimeMillis())
-            {
-               if (send.getErrorsCount() != 0 || rec1.getErrorsCount() != 0 || rec2.getErrorsCount() != 0)
-               {
-                  System.out.println("There are sequence errors in some of the clients, please look at the logs");
-                  break;
-               }
-               Thread.sleep(10000);
-            }
-         }
-
-         send.setRunning(false);
-         rec1.setRunning(false);
-         rec2.setRunning(false);
-
-         send.join();
-         rec1.join();
-         rec2.join();
-
-         return send.getErrorsCount() == 0 && rec1.getErrorsCount() == 0 && rec2.getErrorsCount() == 0;
-
-      }
-      finally
-      {
-         connection.close();
-      }
-
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/pom.xml b/hornetq-bootstrap/pom.xml
index f450cb3..50befc1 100644
--- a/hornetq-bootstrap/pom.xml
+++ b/hornetq-bootstrap/pom.xml
@@ -18,6 +18,21 @@
 
    <dependencies>
       <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-server</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-jms-server</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-dto</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
          <groupId>org.jboss.logging</groupId>
          <artifactId>jboss-logging-processor</artifactId>
       </dependency>
@@ -26,9 +41,28 @@
          <artifactId>jboss-logging</artifactId>
       </dependency>
       <dependency>
-         <groupId>org.jboss.microcontainer</groupId>
-         <artifactId>jboss-kernel</artifactId>
+         <groupId>io.airlift</groupId>
+         <artifactId>airline</artifactId>
       </dependency>
    </dependencies>
 
+   <build>
+     <resources>
+       <resource>
+         <directory>${project.basedir}/src/main/resources</directory>
+         <includes>
+           <include>**/*</include>
+         </includes>
+       </resource>
+       <resource>
+         <directory>${project.basedir}/src/main/filtered-resources</directory>
+         <filtering>true</filtering>
+         <includes>
+           <include>**/*</include>
+         </includes>
+       </resource>
+     </resources>
+   </build>
+
+
 </project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/filtered-resources/org/hornetq/cli/banner.txt
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/filtered-resources/org/hornetq/cli/banner.txt b/hornetq-bootstrap/src/main/filtered-resources/org/hornetq/cli/banner.txt
new file mode 100644
index 0000000..411caec
--- /dev/null
+++ b/hornetq-bootstrap/src/main/filtered-resources/org/hornetq/cli/banner.txt
@@ -0,0 +1,8 @@
+  _   _                       _    ___
+ | | | | ___  _ __ _ __   ___| |_ / _ \
+ | |_| |/ _ \| '__| '_ \ / _ \ __| | | |
+ |  _  | (_) | |  | | | |  __/ |_| |_| |
+ |_| |_|\___/|_|  |_| |_|\___|\__|\__\_\
+ HornetQ ${project.version}
+
+

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/cli/ConfigurationException.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/cli/ConfigurationException.java b/hornetq-bootstrap/src/main/java/org/hornetq/cli/ConfigurationException.java
new file mode 100644
index 0000000..5f53bbb
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/cli/ConfigurationException.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.cli;
+
+public class ConfigurationException extends Exception
+{
+   public ConfigurationException(String message)
+   {
+      super(message);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/cli/HornetQ.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/cli/HornetQ.java b/hornetq-bootstrap/src/main/java/org/hornetq/cli/HornetQ.java
new file mode 100644
index 0000000..d2e260e
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/cli/HornetQ.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.cli;
+
+import io.airlift.command.Cli;
+import io.airlift.command.ParseArgumentsUnexpectedException;
+import org.hornetq.cli.commands.Action;
+import org.hornetq.cli.commands.ActionContext;
+import org.hornetq.cli.commands.HelpAction;
+import org.hornetq.cli.commands.Run;
+import org.hornetq.cli.commands.Stop;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+public class HornetQ
+{
+
+   public static void main(String[] args) throws Exception
+   {
+      Cli.CliBuilder<Action> builder = Cli.<Action>builder("hornetq")
+               .withDefaultCommand(HelpAction.class)
+               .withCommand(Run.class)
+               .withCommand(Stop.class)
+               .withCommand(HelpAction.class)
+               .withDescription("HornetQ Command Line");
+
+      Cli<Action> parser = builder.build();
+
+      try
+      {
+         parser.parse(args).execute(ActionContext.system());
+      }
+      catch (ParseArgumentsUnexpectedException e)
+      {
+         System.err.println(e.getMessage());
+         System.out.println();
+         parser.parse("help").execute(ActionContext.system());
+      }
+      catch (ConfigurationException configException)
+      {
+         System.err.println(configException.getMessage());
+         System.out.println();
+         System.out.println("Configuration should be specified as 'scheme:location'. Default configuration is 'xml:${HORNETQ_HOME}/config/non-clustered/bootstrap.xml'");
+      }
+
+   }
+
+   public static void printBanner() throws Exception
+   {
+      copy(HornetQ.class.getResourceAsStream("banner.txt"), System.out);
+   }
+
+   private static long copy(InputStream in, OutputStream out) throws Exception
+   {
+      byte[] buffer = new byte[1024];
+      int len = in.read(buffer);
+      while (len != -1)
+      {
+         out.write(buffer, 0, len);
+         len = in.read(buffer);
+      }
+      return len;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Action.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Action.java b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Action.java
new file mode 100644
index 0000000..bf79994
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Action.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.cli.commands;
+
+public interface Action
+{
+
+   Object execute(ActionContext context) throws Exception;
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/ActionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/ActionContext.java b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/ActionContext.java
new file mode 100644
index 0000000..c31bd88
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/ActionContext.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.cli.commands;
+
+import java.io.InputStream;
+import java.io.PrintStream;
+
+public class ActionContext
+{
+
+   public ActionContext(InputStream in, PrintStream out, PrintStream err)
+   {
+      this.in = in;
+      this.out = out;
+      this.err = err;
+   }
+
+   InputStream in;
+   PrintStream out;
+   PrintStream err;
+
+   public static ActionContext system()
+   {
+      return new ActionContext(System.in, System.out, System.err);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/HelpAction.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/HelpAction.java b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/HelpAction.java
new file mode 100644
index 0000000..d87e859
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/HelpAction.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.cli.commands;
+
+import io.airlift.command.Help;
+
+public class HelpAction extends Help implements Action
+{
+
+   @Override
+   public Object execute(ActionContext context) throws Exception
+   {
+      super.run();
+      return null;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Run.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Run.java b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Run.java
new file mode 100644
index 0000000..c385524
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Run.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.cli.commands;
+
+import io.airlift.command.Arguments;
+import io.airlift.command.Command;
+
+import org.hornetq.cli.HornetQ;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.dto.BrokerDTO;
+import org.hornetq.factory.BrokerFactory;
+import org.hornetq.factory.CoreFactory;
+import org.hornetq.factory.JmsFactory;
+import org.hornetq.factory.SecurityManagerFactory;
+import org.hornetq.integration.bootstrap.HornetQBootstrapLogger;
+import org.hornetq.jms.server.JMSServerManager;
+import org.hornetq.jms.server.config.JMSConfiguration;
+import org.hornetq.jms.server.impl.JMSServerManagerImpl;
+import org.hornetq.jms.server.impl.StandaloneNamingServer;
+import org.hornetq.spi.core.security.HornetQSecurityManager;
+
+import javax.management.MBeanServer;
+
+import java.io.File;
+import java.lang.management.ManagementFactory;
+import java.util.Timer;
+import java.util.TimerTask;
+
+@Command(name = "run", description = "runs the broker instance")
+public class Run implements Action
+{
+
+   @Arguments(description = "Broker Configuration URI, default 'xml:${HORNETQ_HOME}/config/non-clustered/bootstrap.xml'")
+   String configuration;
+   private StandaloneNamingServer namingServer;
+   private JMSServerManager jmsServerManager;
+
+   @Override
+   public Object execute(ActionContext context) throws Exception
+   {
+
+      HornetQ.printBanner();
+
+      if (configuration == null)
+      {
+         configuration = "xml:" + System.getProperty("hornetq.home").replace("\\", "/") + "/config/non-clustered/bootstrap.xml";
+      }
+
+      System.out.println("Loading configuration file: " + configuration);
+
+      BrokerDTO broker = BrokerFactory.createBroker(configuration);
+
+      addShutdownHook(new File(broker.core.configuration).getParentFile());
+
+      Configuration core = CoreFactory.create(broker.core);
+
+      JMSConfiguration jms = JmsFactory.create(broker.jms);
+
+      HornetQSecurityManager security = SecurityManagerFactory.create(broker.security);
+
+      MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
+
+      HornetQServerImpl server = new HornetQServerImpl(core, mBeanServer, security);
+
+      namingServer = new StandaloneNamingServer(server);
+
+      namingServer.setBindAddress(broker.naming.bindAddress);
+
+      namingServer.setPort(broker.naming.port);
+
+      namingServer.setRmiBindAddress(broker.naming.rmiBindAddress);
+
+      namingServer.setRmiPort(broker.naming.rmiPort);
+
+      namingServer.start();
+
+      HornetQBootstrapLogger.LOGGER.startedNamingService(broker.naming.bindAddress, broker.naming.port, broker.naming.rmiBindAddress, broker.naming.rmiPort);
+
+      if (jms != null)
+      {
+         jmsServerManager = new JMSServerManagerImpl(server, jms);
+      }
+      else
+      {
+         jmsServerManager = new JMSServerManagerImpl(server);
+      }
+
+      HornetQBootstrapLogger.LOGGER.serverStarting();
+
+      jmsServerManager.start();
+
+      return null;
+   }
+
+   /**
+    * Add a simple shutdown hook to stop the server.
+    * @param configurationDir
+    */
+   private void addShutdownHook(File configurationDir)
+   {
+      final File file = new File(configurationDir,"STOP_ME");
+      if (file.exists())
+      {
+         if (!file.delete())
+         {
+            HornetQBootstrapLogger.LOGGER.errorDeletingFile(file.getAbsolutePath());
+         }
+      }
+      final Timer timer = new Timer("HornetQ Server Shutdown Timer", true);
+      timer.scheduleAtFixedRate(new TimerTask()
+      {
+         @Override
+         public void run()
+         {
+            if (file.exists())
+            {
+               try
+               {
+                  try
+                  {
+                     jmsServerManager.stop();
+                  }
+                  catch (Exception e)
+                  {
+                     e.printStackTrace();
+                  }
+                  timer.cancel();
+               }
+               finally
+               {
+                  Runtime.getRuntime().exit(0);
+               }
+            }
+         }
+      }, 500, 500);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Stop.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Stop.java b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Stop.java
new file mode 100644
index 0000000..1478507
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/cli/commands/Stop.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.cli.commands;
+
+import io.airlift.command.Arguments;
+import io.airlift.command.Command;
+import org.hornetq.dto.BrokerDTO;
+import org.hornetq.factory.BrokerFactory;
+
+import java.io.File;
+
+@Command(name = "stop", description = "stops the broker instance")
+public class Stop implements Action
+{
+   @Arguments(description = "Broker Configuration URI, default 'xml:${HORNETQ_HOME}/config/non-clustered/bootstrap.xml'")
+   String configuration;
+
+   @Override
+   public Object execute(ActionContext context) throws Exception
+   {
+      if (configuration == null)
+      {
+         configuration = "xml:" + System.getProperty("hornetq.home").replace("\\", "/") + "/config/non-clustered/bootstrap.xml";
+      }
+      BrokerDTO broker = BrokerFactory.createBroker(configuration);
+
+      File file = new File(broker.core.configuration).getParentFile();
+
+      File stopFile = new File(file, "STOP_ME");
+
+      stopFile.createNewFile();
+
+      return null;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactory.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactory.java
new file mode 100644
index 0000000..723b8f4
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactory.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.cli.ConfigurationException;
+import org.hornetq.dto.BrokerDTO;
+import org.hornetq.utils.FactoryFinder;
+
+import java.io.IOException;
+import java.net.URI;
+
+public class BrokerFactory
+{
+
+   public static BrokerDTO createBroker(URI configURI) throws Exception
+   {
+      if (configURI.getScheme() == null)
+      {
+         throw new ConfigurationException("Invalid configuration URI, no scheme specified: " + configURI);
+      }
+
+      BrokerFactoryHandler factory = null;
+      try
+      {
+         FactoryFinder finder = new FactoryFinder("META-INF/services/org/hornetq/broker/");
+         factory = (BrokerFactoryHandler)finder.newInstance(configURI.getScheme());
+      }
+      catch (IOException ioe )
+      {
+         throw new ConfigurationException("Invalid configuration URI, can't find configuration scheme: " + configURI.getScheme());
+      }
+
+
+      return factory.createBroker(configURI);
+   }
+
+   public static BrokerDTO createBroker(String configuration) throws Exception
+   {
+      return createBroker(new URI(configuration));
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactoryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactoryHandler.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactoryHandler.java
new file mode 100644
index 0000000..68afb4b
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/BrokerFactoryHandler.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.dto.BrokerDTO;
+
+import java.net.URI;
+
+public interface BrokerFactoryHandler
+{
+   BrokerDTO createBroker(URI brokerURI) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactory.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactory.java
new file mode 100644
index 0000000..d03cc97
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactory.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.cli.ConfigurationException;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.impl.ConfigurationImpl;
+import org.hornetq.dto.CoreDTO;
+import org.hornetq.utils.FactoryFinder;
+
+import java.io.IOException;
+import java.net.URI;
+
+public class CoreFactory
+{
+   public static Configuration create(CoreDTO core) throws Exception
+   {
+      if (core.configuration != null)
+      {
+         CoreFactoryHandler factory = null;
+         URI configURI = new URI(core.configuration.replace("\\", "/"));
+         try
+         {
+            FactoryFinder finder = new FactoryFinder("META-INF/services/org/hornetq/broker/core/");
+            factory = (CoreFactoryHandler)finder.newInstance(configURI.getScheme());
+         }
+         catch (IOException ioe )
+         {
+            throw new ConfigurationException("Invalid configuration URI, can't find configuration scheme: " + configURI.getScheme());
+         }
+
+         return factory.createConfiguration(configURI);
+      }
+      return new ConfigurationImpl();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactoryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactoryHandler.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactoryHandler.java
new file mode 100644
index 0000000..bec7c85
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/CoreFactoryHandler.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.core.config.Configuration;
+
+import java.net.URI;
+
+public interface CoreFactoryHandler
+{
+   Configuration createConfiguration(URI configuration) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileCoreFactoryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileCoreFactoryHandler.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileCoreFactoryHandler.java
new file mode 100644
index 0000000..76edad7
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileCoreFactoryHandler.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.impl.FileConfiguration;
+
+import java.net.URI;
+
+public class FileCoreFactoryHandler implements CoreFactoryHandler
+{
+   @Override
+   public Configuration createConfiguration(URI configuration) throws Exception
+   {
+      FileConfiguration fileConfiguration = new FileConfiguration(configuration.toURL().toExternalForm());
+      fileConfiguration.start();
+      return fileConfiguration;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileJmsFactoryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileJmsFactoryHandler.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileJmsFactoryHandler.java
new file mode 100644
index 0000000..dc28036
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/FileJmsFactoryHandler.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.jms.server.config.JMSConfiguration;
+import org.hornetq.jms.server.impl.JMSServerConfigParserImpl;
+
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.net.URI;
+
+public class FileJmsFactoryHandler implements JmsFactoryHandler
+{
+   @Override
+   public JMSConfiguration createConfiguration(URI configuration) throws Exception
+   {
+      try (InputStream configIn = new FileInputStream(configuration.getSchemeSpecificPart()))
+      {
+         return new JMSServerConfigParserImpl().parseConfiguration(configIn);
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactory.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactory.java
new file mode 100644
index 0000000..755ce58
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactory.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import java.io.IOException;
+import java.net.URI;
+
+import org.hornetq.cli.ConfigurationException;
+import org.hornetq.dto.JmsDTO;
+import org.hornetq.jms.server.config.JMSConfiguration;
+import org.hornetq.utils.FactoryFinder;
+
+public class JmsFactory
+{
+   public static JMSConfiguration create(JmsDTO jms) throws Exception
+   {
+      if (jms != null && jms.configuration != null)
+      {
+         JmsFactoryHandler factory = null;
+         URI configURI = new URI(jms.configuration.replace("\\", "/"));
+         try
+         {
+            FactoryFinder finder = new FactoryFinder("META-INF/services/org/hornetq/broker/jms/");
+            factory = (JmsFactoryHandler)finder.newInstance(configURI.getScheme());
+         }
+         catch (IOException ioe )
+         {
+            throw new ConfigurationException("Invalid configuration URI, can't find configuration scheme: " + configURI.getScheme());
+         }
+
+         return factory.createConfiguration(configURI);
+      }
+
+      return null;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactoryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactoryHandler.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactoryHandler.java
new file mode 100644
index 0000000..0a1bbd5
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/JmsFactoryHandler.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.jms.server.config.JMSConfiguration;
+
+import java.net.URI;
+
+public interface JmsFactoryHandler
+{
+   JMSConfiguration createConfiguration(URI configuration) throws Exception;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/SecurityManagerFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/SecurityManagerFactory.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/SecurityManagerFactory.java
new file mode 100644
index 0000000..c1ad221
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/SecurityManagerFactory.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.dto.SecurityDTO;
+import org.hornetq.spi.core.security.HornetQSecurityManager;
+import org.hornetq.utils.FactoryFinder;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+public class SecurityManagerFactory
+{
+
+   public static HornetQSecurityManager create(SecurityDTO config) throws Exception
+   {
+      if (config != null)
+      {
+         FactoryFinder finder = new FactoryFinder("META-INF/services/org/hornetq/security/");
+         HornetQSecurityManager manager = (HornetQSecurityManager)finder.newInstance(config.getClass().getAnnotation(XmlRootElement.class).name());
+         return manager;
+      }
+      else
+      {
+         throw new Exception("No security manager configured!");
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/factory/XmlBrokerFactoryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/factory/XmlBrokerFactoryHandler.java b/hornetq-bootstrap/src/main/java/org/hornetq/factory/XmlBrokerFactoryHandler.java
new file mode 100644
index 0000000..ffb37b9
--- /dev/null
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/factory/XmlBrokerFactoryHandler.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.factory;
+
+import org.hornetq.cli.ConfigurationException;
+import org.hornetq.dto.BrokerDTO;
+import org.hornetq.dto.XmlUtil;
+
+import java.io.File;
+import java.net.URI;
+
+public class XmlBrokerFactoryHandler implements BrokerFactoryHandler
+{
+   @Override
+   public BrokerDTO createBroker(URI brokerURI) throws Exception
+   {
+      File file = new File(brokerURI.getSchemeSpecificPart());
+      if (!file.exists())
+      {
+         throw new ConfigurationException("Invalid configuration URI, can't find file: " + file.getName());
+      }
+      return XmlUtil.decode(BrokerDTO.class, file);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapLogger.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapLogger.java b/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapLogger.java
index f85b78c..a426752 100644
--- a/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapLogger.java
+++ b/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapLogger.java
@@ -53,6 +53,10 @@ public interface HornetQBootstrapLogger extends BasicLogger
    @Message(id = 101001, value = "Stopping HornetQ Server", format = Message.Format.MESSAGE_FORMAT)
    void serverStopping();
 
+   @LogMessage(level = Logger.Level.INFO)
+   @Message(id = 101002, value = "Starting Naming server on {0}:{1,number,#} (rmi {2}:{3,number,#})", format = Message.Format.MESSAGE_FORMAT)
+   void startedNamingService(String bindAddress, int port, String rmiBindAddress, int rmiPort);
+
    @LogMessage(level = Logger.Level.WARN)
    @Message(id = 102000, value = "Error during undeployment: {0}", format = Message.Format.MESSAGE_FORMAT)
    void errorDuringUndeployment(@Cause Throwable t, String name);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapServer.java
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapServer.java b/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapServer.java
deleted file mode 100644
index 34a8246..0000000
--- a/hornetq-bootstrap/src/main/java/org/hornetq/integration/bootstrap/HornetQBootstrapServer.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.integration.bootstrap;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.PrintStream;
-import java.net.URL;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Properties;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.jboss.kernel.plugins.bootstrap.basic.BasicBootstrap;
-import org.jboss.kernel.plugins.deployment.xml.BeanXMLDeployer;
-import org.jboss.kernel.spi.config.KernelConfig;
-import org.jboss.kernel.spi.deployment.KernelDeployment;
-
-/**
- * This is the method in which the HornetQ server can be deployed externally outside of jBoss.
- * Alternatively a user can embed by using the same code as in main
- * @author <a href="ataylor@redhat.com">Andy Taylor</a>
- */
-public class HornetQBootstrapServer extends BasicBootstrap
-{
-   /**
-    * The deployer
-    */
-   protected BeanXMLDeployer deployer;
-
-   /**
-    * The deployments
-    */
-   protected List<KernelDeployment> deployments = new CopyOnWriteArrayList<KernelDeployment>();
-
-   /**
-    * The arguments
-    */
-   private final String[] args;
-
-   private Properties properties;
-
-   /**
-    * Bootstrap the kernel from the command line
-    *
-    * @param args the command line arguments
-    * @throws Exception for any error
-    */
-   public static void main(final String[] args) throws Exception
-   {
-      HornetQBootstrapLogger.LOGGER.serverStarting();
-
-      final HornetQBootstrapServer bootstrap = new HornetQBootstrapServer(args);
-
-      bootstrap.run();
-
-      bootstrap.addShutdownHook();
-   }
-
-   /**
-    * Add a simple shutdown hook to stop the server.
-    */
-   private void addShutdownHook()
-   {
-      String dirName = System.getProperty("hornetq.config.dir", ".");
-      final File file = new File(dirName + "/STOP_ME");
-      if (file.exists())
-      {
-         if (!file.delete())
-         {
-            HornetQBootstrapLogger.LOGGER.errorDeletingFile(file.getAbsolutePath());
-         }
-      }
-      final Timer timer = new Timer("HornetQ Server Shutdown Timer", true);
-      timer.scheduleAtFixedRate(new TimerTask()
-      {
-         @Override
-         public void run()
-         {
-            if (file.exists())
-            {
-               try
-               {
-                  shutDown();
-                  timer.cancel();
-               }
-               finally
-               {
-                  Runtime.getRuntime().exit(0);
-               }
-            }
-         }
-      }, 500, 500);
-   }
-
-   @Override
-   public void run()
-   {
-      try
-      {
-         super.run();
-      }
-      catch (RuntimeException e)
-      {
-         HornetQBootstrapLogger.LOGGER.errorStartingServer(e);
-
-         throw e;
-      }
-   }
-
-   /**
-    * JBoss 1.0.0 final
-    * Standalone
-    * Create a new bootstrap
-    *
-    * @param args the arguments
-    * @throws Exception for any error
-    */
-   public HornetQBootstrapServer(final String... args) throws Exception
-   {
-      super();
-      this.args = args;
-   }
-
-   public HornetQBootstrapServer(final KernelConfig kernelConfig, final String... args) throws Exception
-   {
-      super(kernelConfig);
-      this.args = args;
-   }
-
-   @Override
-   public void bootstrap() throws Throwable
-   {
-      super.bootstrap();
-      deployer = new BeanXMLDeployer(getKernel());
-      Runtime.getRuntime().addShutdownHook(new Shutdown());
-
-      for (String arg : args)
-      {
-         deploy(arg);
-      }
-
-      deployer.validate();
-   }
-
-   /**
-    * Undeploy a deployment
-    *
-    * @param deployment the deployment
-    */
-   public void undeploy(final KernelDeployment deployment) throws Throwable
-   {
-      HornetQBootstrapLogger.LOGGER.debug("Undeploying " + deployment.getName());
-      deployments.remove(deployment);
-      try
-      {
-         deployer.undeploy(deployment);
-         HornetQBootstrapLogger.LOGGER.debug("Undeployed " + deployment.getName());
-      }
-      catch (Throwable t)
-      {
-         HornetQBootstrapLogger.LOGGER.errorDuringUndeployment(t, deployment.getName());
-         HornetQBootstrapLogger.LOGGER.warn("Error during undeployment: " + deployment.getName(), t);
-      }
-   }
-
-   public KernelDeployment deploy(final String arg) throws Throwable
-   {
-      ClassLoader cl = Thread.currentThread().getContextClassLoader();
-      URL url = cl.getResource(arg);
-      if (url == null)
-      {
-         url = cl.getResource("META-INF/" + arg);
-      }
-      // try the system classpath
-      if (url == null)
-      {
-         url = getClass().getClassLoader().getResource(arg);
-      }
-      if (url == null)
-      {
-         File file = new File(arg);
-         if (file.exists())
-         {
-            url = file.toURI().toURL();
-         }
-      }
-      if (url == null)
-      {
-         throw new RuntimeException("Unable to find resource:" + arg);
-      }
-      return deploy(url);
-   }
-
-   /**
-    * Deploys a XML on the container
-    */
-   public KernelDeployment deploy(final String name, final String xml) throws Throwable
-   {
-      ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
-      PrintStream printOut = new PrintStream(byteOut);
-      printOut.print(xml);
-      printOut.flush();
-      ByteArrayInputStream is = new ByteArrayInputStream(byteOut.toByteArray());
-
-      KernelDeployment deployment = deployer.deploy(name, is);
-
-      deployments.add(deployment);
-
-      return deployment;
-   }
-
-   /**
-    * Deploy a url
-    *
-    * @param url the deployment url
-    * @throws Throwable for any error
-    */
-   private KernelDeployment deploy(final URL url) throws Throwable
-   {
-      HornetQBootstrapLogger.LOGGER.debug("Deploying " + url);
-      KernelDeployment deployment = deployer.deploy(url);
-      deployments.add(deployment);
-      HornetQBootstrapLogger.LOGGER.debug("Deployed " + url);
-      return deployment;
-   }
-
-   public void shutDown()
-   {
-      HornetQBootstrapLogger.LOGGER.serverStopping();
-
-      ListIterator<KernelDeployment> iterator = deployments.listIterator(deployments.size());
-      while (iterator.hasPrevious())
-      {
-         KernelDeployment deployment = iterator.previous();
-         try
-         {
-            undeploy(deployment);
-         }
-         catch (Throwable t)
-         {
-            HornetQBootstrapLogger.LOGGER.errorDuringUndeployment(t, deployment.getName());
-         }
-      }
-   }
-
-   @Override
-   protected Properties getConfigProperties()
-   {
-      return properties;
-   }
-
-   public void setProperties(final Properties props)
-   {
-      properties = props;
-   }
-
-   private final class Shutdown extends Thread
-   {
-      public Shutdown()
-      {
-         super("hornetq-shutdown-thread");
-      }
-
-      @Override
-      public void run()
-      {
-         shutDown();
-      }
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/core/file
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/core/file b/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/core/file
new file mode 100644
index 0000000..3fc5087
--- /dev/null
+++ b/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/core/file
@@ -0,0 +1,13 @@
+## ---------------------------------------------------------------------------
+## Copyright 2005-2014 Red Hat, Inc.
+## Red Hat licenses this file to you under the Apache License, version
+## 2.0 (the "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##    http://www.apache.org/licenses/LICENSE-2.0
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+## implied.  See the License for the specific language governing
+## permissions and limitations under the License.
+## ---------------------------------------------------------------------------
+class=org.hornetq.factory.FileCoreFactoryHandler
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/jms/file
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/jms/file b/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/jms/file
new file mode 100644
index 0000000..e3a9587
--- /dev/null
+++ b/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/jms/file
@@ -0,0 +1,13 @@
+## ---------------------------------------------------------------------------
+## Copyright 2005-2014 Red Hat, Inc.
+## Red Hat licenses this file to you under the Apache License, version
+## 2.0 (the "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##    http://www.apache.org/licenses/LICENSE-2.0
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+## implied.  See the License for the specific language governing
+## permissions and limitations under the License.
+## ---------------------------------------------------------------------------
+class=org.hornetq.factory.FileJmsFactoryHandler
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/xml
----------------------------------------------------------------------
diff --git a/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/xml b/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/xml
new file mode 100644
index 0000000..9501c92
--- /dev/null
+++ b/hornetq-bootstrap/src/main/resources/META-INF/services/org/hornetq/broker/xml
@@ -0,0 +1,13 @@
+## ---------------------------------------------------------------------------
+## Copyright 2005-2014 Red Hat, Inc.
+## Red Hat licenses this file to you under the Apache License, version
+## 2.0 (the "License"); you may not use this file except in compliance
+## with the License.  You may obtain a copy of the License at
+##    http://www.apache.org/licenses/LICENSE-2.0
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+## implied.  See the License for the specific language governing
+## permissions and limitations under the License.
+## ---------------------------------------------------------------------------
+class=org.hornetq.factory.XmlBrokerFactoryHandler
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-commons/src/main/java/org/hornetq/utils/ByteUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-commons/src/main/java/org/hornetq/utils/ByteUtil.java b/hornetq-commons/src/main/java/org/hornetq/utils/ByteUtil.java
new file mode 100644
index 0000000..20285e1
--- /dev/null
+++ b/hornetq-commons/src/main/java/org/hornetq/utils/ByteUtil.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.utils;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.UnpooledByteBufAllocator;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ByteUtil
+{
+
+   private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
+
+   public static String maxString(String value, int size)
+   {
+      if (value.length() < size)
+      {
+         return value;
+      }
+      else
+      {
+         return value.substring(0, size / 2) + " ... " + value.substring(value.length() - size / 2);
+      }
+   }
+   public static String bytesToHex(byte[] bytes, int groupSize)
+   {
+      if (bytes == null)
+      {
+         return "null";
+      }
+      else
+      {
+         char[] hexChars = new char[bytes.length * 2 + numberOfGroups(bytes, groupSize)];
+         int outPos = 0;
+         for (int j = 0; j < bytes.length; j++)
+         {
+            if (j > 0 && j % groupSize == 0)
+            {
+               hexChars[outPos++] = ' ';
+            }
+            int v = bytes[j] & 0xFF;
+            hexChars[outPos++] = hexArray[v >>> 4];
+            hexChars[outPos++] = hexArray[v & 0x0F];
+         }
+         return new String(hexChars);
+      }
+   }
+
+   private static int numberOfGroups(byte[] bytes, int groupSize)
+   {
+      int groups = bytes.length / groupSize;
+
+      if (bytes.length % groupSize == 0)
+      {
+         groups--;
+      }
+
+      return groups;
+   }
+
+   public static byte[] longToBytes(long x)
+   {
+      ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.heapBuffer(8, 8);
+      buffer.writeLong(x);
+      return buffer.array();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-commons/src/main/java/org/hornetq/utils/FactoryFinder.java
----------------------------------------------------------------------
diff --git a/hornetq-commons/src/main/java/org/hornetq/utils/FactoryFinder.java b/hornetq-commons/src/main/java/org/hornetq/utils/FactoryFinder.java
new file mode 100644
index 0000000..a057656
--- /dev/null
+++ b/hornetq-commons/src/main/java/org/hornetq/utils/FactoryFinder.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.utils;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class FactoryFinder
+{
+   /**
+    * The strategy that the FactoryFinder uses to find load and instantiate Objects
+    * can be changed out by calling the
+    * {@link org.hornetq.utils.FactoryFinder#setObjectFactory(org.hornetq.utils.FactoryFinder.ObjectFactory)}
+    * method with a custom implementation of ObjectFactory.
+    * <p/>
+    * The default ObjectFactory is typically changed out when running in a specialized container
+    * environment where service discovery needs to be done via the container system.  For example,
+    * in an OSGi scenario.
+    */
+   public interface ObjectFactory
+   {
+      /**
+       * @param path the full service path
+       * @return
+       */
+      Object create(String path) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException;
+
+   }
+
+   /**
+    * The default implementation of Object factory which works well in standalone applications.
+    */
+   protected static class StandaloneObjectFactory implements ObjectFactory
+   {
+      final ConcurrentHashMap<String, Class> classMap = new ConcurrentHashMap<String, Class>();
+
+      public Object create(final String path) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException
+      {
+         Class clazz = classMap.get(path);
+         if (clazz == null)
+         {
+            clazz = loadClass(loadProperties(path));
+            classMap.put(path, clazz);
+         }
+         return clazz.newInstance();
+      }
+
+      static Class loadClass(Properties properties) throws ClassNotFoundException, IOException
+      {
+
+         String className = properties.getProperty("class");
+         if (className == null)
+         {
+            throw new IOException("Expected property is missing: class");
+         }
+         Class clazz = null;
+         ClassLoader loader = Thread.currentThread().getContextClassLoader();
+         if (loader != null)
+         {
+            try
+            {
+               clazz = loader.loadClass(className);
+            }
+            catch (ClassNotFoundException e)
+            {
+               // ignore
+            }
+         }
+         if (clazz == null)
+         {
+            clazz = FactoryFinder.class.getClassLoader().loadClass(className);
+         }
+
+         return clazz;
+      }
+
+      public Properties loadProperties(String uri) throws IOException
+      {
+         // lets try the thread context class loader first
+         ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+         if (classLoader == null)
+         {
+            classLoader = StandaloneObjectFactory.class.getClassLoader();
+         }
+         InputStream in = classLoader.getResourceAsStream(uri);
+         if (in == null)
+         {
+            in = FactoryFinder.class.getClassLoader().getResourceAsStream(uri);
+            if (in == null)
+            {
+               throw new IOException("Could not find factory class for resource: " + uri);
+            }
+         }
+
+         // lets load the file
+         BufferedInputStream reader = null;
+         try
+         {
+            reader = new BufferedInputStream(in);
+            Properties properties = new Properties();
+            properties.load(reader);
+            return properties;
+         }
+         finally
+         {
+            try
+            {
+               reader.close();
+            }
+            catch (Exception e)
+            {
+            }
+         }
+      }
+   }
+
+   // ================================================================
+   // Class methods and properties
+   // ================================================================
+   private static ObjectFactory objectFactory = new StandaloneObjectFactory();
+
+   public static ObjectFactory getObjectFactory()
+   {
+      return objectFactory;
+   }
+
+   public static void setObjectFactory(ObjectFactory objectFactory)
+   {
+      FactoryFinder.objectFactory = objectFactory;
+   }
+
+   // ================================================================
+   // Instance methods and properties
+   // ================================================================
+   private final String path;
+
+   public FactoryFinder(String path)
+   {
+      this.path = path;
+   }
+
+   /**
+    * Creates a new instance of the given key
+    *
+    * @param key is the key to add to the path to find a text file containing
+    *            the factory name
+    * @return a newly created instance
+    */
+   public Object newInstance(String key) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException
+   {
+      return objectFactory.create(path + key);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-commons/src/main/java/org/hornetq/utils/HornetQThreadFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-commons/src/main/java/org/hornetq/utils/HornetQThreadFactory.java b/hornetq-commons/src/main/java/org/hornetq/utils/HornetQThreadFactory.java
index 2fc63ec..be16d4c 100644
--- a/hornetq-commons/src/main/java/org/hornetq/utils/HornetQThreadFactory.java
+++ b/hornetq-commons/src/main/java/org/hornetq/utils/HornetQThreadFactory.java
@@ -49,44 +49,20 @@ public final class HornetQThreadFactory implements ThreadFactory
 
    public Thread newThread(final Runnable command)
    {
-      final Thread t;
-      // attach the thread to a group only if there is no security manager:
-      // when sandboxed, the code does not have the RuntimePermission modifyThreadGroup
-      if (System.getSecurityManager() == null)
+      // always create a thread in a privileged block.
+      return AccessController.doPrivileged(new PrivilegedAction<Thread>()
       {
-         t = new Thread(group, command, "Thread-" + threadCount.getAndIncrement() + " (" + group.getName() + ")");
-      }
-      else
-      {
-         t = new Thread(command, "Thread-" + threadCount.getAndIncrement());
-      }
-
-      AccessController.doPrivileged(new PrivilegedAction<Object>()
-      {
-         public Object run()
+         @Override
+         public Thread run()
          {
+            final Thread t = new Thread(group, command, "Thread-" + threadCount.getAndIncrement() + " (" + group.getName() + ")");
             t.setDaemon(daemon);
             t.setPriority(threadPriority);
-            return null;
+            t.setContextClassLoader(tccl);
+
+            return t;
          }
       });
-
-      try
-      {
-         AccessController.doPrivileged(new PrivilegedAction<Object>()
-         {
-            public Object run()
-            {
-               t.setContextClassLoader(tccl);
-               return null;
-            }
-         });
-      }
-      catch (java.security.AccessControlException e)
-      {
-         HornetQUtilLogger.LOGGER.missingPrivsForClassloader();
-      }
-
-      return t;
    }
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-commons/src/main/java/org/hornetq/utils/TypedProperties.java
----------------------------------------------------------------------
diff --git a/hornetq-commons/src/main/java/org/hornetq/utils/TypedProperties.java b/hornetq-commons/src/main/java/org/hornetq/utils/TypedProperties.java
index f6375a8..d970ebd 100644
--- a/hornetq-commons/src/main/java/org/hornetq/utils/TypedProperties.java
+++ b/hornetq-commons/src/main/java/org/hornetq/utils/TypedProperties.java
@@ -12,8 +12,10 @@
  */
 package org.hornetq.utils;
 
+import java.nio.ByteBuffer;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
@@ -599,7 +601,70 @@ public final class TypedProperties
    @Override
    public String toString()
    {
-      return "TypedProperties[" + properties + "]";
+      StringBuilder sb = new StringBuilder("TypedProperties[");
+
+
+      if (properties != null)
+      {
+
+         Iterator<Entry<SimpleString, PropertyValue>> iter = properties.entrySet().iterator();
+
+         while (iter.hasNext())
+         {
+            Entry<SimpleString, PropertyValue> iterItem = iter.next();
+            sb.append(iterItem.getKey() + "=");
+
+            // it seems weird but it's right!!
+            // The first getValue is from the EntrySet
+            // The second is to convert the PropertyValue into the actual value
+            Object theValue = iterItem.getValue().getValue();
+
+
+            if (theValue == null)
+            {
+               sb.append("NULL-value");
+            }
+            else if (theValue instanceof byte[])
+            {
+               sb.append("[" + ByteUtil.maxString(ByteUtil.bytesToHex((byte [])theValue, 2), 150) + ")");
+
+               if (iterItem.getKey().toString().startsWith("_HQ_ROUTE_TO"))
+               {
+                  sb.append(",bytesAsLongs(");
+                  try
+                  {
+                     ByteBuffer buff = ByteBuffer.wrap((byte[]) theValue);
+                     while (buff.hasRemaining())
+                     {
+                        long bindingID = buff.getLong();
+                        sb.append(bindingID);
+                        if (buff.hasRemaining())
+                        {
+                           sb.append(",");
+                        }
+                     }
+                  }
+                  catch (Throwable e)
+                  {
+                     sb.append("error-converting-longs=" + e.getMessage());
+                  }
+                  sb.append("]");
+               }
+            }
+            else
+            {
+               sb.append(theValue.toString());
+            }
+
+
+            if (iter.hasNext())
+            {
+               sb.append(",");
+            }
+         }
+      }
+
+      return sb.append("]").toString();
    }
 
    // Private ------------------------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-commons/src/main/java/org/hornetq/utils/UTF8Util.java
----------------------------------------------------------------------
diff --git a/hornetq-commons/src/main/java/org/hornetq/utils/UTF8Util.java b/hornetq-commons/src/main/java/org/hornetq/utils/UTF8Util.java
index 55cda20..6fd9253 100644
--- a/hornetq-commons/src/main/java/org/hornetq/utils/UTF8Util.java
+++ b/hornetq-commons/src/main/java/org/hornetq/utils/UTF8Util.java
@@ -167,7 +167,7 @@ public final class UTF8Util
 
    }
 
-   private static StringUtilBuffer getThreadLocalBuffer()
+   public static StringUtilBuffer getThreadLocalBuffer()
    {
       SoftReference<StringUtilBuffer> softReference = UTF8Util.currenBuffer.get();
       StringUtilBuffer value;
@@ -234,7 +234,7 @@ public final class UTF8Util
       return calculatedLen;
    }
 
-   private static class StringUtilBuffer
+   public static class StringUtilBuffer
    {
 
       public char[] charBuffer;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-commons/src/test/java/org/hornetq/utils/ByteUtilTest.java
----------------------------------------------------------------------
diff --git a/hornetq-commons/src/test/java/org/hornetq/utils/ByteUtilTest.java b/hornetq-commons/src/test/java/org/hornetq/utils/ByteUtilTest.java
new file mode 100644
index 0000000..f6ee7a2
--- /dev/null
+++ b/hornetq-commons/src/test/java/org/hornetq/utils/ByteUtilTest.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.utils;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ByteUtilTest
+{
+   @Test
+   public void testBytesToString()
+   {
+      byte[] byteArray = new byte[] {0, 1, 2, 3};
+
+      testEquals("0001 0203", ByteUtil.bytesToHex(byteArray, 2));
+      testEquals("00 01 02 03", ByteUtil.bytesToHex(byteArray, 1));
+      testEquals("000102 03", ByteUtil.bytesToHex(byteArray, 3));
+   }
+
+
+   @Test
+   public void testMaxString()
+   {
+      byte[] byteArray = new byte[20 * 1024];
+      System.out.println(ByteUtil.maxString(ByteUtil.bytesToHex(byteArray, 2),150));
+   }
+
+
+   void testEquals(String string1, String string2)
+   {
+      if (!string1.equals(string2))
+      {
+         Assert.fail("String are not the same:=" + string1 + "!=" + string2);
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastEndpointFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastEndpointFactory.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastEndpointFactory.java
index 447f708..ae6b5ab 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastEndpointFactory.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastEndpointFactory.java
@@ -12,8 +12,10 @@
  */
 package org.hornetq.api.core;
 
+import java.io.Serializable;
 
-public interface BroadcastEndpointFactory
+
+public interface BroadcastEndpointFactory extends Serializable
 {
    BroadcastEndpoint createBroadcastEndpoint() throws Exception;
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastGroupConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastGroupConfiguration.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastGroupConfiguration.java
index 2e35112..575cc32 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastGroupConfiguration.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/BroadcastGroupConfiguration.java
@@ -15,6 +15,8 @@ package org.hornetq.api.core;
 import java.io.Serializable;
 import java.util.List;
 
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+
 
 /**
  * The basic configuration used to determine how the server will broadcast members
@@ -28,23 +30,16 @@ public final class BroadcastGroupConfiguration implements Serializable
 {
    private static final long serialVersionUID = 2335634694112319124L;
 
-   private String name;
+   private String name = null;
 
-   private long broadcastPeriod;
+   private long broadcastPeriod = HornetQDefaultConfiguration.getDefaultBroadcastPeriod();
 
-   private final BroadcastEndpointFactoryConfiguration endpointFactoryConfiguration;
+   private BroadcastEndpointFactoryConfiguration endpointFactoryConfiguration = null;
 
-   private List<String> connectorInfos;
+   private List<String> connectorInfos = null;
 
-   public BroadcastGroupConfiguration(final String name,
-                                      final long broadcastPeriod,
-                                      final List<String> connectorInfos,
-                                      final BroadcastEndpointFactoryConfiguration endpointFactoryConfiguration)
+   public BroadcastGroupConfiguration()
    {
-      this.name = name;
-      this.broadcastPeriod = broadcastPeriod;
-      this.connectorInfos = connectorInfos;
-      this.endpointFactoryConfiguration = endpointFactoryConfiguration;
    }
 
    public String getName()
@@ -62,19 +57,22 @@ public final class BroadcastGroupConfiguration implements Serializable
       return connectorInfos;
    }
 
-   public void setName(final String name)
+   public BroadcastGroupConfiguration setName(final String name)
    {
       this.name = name;
+      return this;
    }
 
-   public void setBroadcastPeriod(final long broadcastPeriod)
+   public BroadcastGroupConfiguration setBroadcastPeriod(final long broadcastPeriod)
    {
       this.broadcastPeriod = broadcastPeriod;
+      return this;
    }
 
-   public void setConnectorInfos(final List<String> connectorInfos)
+   public BroadcastGroupConfiguration setConnectorInfos(final List<String> connectorInfos)
    {
       this.connectorInfos = connectorInfos;
+      return this;
    }
 
    public BroadcastEndpointFactoryConfiguration getEndpointFactoryConfiguration()
@@ -82,6 +80,12 @@ public final class BroadcastGroupConfiguration implements Serializable
       return endpointFactoryConfiguration;
    }
 
+   public BroadcastGroupConfiguration setEndpointFactoryConfiguration(BroadcastEndpointFactoryConfiguration endpointFactoryConfiguration)
+   {
+      this.endpointFactoryConfiguration = endpointFactoryConfiguration;
+      return this;
+   }
+
    @Override
    public int hashCode()
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/api/core/DiscoveryGroupConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/api/core/DiscoveryGroupConfiguration.java b/hornetq-core-client/src/main/java/org/hornetq/api/core/DiscoveryGroupConfiguration.java
index dbd83a8..d97408e 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/api/core/DiscoveryGroupConfiguration.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/api/core/DiscoveryGroupConfiguration.java
@@ -17,6 +17,7 @@ import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 
+import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.utils.UUIDGenerator;
 
 /**
@@ -36,61 +37,39 @@ public final class DiscoveryGroupConfiguration implements Serializable
 {
    private static final long serialVersionUID = 8657206421727863400L;
 
-   private String name;
+   private String name = UUIDGenerator.getInstance().generateStringUUID();
 
-   private long refreshTimeout;
+   private long refreshTimeout = HornetQClient.DEFAULT_DISCOVERY_REFRESH_TIMEOUT;
 
-   private long discoveryInitialWaitTimeout;
+   private long discoveryInitialWaitTimeout = HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT;
 
    /*
    * The localBindAddress is needed so we can be backward compatible with 2.2 clients
    * */
-   private transient String localBindAddress;
+   private transient String localBindAddress = null;
 
    /*
    * The localBindPort is needed so we can be backward compatible with 2.2 clients
    * */
-   private transient int localBindPort;
+   private transient int localBindPort = -1;
 
    /*
    * The groupAddress is needed so we can be backward compatible with 2.2 clients
    * */
-   private String groupAddress;
+   private String groupAddress = null;
 
    /*
    * The groupPort is needed so we can be backward compatible with 2.2 clients
    * */
-   private int groupPort;
+   private int groupPort = -1;
 
    /*
    * This is the actual object used by the class, it has to be transient so we can handle deserialization with a 2.2 client
    * */
    private transient BroadcastEndpointFactoryConfiguration endpointFactoryConfiguration;
 
-   public DiscoveryGroupConfiguration(final String name,
-                                      final long refreshTimeout,
-                                      final long discoveryInitialWaitTimeout, BroadcastEndpointFactoryConfiguration
-         endpointFactoryConfiguration)
+   public DiscoveryGroupConfiguration()
    {
-      this.name = name;
-      this.refreshTimeout = refreshTimeout;
-      this.discoveryInitialWaitTimeout = discoveryInitialWaitTimeout;
-      this.endpointFactoryConfiguration = endpointFactoryConfiguration;
-      if (endpointFactoryConfiguration instanceof DiscoveryGroupConfigurationCompatibilityHelper)
-      {
-         DiscoveryGroupConfigurationCompatibilityHelper dgcch = (DiscoveryGroupConfigurationCompatibilityHelper) endpointFactoryConfiguration;
-         localBindAddress = dgcch.getLocalBindAddress();
-         localBindPort = dgcch.getLocalBindPort();
-         groupAddress = dgcch.getGroupAddress();
-         groupPort = dgcch.getGroupPort();
-      }
-   }
-
-   public DiscoveryGroupConfiguration(final long refreshTimeout,
-                                      final long discoveryInitialWaitTimeout,
-                                            BroadcastEndpointFactoryConfiguration endpointFactoryConfiguration)
-   {
-      this(UUIDGenerator.getInstance().generateStringUUID(), refreshTimeout, discoveryInitialWaitTimeout, endpointFactoryConfiguration);
    }
 
    public String getName()
@@ -106,17 +85,19 @@ public final class DiscoveryGroupConfiguration implements Serializable
    /**
     * @param name the name to set
     */
-   public void setName(final String name)
+   public DiscoveryGroupConfiguration setName(final String name)
    {
       this.name = name;
+      return this;
    }
 
    /**
     * @param refreshTimeout the refreshTimeout to set
     */
-   public void setRefreshTimeout(final long refreshTimeout)
+   public DiscoveryGroupConfiguration setRefreshTimeout(final long refreshTimeout)
    {
       this.refreshTimeout = refreshTimeout;
+      return this;
    }
 
    /**
@@ -130,9 +111,10 @@ public final class DiscoveryGroupConfiguration implements Serializable
    /**
     * @param discoveryInitialWaitTimeout the discoveryInitialWaitTimeout to set
     */
-   public void setDiscoveryInitialWaitTimeout(long discoveryInitialWaitTimeout)
+   public DiscoveryGroupConfiguration setDiscoveryInitialWaitTimeout(long discoveryInitialWaitTimeout)
    {
       this.discoveryInitialWaitTimeout = discoveryInitialWaitTimeout;
+      return this;
    }
 
    public BroadcastEndpointFactoryConfiguration getBroadcastEndpointFactoryConfiguration()
@@ -140,6 +122,20 @@ public final class DiscoveryGroupConfiguration implements Serializable
       return endpointFactoryConfiguration;
    }
 
+   public DiscoveryGroupConfiguration setBroadcastEndpointFactoryConfiguration(BroadcastEndpointFactoryConfiguration endpointFactoryConfiguration)
+   {
+      this.endpointFactoryConfiguration = endpointFactoryConfiguration;
+      if (endpointFactoryConfiguration instanceof DiscoveryGroupConfigurationCompatibilityHelper)
+      {
+         DiscoveryGroupConfigurationCompatibilityHelper dgcch = (DiscoveryGroupConfigurationCompatibilityHelper) endpointFactoryConfiguration;
+         localBindAddress = dgcch.getLocalBindAddress();
+         localBindPort = dgcch.getLocalBindPort();
+         groupAddress = dgcch.getGroupAddress();
+         groupPort = dgcch.getGroupPort();
+      }
+      return this;
+   }
+
    private void writeObject(ObjectOutputStream out) throws IOException
    {
       out.defaultWriteObject();
@@ -158,7 +154,11 @@ public final class DiscoveryGroupConfiguration implements Serializable
       }
       else
       {
-         endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration(groupAddress, groupPort, localBindAddress, localBindPort);
+         endpointFactoryConfiguration = new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(groupAddress)
+            .setGroupPort(groupPort)
+            .setLocalBindAddress(localBindAddress)
+            .setLocalBindPort(localBindPort);
       }
    }
 


[12/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingTest.java
index 1ee3040..c47d79d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/PagingTest.java
@@ -113,9 +113,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server =
          createServer(true, config,
@@ -205,9 +204,9 @@ public class PagingTest extends ServiceTestBase
 
       session.start();
 
-      assertEquals(numberOfMessages * 2, queue.getMessageCount());
+      assertEquals(numberOfMessages * 2, getMessageCount(queue));
 
-      // The consumer has to be created after the queue.getMessageCount assertion
+      // The consumer has to be created after the getMessageCount(queue) assertion
       // otherwise delivery could alter the messagecount and give us a false failure
       ClientConsumer consumer = session.createConsumer(PagingTest.ADDRESS);
       ClientMessage msg = null;
@@ -231,7 +230,7 @@ public class PagingTest extends ServiceTestBase
 
       locator.close();
 
-      assertEquals(0, queue.getMessageCount());
+      assertEquals(0, getMessageCount(queue));
 
       waitForNotPaging(queue);
 
@@ -253,9 +252,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server =
          createServer(true, config,
@@ -374,9 +372,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -542,7 +539,7 @@ public class PagingTest extends ServiceTestBase
       assertNull(cons.receiveImmediate());
       session.commit();
 
-      System.out.println("count = " + queue.getMessageCount());
+      System.out.println("count = " + getMessageCount(queue));
 
       session.commit();
 
@@ -592,14 +589,11 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalDirectory(getJournalDir());
-
-      config.setJournalSyncNonTransactional(false);
-      config.setJournalCompactMinFiles(0); // disable compact
-
-      config.setMessageExpiryScanPeriod(500);
+      Configuration config = createDefaultConfig()
+         .setJournalDirectory(getJournalDir())
+         .setJournalSyncNonTransactional(false)
+         .setJournalCompactMinFiles(0) // disable compact
+         .setMessageExpiryScanPeriod(500);
 
       server = createServer(true,
                             config,
@@ -678,13 +672,13 @@ public class PagingTest extends ServiceTestBase
       session.commit();
       producer.close();
 
-      for (long timeout = System.currentTimeMillis() + 60000; timeout > System.currentTimeMillis() && qEXP.getMessageCount() < 1000; )
+      for (long timeout = System.currentTimeMillis() + 60000; timeout > System.currentTimeMillis() && getMessageCount(qEXP) < 1000; )
       {
-         System.out.println("count = " + qEXP.getMessageCount());
+         System.out.println("count = " + getMessageCount(qEXP));
          Thread.sleep(100);
       }
 
-      assertEquals(1000, qEXP.getMessageCount());
+      assertEquals(1000, getMessageCount(qEXP));
 
       session.start();
 
@@ -702,11 +696,11 @@ public class PagingTest extends ServiceTestBase
 
       assertNull(consumer.receiveImmediate());
 
-      for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && queue1.getMessageCount() != 0; )
+      for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && getMessageCount(queue1) != 0; )
       {
          Thread.sleep(100);
       }
-      assertEquals(0, queue1.getMessageCount());
+      assertEquals(0, getMessageCount(queue1));
 
       consumer.close();
 
@@ -722,10 +716,6 @@ public class PagingTest extends ServiceTestBase
 
       assertNull(consumer.receiveImmediate());
 
-      System.out.println("count Exp = " + qEXP.getMessageCount());
-
-      System.out.println("msgCount = " + queue1.getMessageCount());
-
       // This is just to hold some messages as being delivered
       ClientConsumerInternal cons = (ClientConsumerInternal) session.createConsumer(ADDRESS);
 
@@ -741,12 +731,10 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalDirectory(getJournalDir());
-
-      config.setJournalSyncNonTransactional(false);
-      config.setJournalCompactMinFiles(0); // disable compact
+      Configuration config = createDefaultConfig()
+         .setJournalDirectory(getJournalDir())
+         .setJournalSyncNonTransactional(false)
+         .setJournalCompactMinFiles(0); // disable compact
 
       HornetQServer server =
          createServer(true, config,
@@ -909,7 +897,7 @@ public class PagingTest extends ServiceTestBase
 
       queue = server.locateQueue(PagingTest.ADDRESS);
 
-      assertEquals(0, queue.getMessageCount());
+      assertEquals(0, getMessageCount(queue));
 
       timeout = System.currentTimeMillis() + 10000;
       while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging())
@@ -927,9 +915,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -1007,7 +994,7 @@ public class PagingTest extends ServiceTestBase
 
       Queue queue = server.locateQueue(ADDRESS);
 
-      assertEquals(numberOfMessages, queue.getMessageCount());
+      assertEquals(numberOfMessages, getMessageCount(queue));
 
       LinkedList<Xid> xids = new LinkedList<Xid>();
 
@@ -1044,7 +1031,7 @@ public class PagingTest extends ServiceTestBase
 
       sessionCheck.close();
 
-      assertEquals(numberOfMessages, queue.getMessageCount());
+      assertEquals(numberOfMessages, getMessageCount(queue));
 
       sf.close();
       locator.close();
@@ -1071,7 +1058,7 @@ public class PagingTest extends ServiceTestBase
 
       session.start();
 
-      assertEquals(numberOfMessages, queue.getMessageCount());
+      assertEquals(numberOfMessages, getMessageCount(queue));
 
       ClientMessage msg = consumer.receive(5000);
       if (msg != null)
@@ -1125,7 +1112,7 @@ public class PagingTest extends ServiceTestBase
 
       locator.close();
 
-      assertEquals(0, queue.getMessageCount());
+      assertEquals(0, getMessageCount(queue));
 
       waitForNotPaging(queue);
    }
@@ -1135,9 +1122,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -1223,9 +1209,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -1300,7 +1285,7 @@ public class PagingTest extends ServiceTestBase
 
       Queue queue = server.locateQueue(ADDRESS);
 
-      assertEquals(numberOfMessages, queue.getMessageCount());
+      assertEquals(numberOfMessages, getMessageCount(queue));
 
       int msgReceived = 0;
       ClientSession sessionConsumer = sf.createSession(false, false, false);
@@ -1334,7 +1319,7 @@ public class PagingTest extends ServiceTestBase
 
       locator.close();
 
-      assertEquals(0, queue.getMessageCount());
+      assertEquals(0, getMessageCount(queue));
 
       long timeout = System.currentTimeMillis() + 5000;
       while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging())
@@ -1353,8 +1338,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-      config.setPersistDeliveryCountBeforeDelivery(true);
+      Configuration config = createDefaultConfig()
+         .setPersistDeliveryCountBeforeDelivery(true);
 
       config.setJournalSyncNonTransactional(false);
 
@@ -1431,7 +1416,7 @@ public class PagingTest extends ServiceTestBase
 
       Queue queue = server.locateQueue(ADDRESS);
 
-      assertEquals(numberOfMessages, queue.getMessageCount());
+      assertEquals(numberOfMessages, getMessageCount(queue));
 
       int msgReceived = 0;
       ClientSession sessionConsumer = sf.createSession(false, false, false);
@@ -1465,7 +1450,7 @@ public class PagingTest extends ServiceTestBase
 
       locator.close();
 
-      assertEquals(0, queue.getMessageCount());
+      assertEquals(0, getMessageCount(queue));
 
       long timeout = System.currentTimeMillis() + 5000;
       while (timeout > System.currentTimeMillis() && queue.getPageSubscription().getPagingStore().isPaging())
@@ -1534,7 +1519,7 @@ public class PagingTest extends ServiceTestBase
 
       queue = server.locateQueue(ADDRESS);
 
-      // assertEquals(numberOfMessages, queue.getMessageCount());
+      // assertEquals(numberOfMessages, getMessageCount(queue));
 
       msgReceived = 0;
       sessionConsumer = sf.createSession(false, false, false);
@@ -1571,9 +1556,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -1757,9 +1741,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -1917,9 +1900,8 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -2036,9 +2018,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -2048,21 +2029,19 @@ public class PagingTest extends ServiceTestBase
 
       if (divert)
       {
-         DivertConfiguration divert1 = new DivertConfiguration("dv1",
-                                                               "nm1",
-                                                               PagingTest.ADDRESS.toString(),
-                                                               PagingTest.ADDRESS.toString() + "-1",
-                                                               true,
-                                                               null,
-                                                               null);
-
-         DivertConfiguration divert2 = new DivertConfiguration("dv2",
-                                                               "nm2",
-                                                               PagingTest.ADDRESS.toString(),
-                                                               PagingTest.ADDRESS.toString() + "-2",
-                                                               true,
-                                                               null,
-                                                               null);
+         DivertConfiguration divert1 = new DivertConfiguration()
+            .setName("dv1")
+            .setRoutingName("nm1")
+            .setAddress(PagingTest.ADDRESS.toString())
+            .setForwardingAddress(PagingTest.ADDRESS.toString() + "-1")
+            .setExclusive(true);
+
+         DivertConfiguration divert2 = new DivertConfiguration()
+            .setName("dv2")
+            .setRoutingName("nm2")
+            .setAddress(PagingTest.ADDRESS.toString())
+            .setForwardingAddress(PagingTest.ADDRESS.toString() + "-2")
+            .setExclusive(true);
 
          ArrayList<DivertConfiguration> divertList = new ArrayList<DivertConfiguration>();
          divertList.add(divert1);
@@ -2102,10 +2081,9 @@ public class PagingTest extends ServiceTestBase
             {
                while (running.get())
                {
-                  // log.info("Message count = " + queue.getMessageCount() + " on queue " + queue.getName());
-                  queue.getMessagesAdded();
-                  queue.getMessageCount();
-                  // log.info("Message added = " + queue.getMessagesAdded() + " on queue " + queue.getName());
+                  // this will be overusing what some users do. flush / getCount
+                  getMessagesAdded(queue);
+                  getMessageCount(queue);
                   Thread.sleep(10);
                }
             }
@@ -2336,9 +2314,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -2504,9 +2481,8 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -3241,9 +3217,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -3928,7 +3903,7 @@ public class PagingTest extends ServiceTestBase
       {
          Queue queue = (Queue) server.getPostOffice().getBinding(new SimpleString("someQueue" + i)).getBindable();
 
-         Assert.assertEquals("Queue someQueue" + i + " was supposed to be empty", 0, queue.getMessageCount());
+         Assert.assertEquals("Queue someQueue" + i + " was supposed to be empty", 0, getMessageCount(queue));
          Assert.assertEquals("Queue someQueue" + i + " was supposed to be empty", 0, queue.getDeliveringCount());
       }
    }
@@ -4235,10 +4210,9 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
-      config.setJournalFileSize(10 * 1024 * 1024);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false)
+         .setJournalFileSize(10 * 1024 * 1024);
 
       server = createServer(true, config, 512 * 1024, 1024 * 1024, new HashMap<String, AddressSettings>());
 
@@ -4358,9 +4332,8 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -4464,9 +4437,8 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -4584,9 +4556,8 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -4684,9 +4655,8 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -4809,10 +4779,9 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-      config.setThreadPoolMaxSize(5);
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setThreadPoolMaxSize(5)
+         .setJournalSyncNonTransactional(false);
 
       Map<String, AddressSettings> settings = new HashMap<String, AddressSettings>();
       AddressSettings dla = new AddressSettings();
@@ -5054,10 +5023,9 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-      config.setMessageExpiryScanPeriod(500);
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setMessageExpiryScanPeriod(500)
+         .setJournalSyncNonTransactional(false);
 
       Map<String, AddressSettings> settings = new HashMap<String, AddressSettings>();
       AddressSettings dla = new AddressSettings();
@@ -5439,7 +5407,7 @@ public class PagingTest extends ServiceTestBase
       producer.send(message);
 
       Queue q = (Queue) server.getPostOffice().getBinding(ADDRESS).getBindable();
-      Assert.assertEquals(3, q.getMessageCount());
+      Assert.assertEquals(3, getMessageCount(q));
 
       // send a message with a dup ID that should fail b/c the address is full
       SimpleString dupID1 = new SimpleString("abcdefg");
@@ -5448,7 +5416,7 @@ public class PagingTest extends ServiceTestBase
 
       validateExceptionOnSending(producer, message);
 
-      Assert.assertEquals(3, q.getMessageCount());
+      Assert.assertEquals(3, getMessageCount(q));
 
       ClientConsumer consumer = session.createConsumer(ADDRESS);
 
@@ -5461,11 +5429,11 @@ public class PagingTest extends ServiceTestBase
       session.commit(); // to make sure it's on the server (roundtrip)
       consumer.close();
 
-      Assert.assertEquals(2, q.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(q));
 
       producer.send(message);
 
-      Assert.assertEquals(3, q.getMessageCount());
+      Assert.assertEquals(3, getMessageCount(q));
 
       consumer = session.createConsumer(ADDRESS);
 
@@ -5516,9 +5484,8 @@ public class PagingTest extends ServiceTestBase
    public void testRouteOnTopWithMultipleQueues() throws Exception
    {
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -5591,9 +5558,8 @@ public class PagingTest extends ServiceTestBase
 
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -5794,9 +5760,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -5895,9 +5860,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -5997,9 +5961,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -6082,9 +6045,8 @@ public class PagingTest extends ServiceTestBase
    @Test
    public void testNoCursors() throws Exception
    {
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -6128,9 +6090,8 @@ public class PagingTest extends ServiceTestBase
    {
       clearDataRecreateServerDirs();
 
-      Configuration config = createDefaultConfig();
-
-      config.setJournalSyncNonTransactional(false);
+      Configuration config = createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
 
       server = createServer(true,
                             config,
@@ -6245,9 +6206,8 @@ public class PagingTest extends ServiceTestBase
    @Override
    protected Configuration createDefaultConfig() throws Exception
    {
-      Configuration config = super.createDefaultConfig();
-      config.setJournalSyncNonTransactional(false);
-      return config;
+      return super.createDefaultConfig()
+         .setJournalSyncNonTransactional(false);
    }
 
    private static final class DummyOperationContext implements OperationContext

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ProducerCloseTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ProducerCloseTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ProducerCloseTest.java
index 94dd634..df3132c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ProducerCloseTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ProducerCloseTest.java
@@ -72,9 +72,9 @@ public class ProducerCloseTest extends ServiceTestBase
    public void setUp() throws Exception
    {
       super.setUp();
-      Configuration config = createDefaultConfig();
-      config.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()));
-      config.setSecurityEnabled(false);
+      Configuration config = createDefaultConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()))
+         .setSecurityEnabled(false);
       server = createServer(false, config);
       server.start();
       locator = createInVMNonHALocator();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/QueueBrowserTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/QueueBrowserTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/QueueBrowserTest.java
index b884933..0bb5248 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/QueueBrowserTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/QueueBrowserTest.java
@@ -310,7 +310,7 @@ public class QueueBrowserTest extends ServiceTestBase
       }
       // assert that all the messages are there and none have been acked
       Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
-      Assert.assertEquals(100, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+      Assert.assertEquals(100, getMessageCount(((Queue)server.getPostOffice().getBinding(QUEUE).getBindable())));
 
       session.close();
 
@@ -347,7 +347,7 @@ public class QueueBrowserTest extends ServiceTestBase
       }
       // assert that all the messages are there and none have been acked
       Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
-      Assert.assertEquals(100, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+      Assert.assertEquals(100, getMessageCount(((Queue)server.getPostOffice().getBinding(QUEUE).getBindable())));
 
       session.close();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ReceiveImmediateTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ReceiveImmediateTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ReceiveImmediateTest.java
index 7197f97..c2eaabe 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ReceiveImmediateTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/ReceiveImmediateTest.java
@@ -255,7 +255,7 @@ public class ReceiveImmediateTest extends ServiceTestBase
       Assert.assertEquals(0, ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
       int messagesOnServer = browser ? numMessages : 0;
       Assert.assertEquals(messagesOnServer,
-                          ((Queue)server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());
+                          getMessageCount(((Queue)server.getPostOffice().getBinding(QUEUE).getBindable())));
 
       consumer.close();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RedeliveryConsumerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RedeliveryConsumerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RedeliveryConsumerTest.java
index 4a3cb8c..e528151 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RedeliveryConsumerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RedeliveryConsumerTest.java
@@ -354,8 +354,8 @@ public class RedeliveryConsumerTest extends ServiceTestBase
     */
    private void setUp(final boolean persistDeliveryCountBeforeDelivery) throws Exception
    {
-      Configuration config = createDefaultConfig();
-      config.setPersistDeliveryCountBeforeDelivery(persistDeliveryCountBeforeDelivery);
+      Configuration config = createDefaultConfig()
+         .setPersistDeliveryCountBeforeDelivery(persistDeliveryCountBeforeDelivery);
 
       server = createServer(true, config);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RequestorTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RequestorTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RequestorTest.java
index b1470de..7b3e7e0 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RequestorTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/RequestorTest.java
@@ -269,8 +269,8 @@ public class RequestorTest extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration conf = createDefaultConfig();
-      conf.getAcceptorConfigurations().add(TransportConfigurationUtils.getInVMAcceptor(true));
+      Configuration conf = createDefaultConfig()
+         .addAcceptorConfiguration(TransportConfigurationUtils.getInVMAcceptor(true));
       service = createServer(false, conf);
       service.start();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionCloseTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionCloseTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionCloseTest.java
index 0433d2c..9dadd77 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionCloseTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionCloseTest.java
@@ -256,9 +256,9 @@ public class SessionCloseTest extends UnitTestCase
    {
       super.setUp();
 
-      Configuration config = createDefaultConfig();
-      config.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()));
-      config.setSecurityEnabled(false);
+      Configuration config = createDefaultConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getCanonicalName()))
+         .setSecurityEnabled(false);
       server = HornetQServers.newHornetQServer(config, false);
 
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java
index a750c4d..fb636e0 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionClosedOnRemotingConnectionFailureTest.java
@@ -111,9 +111,9 @@ public class SessionClosedOnRemotingConnectionFailureTest extends ServiceTestBas
    {
       super.setUp();
 
-      Configuration config = createDefaultConfig();
-      config.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
-      config.setSecurityEnabled(false);
+      Configuration config = createDefaultConfig()
+         .addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY))
+         .setSecurityEnabled(false);
       server = createServer(false, config);
 
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionFactoryTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionFactoryTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionFactoryTest.java
index 6ffa4fd..244037c 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionFactoryTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionFactoryTest.java
@@ -29,10 +29,10 @@ import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
 import org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory;
 import org.hornetq.core.remoting.impl.invm.InVMConnectorFactory;
 import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.tests.util.RandomUtil;
 import org.hornetq.tests.util.ServiceTestBase;
 import org.junit.Assert;
@@ -47,9 +47,10 @@ import org.junit.Test;
  */
 public class SessionFactoryTest extends ServiceTestBase
 {
-   private final DiscoveryGroupConfiguration groupConfiguration =
-      new DiscoveryGroupConfiguration(HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT, HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT,
-                                      new UDPBroadcastGroupConfiguration(getUDPDiscoveryAddress(), getUDPDiscoveryPort(), null, -1));
+   private final DiscoveryGroupConfiguration groupConfiguration = new DiscoveryGroupConfiguration()
+      .setBroadcastEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+         .setGroupAddress(getUDPDiscoveryAddress())
+         .setGroupPort(getUDPDiscoveryPort()));
 
    private HornetQServer liveService;
 
@@ -559,12 +560,7 @@ public class SessionFactoryTest extends ServiceTestBase
 
    private void startServer() throws Exception
    {
-      Configuration liveConf = createDefaultConfig();
-      liveConf.setSecurityEnabled(false);
       liveTC = new TransportConfiguration(InVMConnectorFactory.class.getName());
-      liveConf.getAcceptorConfigurations().add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));
-      liveConf.getConnectorConfigurations().put(liveTC.getName(), liveTC);
-      liveConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
 
       final long broadcastPeriod = 250;
 
@@ -572,18 +568,24 @@ public class SessionFactoryTest extends ServiceTestBase
 
       final int localBindPort = 5432;
 
-      BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration(bcGroupName,
-                                                                              broadcastPeriod,
-                                                                              Arrays.asList(liveTC.getName()),
-                                                                              new UDPBroadcastGroupConfiguration(
-                                                                                 getUDPDiscoveryAddress(),
-                                                                                 getUDPDiscoveryPort(),
-                                                                                 null,
-                                                                                 localBindPort));
+      BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration()
+         .setName(bcGroupName)
+         .setBroadcastPeriod(broadcastPeriod)
+         .setConnectorInfos(Arrays.asList(liveTC.getName()))
+         .setEndpointFactoryConfiguration(new UDPBroadcastGroupConfiguration()
+            .setGroupAddress(getUDPDiscoveryAddress())
+            .setGroupPort(getUDPDiscoveryPort())
+            .setLocalBindPort(localBindPort));
 
       List<BroadcastGroupConfiguration> bcConfigs1 = new ArrayList<BroadcastGroupConfiguration>();
       bcConfigs1.add(bcConfig1);
-      liveConf.setBroadcastGroupConfigurations(bcConfigs1);
+
+      Configuration liveConf = createDefaultConfig()
+         .setSecurityEnabled(false)
+         .addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName()))
+         .addConnectorConfiguration(liveTC.getName(), liveTC)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration())
+         .setBroadcastGroupConfigurations(bcConfigs1);
 
       liveService = createServer(false, liveConf);
       liveService.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionTest.java
index f90bc94..698d631 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SessionTest.java
@@ -41,6 +41,7 @@ import org.junit.Test;
  * This test covers the API for ClientSession although XA tests are tested separately.
  *
  * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class SessionTest extends ServiceTestBase
 {
@@ -205,6 +206,9 @@ public class SessionTest extends ServiceTestBase
       ClientProducer cp = clientSession.createProducer("a1");
       cp.send(clientSession.createMessage(false));
       cp.send(clientSession.createMessage(false));
+
+      flushQueue();
+
       QueueQuery resp = clientSession.queueQuery(new SimpleString(queueName));
       Assert.assertEquals(new SimpleString("a1"), resp.getAddress());
       Assert.assertEquals(2, resp.getConsumerCount());
@@ -213,6 +217,13 @@ public class SessionTest extends ServiceTestBase
       clientSession.close();
    }
 
+   private void flushQueue() throws Exception
+   {
+      Queue queue = server.locateQueue(SimpleString.toSimpleString(queueName));
+      assertNotNull(queue);
+      queue.flushExecutor();
+   }
+
    @Test
    public void testQueueQueryWithFilter() throws Exception
    {
@@ -221,6 +232,7 @@ public class SessionTest extends ServiceTestBase
       clientSession.createQueue("a1", queueName, "foo=bar", false);
       clientSession.createConsumer(queueName);
       clientSession.createConsumer(queueName);
+
       QueueQuery resp = clientSession.queueQuery(new SimpleString(queueName));
       Assert.assertEquals(new SimpleString("a1"), resp.getAddress());
       Assert.assertEquals(2, resp.getConsumerCount());
@@ -349,9 +361,9 @@ public class SessionTest extends ServiceTestBase
       cp.send(clientSession.createMessage(false));
       cp.send(clientSession.createMessage(false));
       Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(queueName)).getBindable();
-      Assert.assertEquals(0, q.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(q));
       clientSession.commit();
-      Assert.assertEquals(10, q.getMessageCount());
+      Assert.assertEquals(10, getMessageCount(q));
       clientSession.close();
    }
 
@@ -373,12 +385,12 @@ public class SessionTest extends ServiceTestBase
       cp.send(clientSession.createMessage(false));
       cp.send(clientSession.createMessage(false));
       Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(queueName)).getBindable();
-      Assert.assertEquals(0, q.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(q));
       clientSession.rollback();
       cp.send(clientSession.createMessage(false));
       cp.send(clientSession.createMessage(false));
       clientSession.commit();
-      Assert.assertEquals(2, q.getMessageCount());
+      Assert.assertEquals(2, getMessageCount(q));
       clientSession.close();
    }
 
@@ -403,7 +415,7 @@ public class SessionTest extends ServiceTestBase
       cp.send(clientSession.createMessage(false));
       cp.send(clientSession.createMessage(false));
       Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(queueName)).getBindable();
-      Assert.assertEquals(10, q.getMessageCount());
+      Assert.assertEquals(10, getMessageCount(q));
       ClientConsumer cc = clientSession.createConsumer(queueName);
       clientSession.start();
       ClientMessage m = cc.receive(5000);
@@ -437,7 +449,7 @@ public class SessionTest extends ServiceTestBase
       Assert.assertNotNull(m);
       m.acknowledge();
       clientSession.commit();
-      Assert.assertEquals(0, q.getMessageCount());
+      Assert.assertEquals(0, getMessageCount(q));
       clientSession.close();
       sendSession.close();
    }
@@ -463,7 +475,7 @@ public class SessionTest extends ServiceTestBase
       cp.send(clientSession.createMessage(false));
       cp.send(clientSession.createMessage(false));
       Queue q = (Queue) server.getPostOffice().getBinding(new SimpleString(queueName)).getBindable();
-      Assert.assertEquals(10, q.getMessageCount());
+      Assert.assertEquals(10, getMessageCount(q));
       ClientConsumer cc = clientSession.createConsumer(queueName);
       clientSession.start();
       ClientMessage m = cc.receive(5000);
@@ -497,8 +509,17 @@ public class SessionTest extends ServiceTestBase
       Assert.assertNotNull(m);
       m.acknowledge();
       clientSession.rollback();
-      Assert.assertEquals(10, q.getMessageCount());
+      Assert.assertEquals(10, getMessageCount(q));
       clientSession.close();
       sendSession.close();
    }
+
+   @Test
+   public void testGetNodeId() throws Exception
+   {
+      cf = createSessionFactory(locator);
+      ClientSession clientSession = addClientSession(cf.createSession(false, true, true));
+      String nodeId = ((ClientSessionInternal) clientSession).getNodeId();
+      assertNotNull(nodeId);
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SlowConsumerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SlowConsumerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SlowConsumerTest.java
new file mode 100644
index 0000000..ce6504c
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/SlowConsumerTest.java
@@ -0,0 +1,361 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.client;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.hornetq.api.config.HornetQDefaultConfiguration;
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.HornetQExceptionType;
+import org.hornetq.api.core.HornetQObjectClosedException;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.client.ClientConsumer;
+import org.hornetq.api.core.client.ClientMessage;
+import org.hornetq.api.core.client.ClientProducer;
+import org.hornetq.api.core.client.ClientSession;
+import org.hornetq.api.core.client.ClientSessionFactory;
+import org.hornetq.api.core.client.MessageHandler;
+import org.hornetq.api.core.client.ServerLocator;
+import org.hornetq.api.core.management.CoreNotificationType;
+import org.hornetq.api.core.management.ManagementHelper;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.settings.impl.AddressSettings;
+import org.hornetq.core.settings.impl.SlowConsumerPolicy;
+import org.hornetq.tests.util.RandomUtil;
+import org.hornetq.tests.util.ServiceTestBase;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * @author Justin Bertram
+ */
+@RunWith(value = Parameterized.class)
+public class SlowConsumerTest extends ServiceTestBase
+{
+   private boolean isNetty = false;
+
+   // this will ensure that all tests in this class are run twice,
+   // once with "true" passed to the class' constructor and once with "false"
+   @Parameterized.Parameters(name = "isNetty={0}")
+   public static Collection getParameters()
+   {
+      return Arrays.asList(new Object[][]{
+         {true},
+         {false}
+      });
+   }
+
+   public SlowConsumerTest(boolean isNetty)
+   {
+      this.isNetty = isNetty;
+   }
+
+   private HornetQServer server;
+
+   private final SimpleString QUEUE = new SimpleString("ConsumerTestQueue");
+
+   private ServerLocator locator;
+
+   @Before
+   @Override
+   public void setUp() throws Exception
+   {
+      super.setUp();
+
+      server = createServer(false, isNetty);
+
+      AddressSettings addressSettings = new AddressSettings();
+      addressSettings.setSlowConsumerCheckPeriod(2);
+      addressSettings.setSlowConsumerThreshold(10);
+      addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.KILL);
+
+      server.start();
+
+      server.getAddressSettingsRepository().addMatch(QUEUE.toString(), addressSettings);
+
+      locator = createFactory(isNetty);
+   }
+
+   @Test
+   public void testSlowConsumerKilled() throws Exception
+   {
+      ClientSessionFactory sf = createSessionFactory(locator);
+
+      ClientSession session = addClientSession(sf.createSession(false, true, true, false));
+
+      session.createQueue(QUEUE, QUEUE, null, false);
+
+      ClientProducer producer = addClientProducer(session.createProducer(QUEUE));
+
+      final int numMessages = 25;
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         producer.send(createTextMessage(session, "m" + i));
+      }
+
+      ClientConsumer consumer = addClientConsumer(session.createConsumer(QUEUE));
+      session.start();
+
+      Thread.sleep(3000);
+
+      try
+      {
+         consumer.receiveImmediate();
+         fail();
+      }
+      catch (HornetQObjectClosedException e)
+      {
+         assertEquals(e.getType(), HornetQExceptionType.OBJECT_CLOSED);
+      }
+   }
+
+   @Test
+   public void testSlowConsumerNotification() throws Exception
+   {
+
+      ClientSessionFactory sf = createSessionFactory(locator);
+
+      ClientSession session = addClientSession(sf.createSession(false, true, true, false));
+
+      session.createQueue(QUEUE, QUEUE, null, false);
+
+      AddressSettings addressSettings = new AddressSettings();
+      addressSettings.setSlowConsumerCheckPeriod(2);
+      addressSettings.setSlowConsumerThreshold(10);
+      addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.NOTIFY);
+
+      server.getAddressSettingsRepository().removeMatch(QUEUE.toString());
+      server.getAddressSettingsRepository().addMatch(QUEUE.toString(), addressSettings);
+
+      ClientProducer producer = addClientProducer(session.createProducer(QUEUE));
+
+      final int numMessages = 25;
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         producer.send(createTextMessage(session, "m" + i));
+      }
+
+      SimpleString notifQueue = RandomUtil.randomSimpleString();
+
+      session.createQueue(HornetQDefaultConfiguration.getDefaultManagementNotificationAddress(), notifQueue, null, false);
+
+      ClientConsumer notifConsumer = session.createConsumer(notifQueue.toString(), ManagementHelper.HDR_NOTIFICATION_TYPE + "='" + CoreNotificationType.CONSUMER_SLOW + "'");
+
+      final CountDownLatch notifLatch = new CountDownLatch(1);
+
+      notifConsumer.setMessageHandler(new MessageHandler()
+      {
+         @Override
+         public void onMessage(ClientMessage message)
+         {
+            assertEquals(CoreNotificationType.CONSUMER_SLOW.toString(), message.getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString());
+            assertEquals(QUEUE.toString(), message.getObjectProperty(ManagementHelper.HDR_ADDRESS).toString());
+            assertEquals(Integer.valueOf(1), message.getIntProperty(ManagementHelper.HDR_CONSUMER_COUNT));
+            if (isNetty)
+            {
+               assertTrue(message.getSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS).toString().startsWith("/127.0.0.1"));
+            }
+            else
+            {
+               assertEquals(SimpleString.toSimpleString("invm:0"), message.getSimpleStringProperty(ManagementHelper.HDR_REMOTE_ADDRESS));
+            }
+            assertNotNull(message.getSimpleStringProperty(ManagementHelper.HDR_CONNECTION_NAME));
+            assertNotNull(message.getSimpleStringProperty(ManagementHelper.HDR_CONSUMER_NAME));
+            assertNotNull(message.getSimpleStringProperty(ManagementHelper.HDR_SESSION_NAME));
+            try
+            {
+               message.acknowledge();
+            }
+            catch (HornetQException e)
+            {
+               e.printStackTrace();
+            }
+            notifLatch.countDown();
+         }
+      });
+
+      ClientConsumer consumer = addClientConsumer(session.createConsumer(QUEUE));
+      session.start();
+
+      assertTrue(notifLatch.await(3, TimeUnit.SECONDS));
+   }
+
+   @Test
+   public void testSlowConsumerSpared() throws Exception
+   {
+      ClientSessionFactory sf = createSessionFactory(locator);
+
+      ClientSession session = addClientSession(sf.createSession(true, true));
+
+      session.createQueue(QUEUE, QUEUE, null, false);
+
+      ClientProducer producer = addClientProducer(session.createProducer(QUEUE));
+
+      final int numMessages = 5;
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         producer.send(createTextMessage(session, "m" + i));
+      }
+
+      ClientConsumer consumer = addClientConsumer(session.createConsumer(QUEUE));
+      session.start();
+
+      Thread.sleep(3000);
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         assertNotNull(consumer.receive(500));
+      }
+   }
+
+   @Test
+   public void testFastThenSlowConsumerSpared() throws Exception
+   {
+      locator.setAckBatchSize(0);
+
+      ClientSessionFactory sf = createSessionFactory(locator);
+
+      ClientSession session = addClientSession(sf.createSession(true, true));
+
+      final ClientSession producerSession = addClientSession(sf.createSession(true, true));
+
+      session.createQueue(QUEUE, QUEUE, null, false);
+
+      final ClientProducer producer = addClientProducer(producerSession.createProducer(QUEUE));
+
+      final AtomicLong messagesProduced = new AtomicLong(0);
+
+      Thread t = new Thread(new Runnable()
+      {
+         @Override
+         public void run()
+         {
+            long start = System.currentTimeMillis();
+            ClientMessage m = createTextMessage(producerSession, "m", true);
+
+            // send messages as fast as possible for 3 seconds
+            while (System.currentTimeMillis() < (start + 3000))
+            {
+               try
+               {
+                  producer.send(m);
+                  messagesProduced.incrementAndGet();
+               }
+               catch (HornetQException e)
+               {
+                  e.printStackTrace();
+                  return;
+               }
+            }
+
+            start = System.currentTimeMillis();
+
+            // send 1 msg/second for 10 seconds
+            while (System.currentTimeMillis() < (start + 10000))
+            {
+               try
+               {
+                  producer.send(m);
+                  messagesProduced.incrementAndGet();
+                  Thread.sleep(1000);
+               }
+               catch (Exception e)
+               {
+                  e.printStackTrace();
+                  return;
+               }
+            }
+         }
+      });
+
+      t.start();
+
+      ClientConsumer consumer = addClientConsumer(session.createConsumer(QUEUE));
+      session.start();
+
+      ClientMessage m = null;
+      long messagesConsumed = 0;
+
+      do
+      {
+         m = consumer.receive(1500);
+         if (m != null)
+         {
+            m.acknowledge();
+            messagesConsumed++;
+         }
+      }
+      while (m != null);
+
+      assertEquals(messagesProduced.longValue(), messagesConsumed);
+   }
+
+   @Test
+   public void testSlowWildcardConsumer() throws Exception
+   {
+      SimpleString addressAB = new SimpleString("a.b");
+      SimpleString addressAC = new SimpleString("a.c");
+      SimpleString address = new SimpleString("a.*");
+      SimpleString queueName1 = new SimpleString("Q1");
+      SimpleString queueName2 = new SimpleString("Q2");
+      SimpleString queueName = new SimpleString("Q");
+
+      AddressSettings addressSettings = new AddressSettings();
+      addressSettings.setSlowConsumerCheckPeriod(2);
+      addressSettings.setSlowConsumerThreshold(10);
+      addressSettings.setSlowConsumerPolicy(SlowConsumerPolicy.KILL);
+
+      server.getAddressSettingsRepository().addMatch(address.toString(), addressSettings);
+
+      ClientSessionFactory sf = createSessionFactory(locator);
+
+      ClientSession session = addClientSession(sf.createSession(false, true, true, false));
+      session.createQueue(addressAB, queueName1, null, false);
+      session.createQueue(addressAC, queueName2, null, false);
+      session.createQueue(address, queueName, null, false);
+      ClientProducer producer = session.createProducer(addressAB);
+      ClientProducer producer2 = session.createProducer(addressAC);
+
+      final int numMessages = 20;
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         producer.send(createTextMessage(session, "m1" + i));
+         producer2.send(createTextMessage(session, "m2" + i));
+      }
+
+      ClientConsumer consumer = addClientConsumer(session.createConsumer(queueName));
+      session.start();
+
+      Thread.sleep(3000);
+
+      try
+      {
+         consumer.receiveImmediate();
+         fail();
+      }
+      catch (HornetQObjectClosedException e)
+      {
+         assertEquals(e.getType(), HornetQExceptionType.OBJECT_CLOSED);
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TemporaryQueueTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TemporaryQueueTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TemporaryQueueTest.java
index 9722371..ebb6491 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TemporaryQueueTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TemporaryQueueTest.java
@@ -551,6 +551,13 @@ public class TemporaryQueueTest extends SingleServerTestBase
                         serverCloseLatch.await(2 * RemotingServiceImpl.CONNECTION_TTL_CHECK_INTERVAL +
                                                   2 *
                                                      TemporaryQueueTest.CONNECTION_TTL, TimeUnit.MILLISECONDS));
+
+      // The next getCount will be asynchronously done at the end of failure. We will wait some time until it has reached there.
+      for (long timeout = System.currentTimeMillis() + 5000; timeout > System.currentTimeMillis() && server.getConnectionCount() > 0;)
+      {
+         Thread.sleep(1);
+      }
+
       Assert.assertEquals(0, server.getConnectionCount());
 
       session.close();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TransactionalSendTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TransactionalSendTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TransactionalSendTest.java
index 3761b0c..8ccb233 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TransactionalSendTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/TransactionalSendTest.java
@@ -62,17 +62,17 @@ public class TransactionalSendTest extends ServiceTestBase
          cp.send(session.createMessage(false));
       }
       Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable();
-      Assert.assertEquals(q.getMessageCount(), 0);
+      Assert.assertEquals(0, getMessageCount(q));
       session.commit();
-      Assert.assertEquals(q.getMessageCount(), numMessages);
+      Assert.assertEquals(getMessageCount(q), numMessages);
       // now send some more
       for (int i = 0; i < numMessages; i++)
       {
          cp.send(session.createMessage(false));
       }
-      Assert.assertEquals(q.getMessageCount(), numMessages);
+      Assert.assertEquals(numMessages, getMessageCount(q));
       session.commit();
-      Assert.assertEquals(q.getMessageCount(), numMessages * 2);
+      Assert.assertEquals(numMessages * 2, getMessageCount(q));
       session.close();
    }
 
@@ -91,17 +91,17 @@ public class TransactionalSendTest extends ServiceTestBase
          cp.send(session.createMessage(false));
       }
       Queue q = (Queue) server.getPostOffice().getBinding(queueA).getBindable();
-      Assert.assertEquals(q.getMessageCount(), 0);
+      Assert.assertEquals(getMessageCount(q), 0);
       session.rollback();
-      Assert.assertEquals(q.getMessageCount(), 0);
+      Assert.assertEquals(getMessageCount(q), 0);
       // now send some more
       for (int i = 0; i < numMessages; i++)
       {
          cp.send(session.createMessage(false));
       }
-      Assert.assertEquals(q.getMessageCount(), 0);
+      Assert.assertEquals(0, getMessageCount(q));
       session.commit();
-      Assert.assertEquals(q.getMessageCount(), numMessages);
+      Assert.assertEquals(numMessages, getMessageCount(q));
       session.close();
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/WildCardRoutingTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/WildCardRoutingTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/WildCardRoutingTest.java
index 8df2c19..726f78a 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/WildCardRoutingTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/client/WildCardRoutingTest.java
@@ -783,13 +783,14 @@ public class WildCardRoutingTest extends UnitTestCase
    public void setUp() throws Exception
    {
       super.setUp();
-
-      Configuration configuration = createDefaultConfig();
-      configuration.setWildcardRoutingEnabled(true);
-      configuration.setSecurityEnabled(false);
-      configuration.setTransactionTimeoutScanPeriod(500);
       TransportConfiguration transportConfig = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY);
-      configuration.getAcceptorConfigurations().add(transportConfig);
+
+      Configuration configuration = createDefaultConfig()
+         .setWildcardRoutingEnabled(true)
+         .setSecurityEnabled(false)
+         .setTransactionTimeoutScanPeriod(500)
+         .addAcceptorConfiguration(transportConfig);
+
       server = HornetQServers.newHornetQServer(configuration, false);
       // start the server
       server.start();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/ClientTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/ClientTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/ClientTestBase.java
index 87932a3..700adcf 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/ClientTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/ClientTestBase.java
@@ -37,8 +37,8 @@ public abstract class ClientTestBase extends ServiceTestBase
    {
       super.setUp();
 
-      Configuration config = createDefaultConfig(true);
-      config.setSecurityEnabled(false);
+      Configuration config = createDefaultConfig(true)
+         .setSecurityEnabled(false);
       server = createServer(false, config);
       server.start();
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient.java
index 5336867..753fc07 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient.java
@@ -26,7 +26,7 @@ import org.hornetq.jms.client.HornetQTextMessage;
 import org.hornetq.tests.integration.IntegrationTestLogger;
 
 /**
- * Code to be run in an external VM, via main().
+ * Code to be run in an external VM, via main()
  *
  * @author <a href="mailto:ovidiu@feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient2.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient2.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient2.java
index f76d033..23715c7 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient2.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/CrashClient2.java
@@ -26,7 +26,7 @@ import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory;
 import org.hornetq.tests.integration.IntegrationTestLogger;
 
 /**
- * Code to be run in an external VM, via main().
+ * Code to be run in an external VM, via main()
  *
  * @author <a href="mailto:ovidiu@feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/GracefulClient.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/GracefulClient.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/GracefulClient.java
index 5169201..2410187 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/GracefulClient.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/clientcrash/GracefulClient.java
@@ -25,7 +25,7 @@ import org.hornetq.jms.client.HornetQTextMessage;
 import org.hornetq.tests.integration.IntegrationTestLogger;
 
 /**
- * Code to be run in an external VM, via main().
+ * Code to be run in an external VM, via main()
  *
  * @author <a href="mailto:ovidiu@feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ClusterControllerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ClusterControllerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ClusterControllerTest.java
new file mode 100644
index 0000000..9f8fad7
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/ClusterControllerTest.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.tests.integration.cluster;
+
+import org.hornetq.api.core.HornetQClusterSecurityException;
+import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
+import org.hornetq.core.client.impl.ServerLocatorImpl;
+import org.hornetq.core.server.cluster.ClusterControl;
+import org.hornetq.core.server.cluster.ClusterController;
+import org.hornetq.core.server.cluster.HornetQServerSideProtocolManagerFactory;
+import org.hornetq.tests.integration.cluster.distribution.ClusterTestBase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+
+public class ClusterControllerTest extends ClusterTestBase
+{
+   @Override
+   @Before
+   public void setUp() throws Exception
+   {
+      super.setUp();
+
+      setupServer(0, isFileStorage(), true);
+      setupServer(1, isFileStorage(), true);
+
+      getServer(0).getConfiguration().getAcceptorConfigurations().add(createTransportConfiguration(false, true,
+            generateParams(0, false)));
+      getServer(1).getConfiguration().getAcceptorConfigurations().add(createTransportConfiguration(false, true,
+            generateParams(1, false)));
+
+      getServer(0).getConfiguration().setSecurityEnabled(true);
+      getServer(1).getConfiguration().setSecurityEnabled(true);
+
+      getServer(1).getConfiguration().setClusterPassword("something different");
+
+      setupClusterConnection("cluster0", "queues", false, 1, true, 0);
+      setupClusterConnection("cluster0", "queues", false, 1, true, 1);
+
+      startServers(0);
+      startServers(1);
+   }
+
+   @Override
+   @After
+   public void tearDown() throws Exception
+   {
+      stopServers();
+
+      super.tearDown();
+   }
+
+   @Test
+   public void controlWithDifferentConnector() throws Exception
+   {
+      try (ServerLocatorImpl locator = (ServerLocatorImpl) HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(INVM_CONNECTOR_FACTORY)))
+      {
+         locator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
+         ClusterController controller = new ClusterController(getServer(0), getServer(0).getScheduledPool());
+         ClusterControl clusterControl = controller.connectToNodeInCluster((ClientSessionFactoryInternal) locator.createSessionFactory());
+         clusterControl.authorize();
+      }
+   }
+
+   @Test
+   public void controlWithDifferentPassword() throws Exception
+   {
+      try (ServerLocatorImpl locator = (ServerLocatorImpl) HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(INVM_CONNECTOR_FACTORY)))
+      {
+         locator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
+         ClusterController controller = new ClusterController(getServer(1), getServer(1).getScheduledPool());
+         ClusterControl clusterControl = controller.connectToNodeInCluster((ClientSessionFactoryInternal) locator.createSessionFactory());
+         try
+         {
+            clusterControl.authorize();
+            fail("should throw HornetQClusterSecurityException");
+         }
+         catch (Exception e)
+         {
+            assertTrue("should throw HornetQClusterSecurityException", e instanceof HornetQClusterSecurityException);
+         }
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeFailoverTest.java
index f2db8ee..019f8b2 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeFailoverTest.java
@@ -57,8 +57,12 @@ public class BridgeFailoverTest extends MultiServerTestBase
 
       for (HornetQServer server : servers)
       {
-         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration(ORIGINAL_QUEUE, ORIGINAL_QUEUE, null, true));
-         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration(TARGET_QUEUE, TARGET_QUEUE, null, true));
+         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration()
+            .setAddress(ORIGINAL_QUEUE)
+            .setName(ORIGINAL_QUEUE));
+         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration()
+            .setAddress(TARGET_QUEUE)
+            .setName(TARGET_QUEUE));
       }
 
       startServers();
@@ -132,8 +136,12 @@ public class BridgeFailoverTest extends MultiServerTestBase
 
       for (HornetQServer server : servers)
       {
-         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration(ORIGINAL_QUEUE, ORIGINAL_QUEUE, null, true));
-         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration(TARGET_QUEUE, TARGET_QUEUE, null, true));
+         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration()
+            .setAddress(ORIGINAL_QUEUE)
+            .setName(ORIGINAL_QUEUE));
+         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration()
+            .setAddress(TARGET_QUEUE)
+            .setName(TARGET_QUEUE));
       }
 
       startServers();
@@ -245,8 +253,12 @@ public class BridgeFailoverTest extends MultiServerTestBase
 
       for (HornetQServer server : servers)
       {
-         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration(ORIGINAL_QUEUE, ORIGINAL_QUEUE, null, true));
-         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration(TARGET_QUEUE, TARGET_QUEUE, null, true));
+         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration()
+            .setAddress(ORIGINAL_QUEUE)
+            .setName(ORIGINAL_QUEUE));
+         server.getConfiguration().getQueueConfigurations().add(new CoreQueueConfiguration()
+            .setAddress(TARGET_QUEUE)
+            .setName(TARGET_QUEUE));
       }
 
       startBackups(0, 1, 3, 4);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeReconnectTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeReconnectTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeReconnectTest.java
index 2c9ea28..ccb1708 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeReconnectTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeReconnectTest.java
@@ -17,7 +17,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.HornetQExceptionType;
 import org.hornetq.api.core.HornetQNotConnectedException;
@@ -158,12 +157,16 @@ public class BridgeReconnectTest extends BridgeTestBase
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
       server2.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server1.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server0.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -209,12 +212,16 @@ public class BridgeReconnectTest extends BridgeTestBase
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -270,13 +277,17 @@ public class BridgeReconnectTest extends BridgeTestBase
 
    private BridgeConfiguration createBridgeConfig()
    {
-      return new BridgeConfiguration(bridgeName, queueName, forwardAddress, null, null,
-                                     HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                     HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                     HornetQClient.DEFAULT_CONNECTION_TTL, retryInterval,
-                                     HornetQClient.DEFAULT_MAX_RETRY_INTERVAL, retryIntervalMultiplier,
-                                     -1, reconnectAttempts, 0, true, confirmationWindowSize, staticConnectors, false,
-                                     HornetQDefaultConfiguration.getDefaultClusterUser(), CLUSTER_PASSWORD);
+      return new BridgeConfiguration()
+         .setName(bridgeName)
+         .setQueueName(queueName)
+         .setForwardingAddress(forwardAddress)
+         .setRetryInterval(retryInterval)
+         .setRetryIntervalMultiplier(retryIntervalMultiplier)
+         .setReconnectAttempts(reconnectAttempts)
+         .setReconnectAttemptsOnSameNode(0)
+         .setConfirmationWindowSize(confirmationWindowSize)
+         .setStaticConnectors(staticConnectors)
+         .setPassword(CLUSTER_PASSWORD);
    }
 
    // Fail bridge and attempt failover a few times before succeeding
@@ -301,12 +312,16 @@ public class BridgeReconnectTest extends BridgeTestBase
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -370,12 +385,16 @@ public class BridgeReconnectTest extends BridgeTestBase
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -457,37 +476,33 @@ public class BridgeReconnectTest extends BridgeTestBase
       reconnectAttempts = -1;
       final long clientFailureCheckPeriod = 1000;
 
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName,
-                                                                        queueName,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        clientFailureCheckPeriod,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        retryInterval,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        retryIntervalMultiplier,
-                                                                        -1,
-                                                                        reconnectAttempts,
-                                                                        0,
-                                                                        true,
-                                                                        confirmationWindowSize,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        CLUSTER_PASSWORD);
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName(bridgeName)
+         .setQueueName(queueName)
+         .setForwardingAddress(forwardAddress)
+         .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+         .setRetryInterval(retryInterval)
+         .setRetryIntervalMultiplier(retryIntervalMultiplier)
+         .setReconnectAttempts(reconnectAttempts)
+         .setReconnectAttemptsOnSameNode(0)
+         .setConfirmationWindowSize(confirmationWindowSize)
+         .setStaticConnectors(staticConnectors)
+         .setPassword(CLUSTER_PASSWORD);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -594,12 +609,16 @@ public class BridgeReconnectTest extends BridgeTestBase
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -707,12 +726,16 @@ public class BridgeReconnectTest extends BridgeTestBase
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);


[23/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/JournalStorageManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/JournalStorageManager.java b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/JournalStorageManager.java
index 1a64e6e..99573f8 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/JournalStorageManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/JournalStorageManager.java
@@ -22,10 +22,10 @@ import java.security.InvalidParameterException;
 import java.security.MessageDigest;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
@@ -45,6 +45,7 @@ import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQBuffers;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.HornetQIllegalStateException;
+import org.hornetq.api.core.HornetQInternalErrorException;
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
@@ -106,6 +107,7 @@ import org.hornetq.core.transaction.TransactionOperationAbstract;
 import org.hornetq.core.transaction.TransactionPropertyIndexes;
 import org.hornetq.core.transaction.impl.TransactionImpl;
 import org.hornetq.utils.Base64;
+import org.hornetq.utils.ByteUtil;
 import org.hornetq.utils.DataConstants;
 import org.hornetq.utils.ExecutorFactory;
 import org.hornetq.utils.HornetQThreadFactory;
@@ -350,7 +352,7 @@ public class JournalStorageManager implements StorageManager
     * To achieve (2), instead of writing directly to instances of {@link JournalImpl}, we write to
     * instances of {@link ReplicatedJournal}.
     * <p/>
-    * At the backup-side replication is handled by {@link ReplicationEndpoint}.
+    * At the backup-side replication is handled by {@link org.hornetq.core.replication.ReplicationEndpoint}.
     *
     * @param replicationManager
     * @param pagingManager
@@ -380,6 +382,10 @@ public class JournalStorageManager implements StorageManager
       JournalFile[] messageFiles = null;
       JournalFile[] bindingsFiles = null;
 
+      // We get a picture of the current sitaution on the large messages
+      // and we send the current messages while more state is coming
+      Map<Long, Pair<String, Long>> pendingLargeMessages = null;
+
       try
       {
          Map<SimpleString, Collection<Integer>> pageFilesToSync;
@@ -408,7 +414,7 @@ public class JournalStorageManager implements StorageManager
                   bindingsFiles =
                      prepareJournalForCopy(originalBindingsJournal, JournalContent.BINDINGS, nodeID, autoFailBack);
                   pageFilesToSync = getPageInformationForSync(pagingManager);
-                  getLargeMessageInformation();
+                  pendingLargeMessages = recoverPendingLargeMessages();
                }
                finally
                {
@@ -428,9 +434,11 @@ public class JournalStorageManager implements StorageManager
             storageManagerLock.writeLock().unlock();
          }
 
+         // it will send a list of IDs that we are allocating
+         replicator.sendLargeMessageIdListMessage(pendingLargeMessages);
          sendJournalFile(messageFiles, JournalContent.MESSAGES);
          sendJournalFile(bindingsFiles, JournalContent.BINDINGS);
-         sendLargeMessageFiles();
+         sendLargeMessageFiles(pendingLargeMessages);
          sendPagesToBackup(pageFilesToSync, pagingManager);
 
          storageManagerLock.writeLock().lock();
@@ -574,23 +582,18 @@ public class JournalStorageManager implements StorageManager
       return info;
    }
 
-   private void sendLargeMessageFiles() throws Exception
+   private void sendLargeMessageFiles(final Map<Long, Pair<String, Long>> pendingLargeMessages) throws Exception
    {
-      while (true)
+      Iterator<Entry<Long, Pair<String, Long>>> iter = pendingLargeMessages.entrySet().iterator();
+      while (started && iter.hasNext())
       {
-         Map.Entry<Long, Pair<String, Long>> entry = replicator.getNextLargeMessageToSync();
-         if (entry == null)
-         {
-            break;
-         }
+         Map.Entry<Long, Pair<String, Long>> entry = iter.next();
          String fileName = entry.getValue().getA();
          final long id = entry.getKey();
          long size = entry.getValue().getB();
          SequentialFile seqFile = largeMessagesFactory.createSequentialFile(fileName, 1);
          if (!seqFile.exists())
             continue;
-         if (!started)
-            return;
          replicator.syncLargeMessageFile(seqFile, size, id);
       }
    }
@@ -610,8 +613,9 @@ public class JournalStorageManager implements StorageManager
     *
     * @throws Exception
     */
-   private void getLargeMessageInformation() throws Exception
+   private Map<Long, Pair<String, Long>> recoverPendingLargeMessages() throws Exception
    {
+
       Map<Long, Pair<String, Long>> largeMessages = new HashMap<Long, Pair<String, Long>>();
       // only send durable messages... // listFiles append a "." to anything...
       List<String> filenames = largeMessagesFactory.listFiles("msg");
@@ -620,12 +624,16 @@ public class JournalStorageManager implements StorageManager
       for (String filename : filenames)
       {
          Long id = getLargeMessageIdFromFilename(filename);
-         idList.add(id);
-         SequentialFile seqFile = largeMessagesFactory.createSequentialFile(filename, 1);
-         long size = seqFile.size();
-         largeMessages.put(id, new Pair<String, Long>(filename, size));
+         if (!largeMessagesToDelete.contains(id))
+         {
+            idList.add(id);
+            SequentialFile seqFile = largeMessagesFactory.createSequentialFile(filename, 1);
+            long size = seqFile.size();
+            largeMessages.put(id, new Pair<String, Long>(filename, size));
+         }
       }
-      replicator.sendLargeMessageIdListMessage(largeMessages);
+
+      return largeMessages;
    }
 
    /**
@@ -763,12 +771,12 @@ public class JournalStorageManager implements StorageManager
       getContext().executeOnCompletion(run);
    }
 
-   public long generateUniqueID()
+   public long generateID()
    {
       return idGenerator.generateID();
    }
 
-   public long getCurrentUniqueID()
+   public long getCurrentID()
    {
       return idGenerator.getCurrentID();
    }
@@ -838,7 +846,7 @@ public class JournalStorageManager implements StorageManager
       readLock();
       try
       {
-         long recordID = generateUniqueID();
+         long recordID = generateID();
 
          messageJournal.appendAddRecord(recordID, JournalRecordIds.ADD_LARGE_MESSAGE_PENDING,
                                         new PendingLargeMessageEncoding(messageID),
@@ -1081,7 +1089,7 @@ public class JournalStorageManager implements StorageManager
       readLock();
       try
       {
-         pageTransaction.setRecordID(generateUniqueID());
+         pageTransaction.setRecordID(generateID());
          messageJournal.appendAddRecordTransactional(txID, pageTransaction.getRecordID(),
                                                      JournalRecordIds.PAGE_TRANSACTION, pageTransaction);
       }
@@ -1207,7 +1215,7 @@ public class JournalStorageManager implements StorageManager
       readLock();
       try
       {
-         long id = generateUniqueID();
+         long id = generateID();
 
          messageJournal.appendAddRecord(id,
                                         JournalRecordIds.HEURISTIC_COMPLETION,
@@ -2392,6 +2400,21 @@ public class JournalStorageManager implements StorageManager
    // This should be accessed from this package only
    void deleteLargeMessageFile(final LargeServerMessage largeServerMessage) throws HornetQException
    {
+      if (largeServerMessage.getPendingRecordID() < 0)
+      {
+         try
+         {
+            // The delete file happens asynchronously
+            // And the client won't be waiting for the actual file to be deleted.
+            // We set a temporary record (short lived) on the journal
+            // to avoid a situation where the server is restarted and pending large message stays on forever
+            largeServerMessage.setPendingRecordID(storePendingLargeMessage(largeServerMessage.getMessageID()));
+         }
+         catch (Exception e)
+         {
+            throw new HornetQInternalErrorException(e.getMessage(), e);
+         }
+      }
       final SequentialFile file = largeServerMessage.getFile();
       if (file == null)
       {
@@ -3434,7 +3457,7 @@ public class JournalStorageManager implements StorageManager
          // SimpleString simpleStr = new SimpleString(duplID);
          // return "DuplicateIDEncoding [address=" + address + ", duplID=" + simpleStr + "]";
 
-         return "DuplicateIDEncoding [address=" + address + ", duplID=" + Arrays.toString(duplID) + "]";
+         return "DuplicateIDEncoding [address=" + address + ", duplID=" + ByteUtil.bytesToHex(duplID, 2) + "]";
       }
 
    }
@@ -3443,7 +3466,7 @@ public class JournalStorageManager implements StorageManager
     * This is only used when loading a transaction.
     * <p/>
     * it might be possible to merge the functionality of this class with
-    * {@link PagingStoreImpl.FinishPageMessageOperation}
+    * {@link org.hornetq.core.persistence.impl.journal.JournalStorageManager.FinishPageMessageOperation}
     */
    // TODO: merge this class with the one on the PagingStoreImpl
    private static class FinishPageMessageOperation extends TransactionOperationAbstract implements TransactionOperation

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/LargeServerMessageInSync.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/LargeServerMessageInSync.java b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/LargeServerMessageInSync.java
index 0c494d2..5e6bfbd 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/LargeServerMessageInSync.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/journal/LargeServerMessageInSync.java
@@ -18,6 +18,7 @@ package org.hornetq.core.persistence.impl.journal;
 import java.nio.ByteBuffer;
 
 import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.Message;
 import org.hornetq.core.journal.SequentialFile;
 import org.hornetq.core.persistence.StorageManager;
 import org.hornetq.core.persistence.StorageManager.LargeMessageExtension;
@@ -77,15 +78,17 @@ public final class LargeServerMessageInSync implements ReplicatedLargeMessage
    }
 
    @Override
-   public void setDurable(boolean durable)
+   public Message setDurable(boolean durable)
    {
       mainLM.setDurable(durable);
+      return mainLM;
    }
 
    @Override
-   public synchronized void setMessageID(long id)
+   public synchronized Message setMessageID(long id)
    {
       mainLM.setMessageID(id);
+      return mainLM;
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/nullpm/NullStorageManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/nullpm/NullStorageManager.java b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/nullpm/NullStorageManager.java
index b29ea13..37866e9 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/nullpm/NullStorageManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/persistence/impl/nullpm/NullStorageManager.java
@@ -232,7 +232,7 @@ public class NullStorageManager implements StorageManager
    @Override
    public long storeHeuristicCompletion(final Xid xid, final boolean isCommit) throws Exception
    {
-      return generateUniqueID();
+      return generateID();
    }
 
    @Override
@@ -264,7 +264,7 @@ public class NullStorageManager implements StorageManager
    }
 
    @Override
-   public long generateUniqueID()
+   public long generateID()
    {
       long id = idSequence.getAndIncrement();
 
@@ -272,7 +272,7 @@ public class NullStorageManager implements StorageManager
    }
 
    @Override
-   public long getCurrentUniqueID()
+   public long getCurrentID()
    {
       return idSequence.get();
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/postoffice/QueueInfo.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/postoffice/QueueInfo.java b/hornetq-server/src/main/java/org/hornetq/core/postoffice/QueueInfo.java
index 05bd090..1e15014 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/postoffice/QueueInfo.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/postoffice/QueueInfo.java
@@ -130,6 +130,27 @@ public class QueueInfo implements Serializable
       numberOfConsumers--;
    }
 
+   public boolean matchesAddress(SimpleString address)
+   {
+      boolean containsAddress = false;
+
+      if (address != null)
+      {
+         SimpleString[] split = address.split(',');
+         for (SimpleString addressPart : split)
+         {
+            containsAddress = address.startsWith(addressPart);
+
+            if (containsAddress)
+            {
+               break;
+            }
+         }
+      }
+
+      return containsAddress;
+   }
+
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
@@ -153,6 +174,4 @@ public class QueueInfo implements Serializable
              distance +
              "]";
    }
-
-
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/BindingsImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/BindingsImpl.java b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/BindingsImpl.java
index c037ff5..f545345 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/BindingsImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/BindingsImpl.java
@@ -34,6 +34,7 @@ import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.Queue;
 import org.hornetq.core.server.RoutingContext;
 import org.hornetq.core.server.ServerMessage;
+import org.hornetq.core.server.cluster.RemoteQueueBinding;
 import org.hornetq.core.server.group.GroupingHandler;
 import org.hornetq.core.server.group.impl.Proposal;
 import org.hornetq.core.server.group.impl.Response;
@@ -262,6 +263,34 @@ public final class BindingsImpl implements Bindings
 
    private void route(final ServerMessage message, final RoutingContext context, final boolean groupRouting) throws Exception
    {
+      /* This is a special treatment for scaled-down messages involving SnF queues.
+       * See org.hornetq.core.server.impl.ScaleDownHandler.scaleDownMessages() for the logic that sends messages with this property
+       */
+      if (message.containsProperty(MessageImpl.HDR_SCALEDOWN_TO_IDS))
+      {
+         byte[] ids = (byte[]) message.removeProperty(MessageImpl.HDR_SCALEDOWN_TO_IDS);
+
+         if (ids != null)
+         {
+            ByteBuffer buffer = ByteBuffer.wrap(ids);
+            while (buffer.hasRemaining())
+            {
+               long id = buffer.getLong();
+               for (Map.Entry<Long, Binding> entry : bindingsMap.entrySet())
+               {
+                  if (entry.getValue() instanceof RemoteQueueBinding)
+                  {
+                     RemoteQueueBinding remoteQueueBinding = (RemoteQueueBinding) entry.getValue();
+                     if (remoteQueueBinding.getRemoteQueueID() == id)
+                     {
+                        message.putBytesProperty(MessageImpl.HDR_ROUTE_TO_IDS, ByteBuffer.allocate(8).putLong(remoteQueueBinding.getID()).array());
+                     }
+                  }
+               }
+            }
+         }
+      }
+
       boolean routed = false;
 
       if (!exclusiveBindings.isEmpty())

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/DuplicateIDCacheImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/DuplicateIDCacheImpl.java b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/DuplicateIDCacheImpl.java
index ddd8a44..d10294a 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/DuplicateIDCacheImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/DuplicateIDCacheImpl.java
@@ -93,7 +93,7 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache
             // cache size has been reduced in config - delete the extra records
             if (txID == -1)
             {
-               txID = storageManager.generateUniqueID();
+               txID = storageManager.generateID();
             }
 
             storageManager.deleteDuplicateIDTransactional(txID, id.getB());
@@ -156,7 +156,7 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache
       {
          if (persist)
          {
-            recordID = storageManager.generateUniqueID();
+            recordID = storageManager.generateID();
             storageManager.storeDuplicateID(address, duplID, recordID);
          }
 
@@ -166,7 +166,7 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache
       {
          if (persist)
          {
-            recordID = storageManager.generateUniqueID();
+            recordID = storageManager.generateID();
             storageManager.storeDuplicateIDTransactional(tx.getID(), address, duplID, recordID);
 
             tx.setContainsPersistent();
@@ -245,12 +245,15 @@ public class DuplicateIDCacheImpl implements DuplicateIDCache
    {
       synchronized (this)
       {
-         long tx = storageManager.generateUniqueID();
-         for (Pair<ByteArrayHolder, Long> id : ids)
+         if (ids.size() > 0)
          {
-            storageManager.deleteDuplicateIDTransactional(tx, id.getB());
+            long tx = storageManager.generateID();
+            for (Pair<ByteArrayHolder, Long> id : ids)
+            {
+               storageManager.deleteDuplicateIDTransactional(tx, id.getB());
+            }
+            storageManager.commit(tx);
          }
-         storageManager.commit(tx);
 
          ids.clear();
          cache.clear();

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/PostOfficeImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/PostOfficeImpl.java b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/PostOfficeImpl.java
index 8b90e9a..5b3e7cb 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/PostOfficeImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/PostOfficeImpl.java
@@ -34,6 +34,7 @@ import org.hornetq.api.core.HornetQNonExistentQueueException;
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
 import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.filter.Filter;
@@ -218,13 +219,15 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
 
    public void onNotification(final Notification notification)
    {
+      if (!(notification.getType() instanceof CoreNotificationType)) return;
+
       if (isTrace)
       {
          HornetQServerLogger.LOGGER.trace("Receiving notification : " + notification + " on server " + this.server);
       }
       synchronized (notificationLock)
       {
-         NotificationType type = notification.getType();
+         CoreNotificationType type = (CoreNotificationType) notification.getType();
 
          switch (type)
          {
@@ -446,7 +449,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
 
    // PostOffice implementation -----------------------------------------------
 
-   // TODO - needs to be synchronized to prevent happening concurrently with activate().
+   // TODO - needs to be synchronized to prevent happening concurrently with activate()
    // (and possible removeBinding and other methods)
    // Otherwise can have situation where createQueue comes in before failover, then failover occurs
    // and post office is activated but queue remains unactivated after failover so delivery never occurs
@@ -483,7 +486,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
          HornetQServerLogger.LOGGER.debug("ClusterCommunication::Sending notification for addBinding " + binding + " from server " + server);
       }
 
-      managementService.sendNotification(new Notification(uid, NotificationType.BINDING_ADDED, props));
+      managementService.sendNotification(new Notification(uid, CoreNotificationType.BINDING_ADDED, props));
    }
 
    public synchronized Binding removeBinding(final SimpleString uniqueName, Transaction tx) throws Exception
@@ -539,7 +542,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
             props.putSimpleStringProperty(ManagementHelper.HDR_FILTERSTRING, binding.getFilter().getFilterString());
          }
 
-         managementService.sendNotification(new Notification(null, NotificationType.BINDING_REMOVED, props));
+         managementService.sendNotification(new Notification(null, CoreNotificationType.BINDING_REMOVED, props));
       }
 
       binding.close();
@@ -555,6 +558,13 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
       {
          cache.clear();
       }
+
+      cache = duplicateIDCaches.remove(BRIDGE_CACHE_STR.concat(address));
+
+      if (cache != null)
+      {
+         cache.clear();
+      }
    }
 
    @Override
@@ -799,7 +809,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
       // We have to copy the message and store it separately, otherwise we may lose remote bindings in case of restart before the message
       // arrived the target node
       // as described on https://issues.jboss.org/browse/JBPAPP-6130
-      ServerMessage copyRedistribute = message.copy(storageManager.generateUniqueID());
+      ServerMessage copyRedistribute = message.copy(storageManager.generateID());
 
       Bindings bindings = addressManager.getBindingsForRoutingAddress(message.getAddress());
 
@@ -871,7 +881,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
       {
          // First send a reset message
 
-         ServerMessage message = new ServerMessageImpl(storageManager.generateUniqueID(), 50);
+         ServerMessage message = new ServerMessageImpl(storageManager.generateID(), 50);
 
          message.setAddress(queueName);
          message.putBooleanProperty(PostOfficeImpl.HDR_RESET_QUEUE_DATA, true);
@@ -883,9 +893,9 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
             {
                HornetQServerLogger.LOGGER.trace("QueueInfo on sendQueueInfoToQueue = " + info);
             }
-            if (info.getAddress().startsWith(address))
+            if (info.matchesAddress(address))
             {
-               message = createQueueInfoMessage(NotificationType.BINDING_ADDED, queueName);
+               message = createQueueInfoMessage(CoreNotificationType.BINDING_ADDED, queueName);
 
                message.putStringProperty(ManagementHelper.HDR_ADDRESS, info.getAddress());
                message.putStringProperty(ManagementHelper.HDR_CLUSTER_NAME, info.getClusterName());
@@ -900,7 +910,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
 
                for (int i = 0; i < info.getNumberOfConsumers() - consumersWithFilters; i++)
                {
-                  message = createQueueInfoMessage(NotificationType.CONSUMER_CREATED, queueName);
+                  message = createQueueInfoMessage(CoreNotificationType.CONSUMER_CREATED, queueName);
 
                   message.putStringProperty(ManagementHelper.HDR_ADDRESS, info.getAddress());
                   message.putStringProperty(ManagementHelper.HDR_CLUSTER_NAME, info.getClusterName());
@@ -914,7 +924,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
                {
                   for (SimpleString filterString : info.getFilterStrings())
                   {
-                     message = createQueueInfoMessage(NotificationType.CONSUMER_CREATED, queueName);
+                     message = createQueueInfoMessage(CoreNotificationType.CONSUMER_CREATED, queueName);
 
                      message.putStringProperty(ManagementHelper.HDR_ADDRESS, info.getAddress());
                      message.putStringProperty(ManagementHelper.HDR_CLUSTER_NAME, info.getClusterName());
@@ -927,7 +937,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
                }
             }
          }
-         ServerMessage completeMessage = new ServerMessageImpl(storageManager.generateUniqueID(), 50);
+         ServerMessage completeMessage = new ServerMessageImpl(storageManager.generateID(), 50);
 
          completeMessage.setAddress(queueName);
          completeMessage.putBooleanProperty(PostOfficeImpl.HDR_RESET_QUEUE_DATA_COMPLETE, true);
@@ -960,7 +970,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
          // We use properties to establish routing context on clustering.
          // However if the client resends the message after receiving, it needs to be removed
          if ((name.startsWith(MessageImpl.HDR_ROUTE_TO_IDS) && !name.equals(MessageImpl.HDR_ROUTE_TO_IDS)) ||
-            name.equals(MessageImpl.HDR_ROUTE_TO_ACK_IDS))
+               (name.startsWith(MessageImpl.HDR_ROUTE_TO_ACK_IDS) && !name.equals(MessageImpl.HDR_ROUTE_TO_ACK_IDS)))
          {
             if (valuesToRemove == null)
             {
@@ -1360,7 +1370,7 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
 
    private ServerMessage createQueueInfoMessage(final NotificationType type, final SimpleString queueName)
    {
-      ServerMessage message = new ServerMessageImpl(storageManager.generateUniqueID(), 50);
+      ServerMessage message = new ServerMessageImpl(storageManager.generateID(), 50);
 
       message.setAddress(queueName);
 
@@ -1513,4 +1523,15 @@ public class PostOfficeImpl implements PostOffice, NotificationListener, Binding
       }
       return bindings;
    }
+
+   // For tests only
+   public AddressManager getAddressManager()
+   {
+      return addressManager;
+   }
+
+   public HornetQServer getServer()
+   {
+      return server;
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/SimpleAddressManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/SimpleAddressManager.java b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/SimpleAddressManager.java
index 66128db..08ad4f1 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/SimpleAddressManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/postoffice/impl/SimpleAddressManager.java
@@ -63,9 +63,9 @@ public class SimpleAddressManager implements AddressManager
          throw HornetQMessageBundle.BUNDLE.bindingAlreadyExists(binding);
       }
 
-      if (HornetQServerLogger.LOGGER.isDebugEnabled())
+      if (HornetQServerLogger.LOGGER.isTraceEnabled())
       {
-         HornetQServerLogger.LOGGER.debug("Adding binding " + binding + " with address = " + binding.getUniqueName(), new Exception("trace"));
+         HornetQServerLogger.LOGGER.trace("Adding binding " + binding + " with address = " + binding.getUniqueName(), new Exception("trace"));
       }
 
       return addMappingInternal(binding.getAddress(), binding);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/protocol/ProtocolHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/protocol/ProtocolHandler.java b/hornetq-server/src/main/java/org/hornetq/core/protocol/ProtocolHandler.java
index dfc0521..d7edc4a 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/protocol/ProtocolHandler.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/protocol/ProtocolHandler.java
@@ -14,16 +14,19 @@ package org.hornetq.core.protocol;
 
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.Future;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 
 import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelHandler;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelPipeline;
 import io.netty.handler.codec.ByteToMessageDecoder;
 import io.netty.handler.codec.http.DefaultFullHttpRequest;
+import io.netty.handler.codec.http.DefaultFullHttpResponse;
 import io.netty.handler.codec.http.HttpHeaders;
 import io.netty.handler.codec.http.HttpObjectAggregator;
 import io.netty.handler.codec.http.HttpRequestDecoder;
@@ -35,11 +38,15 @@ import org.hornetq.core.remoting.impl.netty.ConnectionCreator;
 import org.hornetq.core.remoting.impl.netty.HttpAcceptorHandler;
 import org.hornetq.core.remoting.impl.netty.HttpKeepAliveRunnable;
 import org.hornetq.core.remoting.impl.netty.NettyAcceptor;
+import org.hornetq.core.remoting.impl.netty.NettyConnector;
 import org.hornetq.core.remoting.impl.netty.NettyServerConnection;
 import org.hornetq.core.remoting.impl.netty.TransportConstants;
 import org.hornetq.spi.core.protocol.ProtocolManager;
 import org.hornetq.utils.ConfigurationHelper;
 
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
 public class ProtocolHandler
 {
    private Map<String, ProtocolManager> protocolMap;
@@ -104,6 +111,12 @@ public class ProtocolHandler
                ctx.pipeline().remove("http-handler");
                ctx.fireChannelRead(msg);
             }
+            // HORNETQ-1391
+            else if (upgrade != null && upgrade.equalsIgnoreCase(NettyConnector.HORNETQ_REMOTING))
+            {
+               // Send the response and close the connection if necessary.
+               ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)).addListener(ChannelFutureListener.CLOSE);
+            }
          }
          else
          {
@@ -133,15 +146,25 @@ public class ProtocolHandler
             return;
          }
          String protocolToUse = null;
-         for (String protocol : protocolMap.keySet())
+         Set<String> protocolSet = protocolMap.keySet();
+         if (!protocolSet.isEmpty())
          {
-            ProtocolManager protocolManager = protocolMap.get(protocol);
-            if (protocolManager.isProtocol(in.copy(0, 8).array()))
+            // Use getBytes(...) as this works with direct and heap buffers.
+            // See https://issues.jboss.org/browse/HORNETQ-1406
+            byte[] bytes = new byte[8];
+            in.getBytes(0, bytes);
+
+            for (String protocol : protocolSet)
             {
-               protocolToUse = protocol;
-               break;
+               ProtocolManager protocolManager = protocolMap.get(protocol);
+               if (protocolManager.isProtocol(bytes))
+               {
+                  protocolToUse = protocol;
+                  break;
+               }
             }
          }
+
          //if we get here we assume we use the core protocol as we match nothing else
          if (protocolToUse == null)
          {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreProtocolManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreProtocolManager.java b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreProtocolManager.java
index 9d5fdb0..d0fe3ac 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreProtocolManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreProtocolManager.java
@@ -20,9 +20,7 @@ import java.util.concurrent.Executor;
 import java.util.concurrent.RejectedExecutionException;
 
 import io.netty.channel.ChannelPipeline;
-import org.hornetq.api.core.HornetQAlreadyReplicatingException;
 import org.hornetq.api.core.HornetQBuffer;
-import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Interceptor;
 import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.TransportConfiguration;
@@ -37,8 +35,6 @@ import org.hornetq.core.protocol.core.CoreRemotingConnection;
 import org.hornetq.core.protocol.core.Packet;
 import org.hornetq.core.protocol.core.ServerSessionPacketHandler;
 import org.hornetq.core.protocol.core.impl.ChannelImpl.CHANNEL_ID;
-import org.hornetq.core.protocol.core.impl.wireformat.BackupRegistrationMessage;
-import org.hornetq.core.protocol.core.impl.wireformat.BackupReplicationStartFailedMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage_V2;
 import org.hornetq.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage_V3;
@@ -50,8 +46,8 @@ import org.hornetq.core.remoting.impl.netty.HornetQFrameDecoder2;
 import org.hornetq.core.remoting.impl.netty.NettyServerConnection;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
-import org.hornetq.core.server.cluster.ClusterConnection;
 import org.hornetq.spi.core.protocol.ConnectionEntry;
+import org.hornetq.spi.core.protocol.MessageConverter;
 import org.hornetq.spi.core.protocol.ProtocolManager;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.spi.core.remoting.Acceptor;
@@ -81,6 +77,16 @@ class CoreProtocolManager implements ProtocolManager
       this.outgoingInterceptors = outgoingInterceptors;
    }
 
+   /**
+    * no need to implement this now
+    * @return
+    */
+   @Override
+   public MessageConverter getConverter()
+   {
+      return null;
+   }
+
    public ConnectionEntry createConnectionEntry(final Acceptor acceptorUsed, final Connection connection)
    {
       final Configuration config = server.getConfiguration();
@@ -113,7 +119,7 @@ class CoreProtocolManager implements ProtocolManager
 
       channel0.setHandler(new LocalChannelHandler(config, entry, channel0, acceptorUsed, rc));
 
-      server.getClusterManager().addClusterChannelHandler(rc.getChannel(CHANNEL_ID.CLUSTER.id, -1), acceptorUsed, rc);
+      server.getClusterManager().addClusterChannelHandler(rc.getChannel(CHANNEL_ID.CLUSTER.id, -1), acceptorUsed, rc, server.getActivation());
 
       return entry;
    }
@@ -332,33 +338,6 @@ class CoreProtocolManager implements ProtocolManager
                      }
                   }
                });
-
-            }
-         }
-         else if (packet.getType() == PacketImpl.BACKUP_REGISTRATION)
-         {
-            BackupRegistrationMessage msg = (BackupRegistrationMessage)packet;
-            ClusterConnection clusterConnection = acceptorUsed.getClusterConnection();
-
-            if (!config.isSecurityEnabled() || clusterConnection.verify(msg.getClusterUser(), msg.getClusterPassword()))
-            {
-               try
-               {
-                  server.startReplication(rc, clusterConnection, getPair(msg.getConnector(), true),
-                                          msg.isFailBackRequest());
-               }
-               catch (HornetQAlreadyReplicatingException are)
-               {
-                  channel0.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.ALREADY_REPLICATING));
-               }
-               catch (HornetQException e)
-               {
-                  channel0.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.EXCEPTION));
-               }
-            }
-            else
-            {
-               channel0.send(new BackupReplicationStartFailedMessage(BackupReplicationStartFailedMessage.BackupRegistrationProblem.AUTHENTICATION));
             }
          }
       }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreSessionCallback.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreSessionCallback.java b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreSessionCallback.java
index 12dd132..b4d993b 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreSessionCallback.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/CoreSessionCallback.java
@@ -22,6 +22,7 @@ import org.hornetq.core.protocol.core.impl.wireformat.SessionReceiveContinuation
 import org.hornetq.core.protocol.core.impl.wireformat.SessionReceiveLargeMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.SessionReceiveMessage;
 import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.core.server.ServerConsumer;
 import org.hornetq.core.server.ServerMessage;
 import org.hornetq.spi.core.protocol.ProtocolManager;
 import org.hornetq.spi.core.protocol.SessionCallback;
@@ -47,9 +48,9 @@ public final class CoreSessionCallback implements SessionCallback
       this.channel = channel;
    }
 
-   public int sendLargeMessage(ServerMessage message, long consumerID, long bodySize, int deliveryCount)
+   public int sendLargeMessage(ServerMessage message, ServerConsumer consumer, long bodySize, int deliveryCount)
    {
-      Packet packet = new SessionReceiveLargeMessage(consumerID, message, bodySize, deliveryCount);
+      Packet packet = new SessionReceiveLargeMessage(consumer.getID(), message, bodySize, deliveryCount);
 
       channel.send(packet);
 
@@ -58,18 +59,18 @@ public final class CoreSessionCallback implements SessionCallback
       return size;
    }
 
-   public int sendLargeMessageContinuation(long consumerID, byte[] body, boolean continues, boolean requiresResponse)
+   public int sendLargeMessageContinuation(ServerConsumer consumer, byte[] body, boolean continues, boolean requiresResponse)
    {
-      Packet packet = new SessionReceiveContinuationMessage(consumerID, body, continues, requiresResponse);
+      Packet packet = new SessionReceiveContinuationMessage(consumer.getID(), body, continues, requiresResponse);
 
       channel.send(packet);
 
       return packet.getPacketSize();
    }
 
-   public int sendMessage(ServerMessage message, long consumerID, int deliveryCount)
+   public int sendMessage(ServerMessage message, ServerConsumer consumer, int deliveryCount)
    {
-      Packet packet = new SessionReceiveMessage(consumerID, message, deliveryCount);
+      Packet packet = new SessionReceiveMessage(consumer.getID(), message, deliveryCount);
 
       int size = 0;
 
@@ -112,15 +113,24 @@ public final class CoreSessionCallback implements SessionCallback
    }
 
    @Override
-   public void disconnect(long consumerId, String queueName)
+   public void disconnect(ServerConsumer consumerId, String queueName)
    {
       if (channel.supports(PacketImpl.DISCONNECT_CONSUMER))
       {
-         channel.send(new DisconnectConsumerMessage(consumerId));
+         channel.send(new DisconnectConsumerMessage(consumerId.getID()));
       }
       else
       {
          HornetQServerLogger.LOGGER.warnDisconnectOldClient(queueName);
       }
    }
+
+
+   @Override
+   public boolean hasCredits(ServerConsumer consumer)
+   {
+      // This one will always return has credits
+      // as the flow control is done by hornetq
+      return true;
+   }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/HornetQPacketHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/HornetQPacketHandler.java b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/HornetQPacketHandler.java
index bb4e111..2d8f227 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/HornetQPacketHandler.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/HornetQPacketHandler.java
@@ -16,7 +16,6 @@ import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.HornetQExceptionType;
 import org.hornetq.api.core.HornetQInternalErrorException;
 import org.hornetq.api.core.SimpleString;
-import org.hornetq.core.config.BackupStrategy;
 import org.hornetq.core.protocol.core.Channel;
 import org.hornetq.core.protocol.core.ChannelHandler;
 import org.hornetq.core.protocol.core.CoreRemotingConnection;
@@ -119,8 +118,7 @@ public class HornetQPacketHandler implements ChannelHandler
    {
       String nodeID = failoverMessage.getNodeID();
       boolean okToFailover = nodeID == null ||
-            !(server.getConfiguration().getHAPolicy().getBackupStrategy() == BackupStrategy.SCALE_DOWN &&
-            !server.hasScaledDown(new SimpleString(nodeID)));
+            !(server.getHAPolicy().canScaleDown() && !server.hasScaledDown(new SimpleString(nodeID)));
       channel1.send(new CheckFailoverReplyMessage(okToFailover));
    }
 
@@ -133,7 +131,6 @@ public class HornetQPacketHandler implements ChannelHandler
          Version version = server.getVersion();
          if (!version.isCompatible(request.getVersion()))
          {
-            HornetQServerLogger.LOGGER.incompatibleVersion(request.getVersion(), connection.getRemoteAddress(), version.getFullVersion());
             throw HornetQMessageBundle.BUNDLE.incompatibleClientServer();
          }
 
@@ -180,7 +177,7 @@ public class HornetQPacketHandler implements ChannelHandler
                                                       request.getDefaultAddress(),
                                                       new CoreSessionCallback(request.getName(),
                                                                               protocolManager,
-                                                                              channel));
+                                                                              channel), null);
 
          ServerSessionPacketHandler handler = new ServerSessionPacketHandler(session,
                                                                              server.getStorageManager(),
@@ -194,13 +191,17 @@ public class HornetQPacketHandler implements ChannelHandler
       }
       catch (HornetQException e)
       {
-         HornetQServerLogger.LOGGER.failedToCreateSession(e);
-         response = new HornetQExceptionMessage(e);
-
          if (e.getType() == HornetQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS)
          {
             incompatibleVersion = true;
+            HornetQServerLogger.LOGGER.debug("Sending HornetQException after Incompatible client", e);
+         }
+         else
+         {
+            HornetQServerLogger.LOGGER.failedToCreateSession(e);
          }
+
+         response = new HornetQExceptionMessage(e);
       }
       catch (Exception e)
       {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/BackupRequestMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/BackupRequestMessage.java b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/BackupRequestMessage.java
index d908e54..566bb74 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/BackupRequestMessage.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/BackupRequestMessage.java
@@ -16,13 +16,11 @@ package org.hornetq.core.protocol.core.impl.wireformat;
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.core.protocol.core.impl.PacketImpl;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 
 public class BackupRequestMessage extends PacketImpl
 {
    private int backupSize;
    private SimpleString nodeID;
-   private HAPolicy.POLICY_TYPE backupType;
    private String journalDirectory;
    private String bindingsDirectory;
    private String largeMessagesDirectory;
@@ -38,7 +36,6 @@ public class BackupRequestMessage extends PacketImpl
    {
       super(BACKUP_REQUEST);
       this.backupSize = backupSize;
-      backupType = HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE;
       this.journalDirectory = journalDirectory;
       this.bindingsDirectory = bindingsDirectory;
       this.largeMessagesDirectory = largeMessagesDirectory;
@@ -50,7 +47,6 @@ public class BackupRequestMessage extends PacketImpl
       super(BACKUP_REQUEST);
       this.backupSize = backupSize;
       this.nodeID = nodeID;
-      backupType = HAPolicy.POLICY_TYPE.COLOCATED_REPLICATED;
    }
 
    @Override
@@ -58,18 +54,11 @@ public class BackupRequestMessage extends PacketImpl
    {
       super.encodeRest(buffer);
       buffer.writeInt(backupSize);
-      buffer.writeByte(backupType.getType());
-      if (backupType == HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE)
-      {
-         buffer.writeString(journalDirectory);
-         buffer.writeString(bindingsDirectory);
-         buffer.writeString(largeMessagesDirectory);
-         buffer.writeString(pagingDirectory);
-      }
-      else
-      {
-         buffer.writeSimpleString(nodeID);
-      }
+      buffer.writeNullableString(journalDirectory);
+      buffer.writeNullableString(bindingsDirectory);
+      buffer.writeNullableString(largeMessagesDirectory);
+      buffer.writeNullableString(pagingDirectory);
+      buffer.writeNullableSimpleString(nodeID);
    }
 
    @Override
@@ -77,18 +66,11 @@ public class BackupRequestMessage extends PacketImpl
    {
       super.decodeRest(buffer);
       backupSize = buffer.readInt();
-      backupType = HAPolicy.POLICY_TYPE.toBackupType(buffer.readByte());
-      if (backupType == HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE)
-      {
-         journalDirectory = buffer.readString();
-         bindingsDirectory = buffer.readString();
-         largeMessagesDirectory = buffer.readString();
-         pagingDirectory = buffer.readString();
-      }
-      else
-      {
-         nodeID = buffer.readSimpleString();
-      }
+      journalDirectory = buffer.readNullableString();
+      bindingsDirectory = buffer.readNullableString();
+      largeMessagesDirectory = buffer.readNullableString();
+      pagingDirectory = buffer.readNullableString();
+      nodeID = buffer.readNullableSimpleString();
    }
 
    public int getBackupSize()
@@ -101,11 +83,6 @@ public class BackupRequestMessage extends PacketImpl
       return nodeID;
    }
 
-   public HAPolicy.POLICY_TYPE getBackupType()
-   {
-      return backupType;
-   }
-
    public String getJournalDirectory()
    {
       return journalDirectory;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java
index 1fc484f..114de68 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/ReplicationSyncFileMessage.java
@@ -23,7 +23,7 @@ import org.hornetq.core.persistence.impl.journal.JournalStorageManager.JournalCo
 import org.hornetq.core.protocol.core.impl.PacketImpl;
 
 /**
- * Message is used to sync {@link SequentialFile}s to a backup server. The {@link FileType} controls
+ * Message is used to sync {@link org.hornetq.core.journal.SequentialFile}s to a backup server. The {@link FileType} controls
  * which extra information is sent.
  */
 public final class ReplicationSyncFileMessage extends PacketImpl

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMAcceptor.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMAcceptor.java b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMAcceptor.java
index e794ef6..ae0838e 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMAcceptor.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMAcceptor.java
@@ -20,7 +20,7 @@ import java.util.concurrent.Executor;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.security.HornetQPrincipal;
 import org.hornetq.core.server.HornetQComponent;
 import org.hornetq.core.server.HornetQMessageBundle;
@@ -109,7 +109,7 @@ public final class InVMAcceptor implements Acceptor
          props.putSimpleStringProperty(new SimpleString("factory"),
                                        new SimpleString(InVMAcceptorFactory.class.getName()));
          props.putIntProperty(new SimpleString("id"), id);
-         Notification notification = new Notification(null, NotificationType.ACCEPTOR_STARTED, props);
+         Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
          notificationService.sendNotification(notification);
       }
 
@@ -143,7 +143,7 @@ public final class InVMAcceptor implements Acceptor
          props.putSimpleStringProperty(new SimpleString("factory"),
                                        new SimpleString(InVMAcceptorFactory.class.getName()));
          props.putIntProperty(new SimpleString("id"), id);
-         Notification notification = new Notification(null, NotificationType.ACCEPTOR_STOPPED, props);
+         Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STOPPED, props);
          try
          {
             notificationService.sendNotification(notification);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnection.java b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnection.java
index 26bdf13..0613724 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnection.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnection.java
@@ -19,12 +19,14 @@ import java.util.concurrent.Executor;
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.TimeUnit;
 
+import io.netty.channel.ChannelFutureListener;
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQBuffers;
 import org.hornetq.api.core.HornetQInterruptedException;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.security.HornetQPrincipal;
 import org.hornetq.core.server.HornetQServerLogger;
+import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.spi.core.remoting.BufferHandler;
 import org.hornetq.spi.core.remoting.Connection;
 import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener;
@@ -59,6 +61,8 @@ public class InVMConnection implements Connection
 
    private final HornetQPrincipal defaultHornetQPrincipal;
 
+   private RemotingConnection protocolConnection;
+
    public InVMConnection(final int serverID,
                          final BufferHandler handler,
                          final ConnectionLifeCycleListener listener,
@@ -96,6 +100,24 @@ public class InVMConnection implements Connection
       this.defaultHornetQPrincipal = defaultHornetQPrincipal;
    }
 
+
+   public void forceClose()
+   {
+      // no op
+   }
+
+   public RemotingConnection getProtocolConnection()
+   {
+      return this.protocolConnection;
+   }
+
+   public void setProtocolConnection(RemotingConnection connection)
+   {
+      this.protocolConnection = connection;
+   }
+
+
+
    public void close()
    {
       if (closing)
@@ -132,11 +154,16 @@ public class InVMConnection implements Connection
 
    public void write(final HornetQBuffer buffer)
    {
-      write(buffer, false, false);
+      write(buffer, false, false, null);
    }
 
    public void write(final HornetQBuffer buffer, final boolean flush, final boolean batch)
    {
+      write(buffer, flush, batch, null);
+   }
+
+   public void write(final HornetQBuffer buffer, final boolean flush, final boolean batch, final ChannelFutureListener futureListener)
+   {
       final HornetQBuffer copied = buffer.copy(0, buffer.capacity());
 
       copied.setIndex(buffer.readerIndex(), buffer.writerIndex());
@@ -157,6 +184,11 @@ public class InVMConnection implements Connection
                         HornetQServerLogger.LOGGER.trace(InVMConnection.this + "::Sending inVM packet");
                      }
                      handler.bufferReceived(id, copied);
+                     if (futureListener != null)
+                     {
+                         // TODO BEFORE MERGE: (is null a good option here?)
+                        futureListener.operationComplete(null);
+                     }
                   }
                }
                catch (Exception e)
@@ -224,6 +256,12 @@ public class InVMConnection implements Connection
    {
    }
 
+   @Override
+   public boolean isUsingProtocolHandling()
+   {
+      return false;
+   }
+
    public HornetQPrincipal getDefaultHornetQPrincipal()
    {
       return defaultHornetQPrincipal;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnector.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnector.java b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnector.java
index 1d24adf..b47cc66 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnector.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnector.java
@@ -12,19 +12,21 @@
  */
 package org.hornetq.core.remoting.impl.invm;
 
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.Executor;
 
 import org.hornetq.api.core.HornetQException;
-import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.core.server.HornetQComponent;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.HornetQMessageBundle;
 import org.hornetq.spi.core.remoting.AbstractConnector;
 import org.hornetq.spi.core.remoting.Acceptor;
 import org.hornetq.spi.core.remoting.BufferHandler;
+import org.hornetq.spi.core.remoting.ClientProtocolManager;
 import org.hornetq.spi.core.remoting.Connection;
 import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener;
 import org.hornetq.utils.ConfigurationHelper;
@@ -34,10 +36,20 @@ import org.hornetq.utils.OrderedExecutorFactory;
  * A InVMConnector
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  *
  */
 public class InVMConnector extends AbstractConnector
 {
+   public static final Map<String, Object> DEFAULT_CONFIG;
+
+   static
+   {
+      Map<String, Object> config = new HashMap<String , Object>();
+      config.put(TransportConstants.SERVER_ID_PROP_NAME, TransportConstants.DEFAULT_SERVER_ID);
+      DEFAULT_CONFIG = Collections.unmodifiableMap(config);
+   }
+
    // Used for testing failure only
    public static volatile boolean failOnCreateConnection;
 
@@ -63,6 +75,8 @@ public class InVMConnector extends AbstractConnector
 
    protected final int id;
 
+   private final ClientProtocolManager protocolManager;
+
    private final BufferHandler handler;
 
    private final ConnectionLifeCycleListener listener;
@@ -81,7 +95,8 @@ public class InVMConnector extends AbstractConnector
                         final BufferHandler handler,
                         final ConnectionLifeCycleListener listener,
                         final Executor closeExecutor,
-                        final Executor threadPool)
+                        final Executor threadPool,
+                        ClientProtocolManager protocolManager)
    {
       super(configuration);
       this.listener = listener;
@@ -97,6 +112,8 @@ public class InVMConnector extends AbstractConnector
       InVMRegistry registry = InVMRegistry.instance;
 
       acceptor = registry.getAcceptor(id);
+
+      this.protocolManager = protocolManager;
    }
 
    public Acceptor getAcceptor()
@@ -180,7 +197,7 @@ public class InVMConnector extends AbstractConnector
    {
       // No acceptor on a client connection
       InVMConnection inVMConnection = new InVMConnection(id, handler, listener, serverExecutor);
-      listener.connectionCreated(null, inVMConnection, HornetQClient.DEFAULT_CORE_PROTOCOL);
+      listener.connectionCreated(null, inVMConnection, protocolManager.getName());
       return inVMConnection;
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnectorFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnectorFactory.java b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnectorFactory.java
index 9788d85..283ea98 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnectorFactory.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/InVMConnectorFactory.java
@@ -19,6 +19,7 @@ import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
 
 import org.hornetq.spi.core.remoting.BufferHandler;
+import org.hornetq.spi.core.remoting.ClientProtocolManager;
 import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener;
 import org.hornetq.spi.core.remoting.Connector;
 import org.hornetq.spi.core.remoting.ConnectorFactory;
@@ -27,7 +28,7 @@ import org.hornetq.spi.core.remoting.ConnectorFactory;
  * A InVMConnectorFactory
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
- *
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class InVMConnectorFactory implements ConnectorFactory
 {
@@ -36,9 +37,10 @@ public class InVMConnectorFactory implements ConnectorFactory
                                     final ConnectionLifeCycleListener listener,
                                     final Executor closeExecutor,
                                     final Executor threadPool,
-                                    final ScheduledExecutorService scheduledThreadPool)
+                                    final ScheduledExecutorService scheduledThreadPool,
+                                    final ClientProtocolManager protocolManager)
    {
-      InVMConnector connector = new InVMConnector(configuration, handler, listener, closeExecutor, threadPool);
+      InVMConnector connector = new InVMConnector(configuration, handler, listener, closeExecutor, threadPool, protocolManager);
 
       return connector;
    }
@@ -53,4 +55,10 @@ public class InVMConnectorFactory implements ConnectorFactory
    {
       return true;
    }
+
+   @Override
+   public Map<String, Object> getDefaults()
+   {
+      return InVMConnector.DEFAULT_CONFIG;
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/TransportConstants.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/TransportConstants.java b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/TransportConstants.java
index 46332d3..ea67573 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/TransportConstants.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/invm/TransportConstants.java
@@ -22,12 +22,15 @@ import org.hornetq.api.config.HornetQDefaultConfiguration;
  * A TransportConstants
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  *
  */
 public final class TransportConstants
 {
    public static final String SERVER_ID_PROP_NAME = "server-id";
 
+   public static final int DEFAULT_SERVER_ID = 0;
+
    public static final Set<String> ALLOWABLE_CONNECTOR_KEYS;
 
    public static final Set<String> ALLOWABLE_ACCEPTOR_KEYS;

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/netty/NettyAcceptor.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/netty/NettyAcceptor.java b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/netty/NettyAcceptor.java
index 0a8288b..adcf29f 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/netty/NettyAcceptor.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/remoting/impl/netty/NettyAcceptor.java
@@ -52,7 +52,7 @@ import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.management.NotificationType;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
 import org.hornetq.core.protocol.ProtocolHandler;
 import org.hornetq.core.remoting.impl.ssl.SSLSupport;
@@ -443,7 +443,7 @@ public class NettyAcceptor implements Acceptor
                                           new SimpleString(NettyAcceptorFactory.class.getName()));
             props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
             props.putIntProperty(new SimpleString("port"), port);
-            Notification notification = new Notification(null, NotificationType.ACCEPTOR_STARTED, props);
+            Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
             notificationService.sendNotification(notification);
          }
 
@@ -457,7 +457,6 @@ public class NettyAcceptor implements Acceptor
                                                                             TimeUnit.MILLISECONDS);
          }
 
-         // TODO: Think about add Version back to netty
          HornetQServerLogger.LOGGER.startedNettyAcceptor(TransportConstants.NETTY_VERSION, host, port);
       }
    }
@@ -560,7 +559,7 @@ public class NettyAcceptor implements Acceptor
                                        new SimpleString(NettyAcceptorFactory.class.getName()));
          props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
          props.putIntProperty(new SimpleString("port"), port);
-         Notification notification = new Notification(null, NotificationType.ACCEPTOR_STOPPED, props);
+         Notification notification = new Notification(null, CoreNotificationType.ACCEPTOR_STOPPED, props);
          try
          {
             notificationService.sendNotification(notification);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/remoting/server/impl/RemotingServiceImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/remoting/server/impl/RemotingServiceImpl.java b/hornetq-server/src/main/java/org/hornetq/core/remoting/server/impl/RemotingServiceImpl.java
index 60d1570..f1b2ce9 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/remoting/server/impl/RemotingServiceImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/remoting/server/impl/RemotingServiceImpl.java
@@ -24,6 +24,7 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -48,6 +49,7 @@ import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.cluster.ClusterConnection;
 import org.hornetq.core.server.cluster.ClusterManager;
+import org.hornetq.core.server.impl.ServiceRegistry;
 import org.hornetq.core.server.impl.ServerSessionImpl;
 import org.hornetq.core.server.management.ManagementService;
 import org.hornetq.spi.core.protocol.ConnectionEntry;
@@ -67,6 +69,7 @@ import org.hornetq.utils.HornetQThreadFactory;
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  * @author <a href="mailto:ataylor@redhat.com">Andy Taylor</a>
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycleListener
 {
@@ -96,6 +99,8 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle
 
    private ExecutorService threadPool;
 
+   private final Executor flushExecutor;
+
    private final ScheduledExecutorService scheduledThreadPool;
 
    private FailureCheckAndFlushThread failureCheckAndFlushThread;
@@ -106,6 +111,8 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle
 
    private HornetQPrincipal defaultInvmSecurityPrincipal;
 
+   private ServiceRegistry serviceRegistry;
+
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
@@ -114,43 +121,29 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle
                               final Configuration config,
                               final HornetQServer server,
                               final ManagementService managementService,
-                              final ScheduledExecutorService scheduledThreadPool, List<ProtocolManagerFactory> protocolManagerFactories)
+                              final ScheduledExecutorService scheduledThreadPool,
+                              List<ProtocolManagerFactory> protocolManagerFactories,
+                              final Executor flushExecutor,
+                              final ServiceRegistry serviceRegistry)
    {
+      this.serviceRegistry = serviceRegistry;
+
       acceptorsConfig = config.getAcceptorConfigurations();
 
       this.server = server;
 
       this.clusterManager = clusterManager;
 
-      for (String interceptorClass : config.getIncomingInterceptorClassNames())
-      {
-         try
-         {
-            incomingInterceptors.add((Interceptor) safeInitNewInstance(interceptorClass));
-         }
-         catch (Exception e)
-         {
-            HornetQServerLogger.LOGGER.errorCreatingRemotingInterceptor(e, interceptorClass);
-         }
-      }
+      setInterceptors(config);
 
-      for (String interceptorClass : config.getOutgoingInterceptorClassNames())
-      {
-         try
-         {
-            outgoingInterceptors.add((Interceptor) safeInitNewInstance(interceptorClass));
-         }
-         catch (Exception e)
-         {
-            HornetQServerLogger.LOGGER.errorCreatingRemotingInterceptor(e, interceptorClass);
-         }
-      }
       this.managementService = managementService;
 
       this.scheduledThreadPool = scheduledThreadPool;
 
       CoreProtocolManagerFactory coreProtocolManagerFactory = new CoreProtocolManagerFactory();
       //i know there is only 1
+      this.flushExecutor = flushExecutor;
+
       HornetQServerLogger.LOGGER.addingProtocolSupport(coreProtocolManagerFactory.getProtocols()[0]);
       this.protocolMap.put(coreProtocolManagerFactory.getProtocols()[0],
                            coreProtocolManagerFactory.createProtocolManager(server, incomingInterceptors, outgoingInterceptors));
@@ -188,6 +181,23 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle
 
    // RemotingService implementation -------------------------------
 
+   private void setInterceptors(Configuration configuration)
+   {
+      addReflectivelyInstantiatedInterceptors(configuration.getIncomingInterceptorClassNames(), incomingInterceptors);
+      addReflectivelyInstantiatedInterceptors(configuration.getOutgoingInterceptorClassNames(), outgoingInterceptors);
+      incomingInterceptors.addAll(serviceRegistry.getIncomingInterceptors());
+      outgoingInterceptors.addAll(serviceRegistry.getOutgoingInterceptors());
+   }
+
+   private void addReflectivelyInstantiatedInterceptors(List<String> classNames, List<Interceptor> interceptors)
+   {
+      for (String className : classNames)
+      {
+         Interceptor interceptor = ((Interceptor) safeInitNewInstance(className));
+         interceptors.add(interceptor);
+      }
+   }
+
    public synchronized void start() throws Exception
    {
       if (started)
@@ -463,6 +473,23 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle
       return started;
    }
 
+
+   private RemotingConnection getConnection(final Object remotingConnectionID)
+   {
+      ConnectionEntry entry = connections.get(remotingConnectionID);
+
+      if (entry != null)
+      {
+         return entry.connection;
+      }
+      else
+      {
+         HornetQServerLogger.LOGGER.errorRemovingConnection();
+
+         return null;
+      }
+   }
+
    public RemotingConnection removeConnection(final Object remotingConnectionID)
    {
       ConnectionEntry entry = connections.remove(remotingConnectionID);
@@ -689,7 +716,7 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle
 
                for (ConnectionEntry entry : connections.values())
                {
-                  RemotingConnection conn = entry.connection;
+                  final RemotingConnection conn = entry.connection;
 
                   boolean flush = true;
 
@@ -712,16 +739,34 @@ public class RemotingServiceImpl implements RemotingService, ConnectionLifeCycle
 
                   if (flush)
                   {
-                     conn.flush();
+                     flushExecutor.execute(new Runnable()
+                     {
+                        public void run()
+                        {
+                           try
+                           {
+                              // this is using a different thread
+                              // as if anything wrong happens on flush
+                              // failure detection could be affected
+                              conn.flush();
+                           }
+                           catch (Throwable e)
+                           {
+                              HornetQServerLogger.LOGGER.warn(e.getMessage(), e);
+                           }
+
+                        }
+                     });
                   }
                }
 
                for (Object id : idsToRemove)
                {
-                  RemotingConnection conn = removeConnection(id);
+                  RemotingConnection conn = getConnection(id);
                   if (conn != null)
                   {
                      conn.fail(HornetQMessageBundle.BUNDLE.clientExited(conn.getRemoteAddress()));
+                     removeConnection(id);
                   }
                }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedJournal.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedJournal.java b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedJournal.java
index e6c539e..94dcc29 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedJournal.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedJournal.java
@@ -30,12 +30,12 @@ import org.hornetq.core.persistence.OperationContext;
 import org.hornetq.core.replication.ReplicationManager.ADD_OPERATION_TYPE;
 
 /**
- * Used by the {@link JournalStorageManager} to replicate journal calls.
+ * Used by the {@link org.hornetq.core.persistence.impl.journal.JournalStorageManager} to replicate journal calls.
  * <p>
  * This class wraps a {@link ReplicationManager} and the local {@link Journal}. Every call will be
  * relayed to both instances.
  * @author <mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- * @see JournalStorageManager
+ * @see org.hornetq.core.persistence.impl.journal.JournalStorageManager
  */
 public class ReplicatedJournal implements Journal
 {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedLargeMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedLargeMessage.java b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedLargeMessage.java
index 21721e8..52404a8 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedLargeMessage.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicatedLargeMessage.java
@@ -15,32 +15,34 @@
  */
 package org.hornetq.core.replication;
 
+import org.hornetq.api.core.Message;
+
 /**
- * {@link LargeServerMessage} methods used by the {@link ReplicationEndpoint}.
+ * {@link org.hornetq.core.server.LargeServerMessage} methods used by the {@link ReplicationEndpoint}.
  * <p/>
- * In practice a subset of the methods necessary to have a {@link LargeServerMessage}
+ * In practice a subset of the methods necessary to have a {@link org.hornetq.core.server.LargeServerMessage}
  *
- * @see LargeServerMessageInSync
+ * @see org.hornetq.core.persistence.impl.journal.LargeServerMessageInSync
  */
 public interface ReplicatedLargeMessage
 {
    /**
-    * @see LargeServerMessage#setDurable(boolean)
+    * @see org.hornetq.core.server.LargeServerMessage#setDurable(boolean)
     */
-   void setDurable(boolean b);
+   Message setDurable(boolean b);
 
    /**
-    * @see LargeServerMessage#setMessageID(long)
+    * @see org.hornetq.core.server.LargeServerMessage#setMessageID(long)
     */
-   void setMessageID(long id);
+   Message setMessageID(long id);
 
    /**
-    * @see LargeServerMessage#releaseResources()
+    * @see org.hornetq.core.server.LargeServerMessage#releaseResources()
     */
    void releaseResources();
 
    /**
-    * @see LargeServerMessage#deleteFile()
+    * @see org.hornetq.core.server.LargeServerMessage#deleteFile()
     */
    void deleteFile() throws Exception;
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationEndpoint.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationEndpoint.java b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationEndpoint.java
index c667fa3..dd68e36 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationEndpoint.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationEndpoint.java
@@ -74,6 +74,7 @@ import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.ServerMessage;
 import org.hornetq.core.server.cluster.qourum.SharedNothingBackupQuorum;
 import org.hornetq.core.server.impl.HornetQServerImpl;
+import org.hornetq.core.server.impl.SharedNothingBackupActivation;
 
 /**
  * Handles all the synchronization necessary for replication on the backup side (that is the
@@ -88,6 +89,7 @@ public final class ReplicationEndpoint implements ChannelHandler, HornetQCompone
    private final IOCriticalErrorListener criticalErrorListener;
    private final HornetQServerImpl server;
    private final boolean wantedFailBack;
+   private final SharedNothingBackupActivation activation;
    private final boolean noSync = false;
    private Channel channel;
 
@@ -125,11 +127,12 @@ public final class ReplicationEndpoint implements ChannelHandler, HornetQCompone
 
    // Constructors --------------------------------------------------
    public ReplicationEndpoint(final HornetQServerImpl server, IOCriticalErrorListener criticalErrorListener,
-                              boolean wantedFailBack)
+                              boolean wantedFailBack, SharedNothingBackupActivation activation)
    {
       this.server = server;
       this.criticalErrorListener = criticalErrorListener;
       this.wantedFailBack = wantedFailBack;
+      this.activation = activation;
    }
 
    // Public --------------------------------------------------------
@@ -260,7 +263,7 @@ public final class ReplicationEndpoint implements ChannelHandler, HornetQCompone
     */
    private void handleLiveStopping(ReplicationLiveIsStoppingMessage packet) throws HornetQException
    {
-      server.remoteFailOver(packet.isFinalMessage());
+      activation.remoteFailOver(packet.isFinalMessage());
    }
 
    public boolean isStarted()
@@ -394,7 +397,7 @@ public final class ReplicationEndpoint implements ChannelHandler, HornetQCompone
 
    public void compareJournalInformation(final JournalLoadInformation[] journalInformation) throws HornetQException
    {
-      if (!server.isRemoteBackupUpToDate())
+      if (!activation.isRemoteBackupUpToDate())
       {
          throw HornetQMessageBundle.BUNDLE.journalsNotInSync();
       }
@@ -481,7 +484,7 @@ public final class ReplicationEndpoint implements ChannelHandler, HornetQCompone
 
       journalsHolder = null;
       backupQuorum.liveIDSet(liveID);
-      server.setRemoteBackupUpToDate();
+      activation.setRemoteBackupUpToDate();
       HornetQServerLogger.LOGGER.backupServerSynched(server);
       return;
    }
@@ -555,7 +558,7 @@ public final class ReplicationEndpoint implements ChannelHandler, HornetQCompone
     */
    private void handleStartReplicationSynchronization(final ReplicationStartSyncMessage packet) throws Exception
    {
-      if (server.isRemoteBackupUpToDate())
+      if (activation.isRemoteBackupUpToDate())
       {
          throw HornetQMessageBundle.BUNDLE.replicationBackupUpToDate();
       }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationManager.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationManager.java b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationManager.java
index 42f3872..cd43ffa 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationManager.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/replication/ReplicationManager.java
@@ -16,11 +16,8 @@ import java.io.FileInputStream;
 import java.nio.ByteBuffer;
 import java.nio.channels.FileChannel;
 import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.Map;
-import java.util.Map.Entry;
 import java.util.Queue;
 import java.util.Set;
 import java.util.concurrent.ConcurrentLinkedQueue;
@@ -112,8 +109,6 @@ public final class ReplicationManager implements HornetQComponent
    private volatile boolean enabled;
 
    private final Object replicationLock = new Object();
-   private final Object largeMessageSyncGuard = new Object();
-   private final HashMap<Long, Pair<String, Long>> largeMessagesToSync = new HashMap<Long, Pair<String, Long>>();
 
    private final Queue<OperationContext> pendingTokens = new ConcurrentLinkedQueue<OperationContext>();
 
@@ -506,22 +501,6 @@ public final class ReplicationManager implements HornetQComponent
       }
    }
 
-   /**
-    * @return
-    */
-   public Map.Entry<Long, Pair<String, Long>> getNextLargeMessageToSync()
-   {
-      Iterator<Entry<Long, Pair<String, Long>>> iter = largeMessagesToSync.entrySet().iterator();
-      if (!iter.hasNext())
-      {
-         return null;
-      }
-
-      Entry<Long, Pair<String, Long>> entry = iter.next();
-      iter.remove();
-      return entry;
-   }
-
    public void syncLargeMessageFile(SequentialFile file, long size, long id) throws Exception
    {
       if (enabled)
@@ -563,7 +542,10 @@ public final class ReplicationManager implements HornetQComponent
             final FileChannel channel = fis.getChannel();
             try
             {
-               final ByteBuffer buffer = ByteBuffer.allocate(1 << 17);
+               // We can afford having a single buffer here for this entire loop
+               // because sendReplicatePacket will encode the packet as a NettyBuffer
+               // through HornetQBuffer class leaving this buffer free to be reused on the next copy
+               final ByteBuffer buffer = ByteBuffer.allocate(1 << 17); // 1 << 17 == 131072 == 128 * 1024
                while (true)
                {
                   buffer.clear();
@@ -649,8 +631,7 @@ public final class ReplicationManager implements HornetQComponent
    public void sendLargeMessageIdListMessage(Map<Long, Pair<String, Long>> largeMessages)
    {
       ArrayList<Long> idsToSend;
-      largeMessagesToSync.putAll(largeMessages);
-      idsToSend = new ArrayList<Long>(largeMessagesToSync.keySet());
+      idsToSend = new ArrayList<Long>(largeMessages.keySet());
 
       if (enabled)
          sendReplicatePacket(new ReplicationStartSyncMessage(idsToSend));

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/security/SecurityStore.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/security/SecurityStore.java b/hornetq-server/src/main/java/org/hornetq/core/security/SecurityStore.java
index 01a8f17..c7325ca 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/security/SecurityStore.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/security/SecurityStore.java
@@ -26,5 +26,7 @@ public interface SecurityStore
 
    void check(SimpleString address, CheckType checkType, ServerSession session) throws Exception;
 
+   boolean isSecurityEnabled();
+
    void stop();
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/security/impl/SecurityStoreImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/security/impl/SecurityStoreImpl.java b/hornetq-server/src/main/java/org/hornetq/core/security/impl/SecurityStoreImpl.java
index a0a4807..d260ba3 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/security/impl/SecurityStoreImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/security/impl/SecurityStoreImpl.java
@@ -12,15 +12,13 @@
  */
 package org.hornetq.core.security.impl;
 
-import static org.hornetq.api.core.management.NotificationType.SECURITY_AUTHENTICATION_VIOLATION;
-
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.security.CheckType;
 import org.hornetq.core.security.Role;
 import org.hornetq.core.security.SecurityStore;
@@ -98,6 +96,12 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC
 
    // SecurityManager implementation --------------------------------
 
+   @Override
+   public boolean isSecurityEnabled()
+   {
+      return securityEnabled;
+   }
+
    public void stop()
    {
       securityRepository.unRegisterListener(this);
@@ -137,7 +141,7 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC
 
                props.putSimpleStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(user));
 
-               Notification notification = new Notification(null, SECURITY_AUTHENTICATION_VIOLATION, props);
+               Notification notification = new Notification(null, CoreNotificationType.SECURITY_AUTHENTICATION_VIOLATION, props);
 
                notificationService.sendNotification(notification);
             }
@@ -183,7 +187,7 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC
                props.putSimpleStringProperty(ManagementHelper.HDR_CHECK_TYPE, new SimpleString(checkType.toString()));
                props.putSimpleStringProperty(ManagementHelper.HDR_USER, SimpleString.toSimpleString(user));
 
-               Notification notification = new Notification(null, NotificationType.SECURITY_PERMISSION_VIOLATION, props);
+               Notification notification = new Notification(null, CoreNotificationType.SECURITY_PERMISSION_VIOLATION, props);
 
                notificationService.sendNotification(notification);
             }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/ActivateCallback.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/ActivateCallback.java b/hornetq-server/src/main/java/org/hornetq/core/server/ActivateCallback.java
index 1f10891..361bb3a 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/ActivateCallback.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/ActivateCallback.java
@@ -21,9 +21,24 @@ package org.hornetq.core.server;
  */
 public interface ActivateCallback
 {
+   /*
+    * this is called before any services are started when the server first initialised
+    */
    void preActivate();
 
+   /*
+    * this is called after most of the services have been started but before any cluster resources or JMS resources have been
+    */
    void activated();
 
+   /*
+    * this is called when the server is stopping, after any network resources and clients are closed but before the rest
+    * of the resources
+    */
    void deActivate();
+
+   /*
+    * this is called when all resources have been started including any JMS resources
+    */
+   void activationComplete();
 }


[31/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscription.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscription.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscription.java
new file mode 100644
index 0000000..0eb84a2
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscription.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.jms.InvalidSelectorException;
+import javax.management.ObjectName;
+
+import org.apache.activemq.broker.region.MessageReference;
+import org.apache.activemq.command.ActiveMQDestination;
+import org.apache.activemq.command.ConsumerInfo;
+import org.apache.activemq.command.MessageAck;
+import org.apache.activemq.command.MessageDispatchNotification;
+import org.apache.activemq.command.MessagePull;
+import org.apache.activemq.command.Response;
+import org.apache.activemq.filter.MessageEvaluationContext;
+
+public interface AMQSubscription extends AMQSubscriptionRecovery
+{
+
+   /**
+    * Used to add messages that match the subscription.
+    * @param node
+    * @throws Exception
+    * @throws InterruptedException
+    * @throws IOException
+    */
+   void add(MessageReference node) throws Exception;
+
+   /**
+    * Used when client acknowledge receipt of dispatched message.
+    * @throws IOException
+    * @throws Exception
+    */
+   void acknowledge(AMQConnectionContext context, final MessageAck ack) throws Exception;
+
+   /**
+    * Allows a consumer to pull a message on demand
+    */
+   Response pullMessage(AMQConnectionContext context, MessagePull pull) throws Exception;
+
+   /**
+    * Returns true if this subscription is a Wildcard subscription.
+    * @return true if wildcard subscription.
+    */
+   boolean isWildcard();
+
+   /**
+    * Is the subscription interested in the message?
+    * @param node
+    * @param context
+    * @return
+    * @throws IOException
+    */
+   boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException;
+
+   /**
+    * Is the subscription interested in messages in the destination?
+    * @param destination
+    * @return
+    */
+   boolean matches(ActiveMQDestination destination);
+
+   /**
+    * The subscription will be receiving messages from the destination.
+    * @param context
+    * @param destination
+    * @throws Exception
+    */
+   void add(AMQConnectionContext context, AMQDestination destination) throws Exception;
+
+   /**
+    * The subscription will be no longer be receiving messages from the destination.
+    * @param context
+    * @param destination
+    * @return a list of un-acked messages that were added to the subscription.
+    */
+   List<MessageReference> remove(AMQConnectionContext context, AMQDestination destination) throws Exception;
+
+   /**
+    * The ConsumerInfo object that created the subscription.
+    */
+   ConsumerInfo getConsumerInfo();
+
+   /**
+    * The subscription should release as may references as it can to help the garbage collector
+    * reclaim memory.
+    */
+   void gc();
+
+   /**
+    * Used by a Slave Broker to update dispatch infomation
+    * @param mdn
+    * @throws Exception
+    */
+   void processMessageDispatchNotification(MessageDispatchNotification  mdn) throws Exception;
+
+   /**
+    * @return number of messages pending delivery
+    */
+   int getPendingQueueSize();
+
+   /**
+    * @return number of messages dispatched to the client
+    */
+   int getDispatchedQueueSize();
+
+   /**
+    * @return number of messages dispatched to the client
+    */
+   long getDispatchedCounter();
+
+   /**
+    * @return number of messages that matched the subscription
+    */
+   long getEnqueueCounter();
+
+   /**
+    * @return number of messages queued by the client
+    */
+   long getDequeueCounter();
+
+   /**
+    * @return the JMS selector on the current subscription
+    */
+   String getSelector();
+
+   /**
+    * Attempts to change the current active selector on the subscription.
+    * This operation is not supported for persistent topics.
+    */
+   void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException;
+
+   /**
+    * @return the JMX object name that this subscription was registered as if applicable
+    */
+   ObjectName getObjectName();
+
+   /**
+    * Set when the subscription is registered in JMX
+    */
+   void setObjectName(ObjectName objectName);
+
+   /**
+    * @return true when 60% or more room is left for dispatching messages
+    */
+   boolean isLowWaterMark();
+
+   /**
+    * @return true when 10% or less room is left for dispatching messages
+    */
+   boolean isHighWaterMark();
+
+   /**
+    * @return true if there is no space to dispatch messages
+    */
+   boolean isFull();
+
+   /**
+    * inform the MessageConsumer on the client to change it's prefetch
+    * @param newPrefetch
+    */
+   void updateConsumerPrefetch(int newPrefetch);
+
+   /**
+    * Called when the subscription is destroyed.
+    */
+   void destroy();
+
+   /**
+    * @return the prefetch size that is configured for the subscription
+    */
+   int getPrefetchSize();
+
+   /**
+    * @return the number of messages awaiting acknowledgement
+    */
+   int getInFlightSize();
+
+   /**
+    * @return the in flight messages as a percentage of the prefetch size
+    */
+   int getInFlightUsage();
+
+   /**
+    * Informs the Broker if the subscription needs to intervention to recover it's state
+    * e.g. DurableTopicSubscriber may do
+    * @see org.apache.activemq.broker.region.cursors.PendingMessageCursor
+    * @return true if recovery required
+    */
+   boolean isRecoveryRequired();
+
+   /**
+    * @return true if a browser
+    */
+   boolean isBrowser();
+
+   /**
+    * @return the number of messages this subscription can accept before its full
+    */
+   int countBeforeFull();
+
+   AMQConnectionContext getContext();
+
+   int getCursorMemoryHighWaterMark();
+
+   void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark);
+
+   boolean isSlowConsumer();
+
+   void unmatched(MessageReference node) throws IOException;
+
+   /**
+    * Returns the time since the last Ack message was received by this subscription.
+    *
+    * If there has never been an ack this value should be set to the creation time of the
+    * subscription.
+    *
+    * @return time of last received Ack message or Subscription create time if no Acks.
+    */
+   long getTimeOfLastMessageAck();
+
+   long  getConsumedCount();
+
+   void incrementConsumedCount();
+
+   void resetConsumedCount();
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscriptionRecovery.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscriptionRecovery.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscriptionRecovery.java
new file mode 100644
index 0000000..7cf1e84
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQSubscriptionRecovery.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.broker.region.MessageReference;
+import org.apache.activemq.command.ActiveMQDestination;
+
+/**
+ * An interface for recoverying transient messages held by the broker for
+ * retractive recovery for subscribers
+ *
+ *
+ */
+public interface AMQSubscriptionRecovery
+{
+
+   /**
+    * Add a message to the SubscriptionRecovery
+    *
+    * @param context
+    * @param message
+    * @return true if the message is accepted
+    * @throws Exception
+    */
+   boolean addRecoveredMessage(AMQConnectionContext context, MessageReference message) throws Exception;
+
+   /**
+    * @return the Destination associated with this Subscription
+    */
+   ActiveMQDestination getActiveMQDestination();
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransaction.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransaction.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransaction.java
new file mode 100644
index 0000000..1a477b9
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransaction.java
@@ -0,0 +1,249 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+
+import javax.transaction.xa.XAException;
+
+import org.apache.activemq.command.TransactionId;
+import org.apache.activemq.transaction.Synchronization;
+import org.slf4j.Logger;
+
+public abstract class AMQTransaction
+{
+   public static final byte START_STATE = 0; // can go to: 1,2,3
+   public static final byte IN_USE_STATE = 1; // can go to: 2,3
+   public static final byte PREPARED_STATE = 2; // can go to: 3
+   public static final byte FINISHED_STATE = 3;
+   boolean committed = false;
+
+   private final ArrayList<Synchronization> synchronizations = new ArrayList<Synchronization>();
+   private byte state = START_STATE;
+   protected FutureTask<?> preCommitTask = new FutureTask<Object>(
+         new Callable<Object>()
+         {
+            public Object call() throws Exception
+            {
+               doPreCommit();
+               return null;
+            }
+         });
+   protected FutureTask<?> postCommitTask = new FutureTask<Object>(
+         new Callable<Object>()
+         {
+            public Object call() throws Exception
+            {
+               doPostCommit();
+               return null;
+            }
+         });
+
+   public byte getState()
+   {
+      return state;
+   }
+
+   public void setState(byte state)
+   {
+      this.state = state;
+   }
+
+   public boolean isCommitted()
+   {
+      return committed;
+   }
+
+   public void setCommitted(boolean committed)
+   {
+      this.committed = committed;
+   }
+
+   public void addSynchronization(Synchronization r)
+   {
+      synchronizations.add(r);
+      if (state == START_STATE)
+      {
+         state = IN_USE_STATE;
+      }
+   }
+
+   public Synchronization findMatching(Synchronization r)
+   {
+      int existing = synchronizations.indexOf(r);
+      if (existing != -1)
+      {
+         return synchronizations.get(existing);
+      }
+      return null;
+   }
+
+   public void removeSynchronization(Synchronization r)
+   {
+      synchronizations.remove(r);
+   }
+
+   public void prePrepare() throws Exception
+   {
+
+      // Is it ok to call prepare now given the state of the
+      // transaction?
+      switch (state)
+      {
+         case START_STATE:
+         case IN_USE_STATE:
+            break;
+         default:
+            XAException xae = new XAException("Prepare cannot be called now.");
+            xae.errorCode = XAException.XAER_PROTO;
+            throw xae;
+      }
+
+      // // Run the prePrepareTasks
+      // for (Iterator iter = prePrepareTasks.iterator(); iter.hasNext();) {
+      // Callback r = (Callback) iter.next();
+      // r.execute();
+      // }
+   }
+
+   protected void fireBeforeCommit() throws Exception
+   {
+      for (Iterator<Synchronization> iter = synchronizations.iterator(); iter
+            .hasNext();)
+      {
+         Synchronization s = iter.next();
+         s.beforeCommit();
+      }
+   }
+
+   protected void fireAfterCommit() throws Exception
+   {
+      for (Iterator<Synchronization> iter = synchronizations.iterator(); iter
+            .hasNext();)
+      {
+         Synchronization s = iter.next();
+         s.afterCommit();
+      }
+   }
+
+   public void fireAfterRollback() throws Exception
+   {
+      Collections.reverse(synchronizations);
+      for (Iterator<Synchronization> iter = synchronizations.iterator(); iter
+            .hasNext();)
+      {
+         Synchronization s = iter.next();
+         s.afterRollback();
+      }
+   }
+
+   @Override
+   public String toString()
+   {
+      return "Local-" + getTransactionId() + "[synchronizations="
+            + synchronizations + "]";
+   }
+
+   public abstract void commit(boolean onePhase) throws XAException,
+         IOException;
+
+   public abstract void rollback() throws XAException, IOException;
+
+   public abstract int prepare() throws XAException, IOException;
+
+   public abstract TransactionId getTransactionId();
+
+   public abstract Logger getLog();
+
+   public boolean isPrepared()
+   {
+      return getState() == PREPARED_STATE;
+   }
+
+   public int size()
+   {
+      return synchronizations.size();
+   }
+
+   protected void waitPostCommitDone(FutureTask<?> postCommitTask) throws XAException, IOException
+   {
+      try
+      {
+         postCommitTask.get();
+      }
+      catch (InterruptedException e)
+      {
+         throw new InterruptedIOException(e.toString());
+      }
+      catch (ExecutionException e)
+      {
+         Throwable t = e.getCause();
+         if (t instanceof XAException)
+         {
+            throw (XAException) t;
+         }
+         else if (t instanceof IOException)
+         {
+            throw (IOException) t;
+         }
+         else
+         {
+            throw new XAException(e.toString());
+         }
+      }
+   }
+
+   protected void doPreCommit() throws XAException
+   {
+      try
+      {
+         fireBeforeCommit();
+      }
+      catch (Throwable e)
+      {
+         // I guess this could happen. Post commit task failed
+         // to execute properly.
+         getLog().warn("PRE COMMIT FAILED: ", e);
+         XAException xae = new XAException("PRE COMMIT FAILED");
+         xae.errorCode = XAException.XAER_RMERR;
+         xae.initCause(e);
+         throw xae;
+      }
+   }
+
+   protected void doPostCommit() throws XAException
+   {
+      try
+      {
+         setCommitted(true);
+         fireAfterCommit();
+      }
+      catch (Throwable e)
+      {
+         // I guess this could happen. Post commit task failed
+         // to execute properly.
+         getLog().warn("POST COMMIT FAILED: ", e);
+         XAException xae = new XAException("POST COMMIT FAILED");
+         xae.errorCode = XAException.XAER_RMERR;
+         xae.initCause(e);
+         throw xae;
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransactionFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransactionFactory.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransactionFactory.java
new file mode 100644
index 0000000..5632a63
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransactionFactory.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import javax.transaction.xa.Xid;
+
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.protocol.openwire.AMQTransactionImpl;
+import org.hornetq.core.transaction.Transaction;
+import org.hornetq.core.transaction.TransactionFactory;
+
+public class AMQTransactionFactory implements TransactionFactory
+{
+   @Override
+   public Transaction newTransaction(Xid xid, StorageManager storageManager, int timeoutSeconds)
+   {
+      return new AMQTransactionImpl(xid, storageManager, timeoutSeconds);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionState.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionState.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionState.java
new file mode 100644
index 0000000..be11e5b
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionState.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.activemq.command.ConnectionInfo;
+import org.apache.activemq.state.ConnectionState;
+import org.hornetq.core.protocol.openwire.OpenWireConnection;
+
+/**
+ * @See org.apache.activemq.broker.TransportConnectionState
+ * @author howard
+ *
+ */
+public class AMQTransportConnectionState extends ConnectionState
+{
+
+   private AMQConnectionContext context;
+   private OpenWireConnection connection;
+   private AtomicInteger referenceCounter = new AtomicInteger();
+   private final Object connectionMutex = new Object();
+
+   public AMQTransportConnectionState(ConnectionInfo info,
+         OpenWireConnection transportConnection)
+   {
+      super(info);
+      connection = transportConnection;
+   }
+
+   public AMQConnectionContext getContext()
+   {
+      return context;
+   }
+
+   public OpenWireConnection getConnection()
+   {
+      return connection;
+   }
+
+   public void setContext(AMQConnectionContext context)
+   {
+      this.context = context;
+   }
+
+   public void setConnection(OpenWireConnection connection)
+   {
+      this.connection = connection;
+   }
+
+   public int incrementReference()
+   {
+      return referenceCounter.incrementAndGet();
+   }
+
+   public int decrementReference()
+   {
+      return referenceCounter.decrementAndGet();
+   }
+
+   public AtomicInteger getReferenceCounter()
+   {
+      return referenceCounter;
+   }
+
+   public void setReferenceCounter(AtomicInteger referenceCounter)
+   {
+      this.referenceCounter = referenceCounter;
+   }
+
+   public Object getConnectionMutex()
+   {
+      return connectionMutex;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionStateRegister.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionStateRegister.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionStateRegister.java
new file mode 100644
index 0000000..d0e68f5
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/AMQTransportConnectionStateRegister.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.activemq.command.ConnectionId;
+import org.apache.activemq.command.ConsumerId;
+import org.apache.activemq.command.ProducerId;
+import org.apache.activemq.command.SessionId;
+
+/**
+ * What's the purpose of this?
+ *
+ * @author howard
+ *
+ */
+public interface AMQTransportConnectionStateRegister
+{
+   AMQTransportConnectionState registerConnectionState(ConnectionId connectionId,
+         AMQTransportConnectionState state);
+
+   AMQTransportConnectionState unregisterConnectionState(ConnectionId connectionId);
+
+   List<AMQTransportConnectionState> listConnectionStates();
+
+   Map<ConnectionId, AMQTransportConnectionState> mapStates();
+
+   AMQTransportConnectionState lookupConnectionState(String connectionId);
+
+   AMQTransportConnectionState lookupConnectionState(ConsumerId id);
+
+   AMQTransportConnectionState lookupConnectionState(ProducerId id);
+
+   AMQTransportConnectionState lookupConnectionState(SessionId id);
+
+   AMQTransportConnectionState lookupConnectionState(ConnectionId connectionId);
+
+   boolean isEmpty();
+
+   boolean doesHandleMultipleConnectionStates();
+
+   void intialize(AMQTransportConnectionStateRegister other);
+
+   void clear();
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/BrowserListener.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/BrowserListener.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/BrowserListener.java
new file mode 100644
index 0000000..12eaf23
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/BrowserListener.java
@@ -0,0 +1,18 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+interface BrowserListener
+{
+   void browseFinished();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/MessageInfo.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/MessageInfo.java b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/MessageInfo.java
new file mode 100644
index 0000000..6315d86
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/java/org/hornetq/core/protocol/openwire/amq/MessageInfo.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.protocol.openwire.amq;
+
+import org.apache.activemq.command.MessageId;
+
+public class MessageInfo
+{
+   public MessageId amqId;
+   public long nativeId;
+   public int size;
+   //mark message that is acked within a local tx
+   public boolean localAcked;
+
+   public MessageInfo(MessageId amqId, long nativeId, int size)
+   {
+      this.amqId = amqId;
+      this.nativeId = nativeId;
+      this.size = size;
+   }
+
+   @Override
+   public String toString()
+   {
+      return "native mid: " + this.nativeId + " amqId: " + amqId + " local acked: " + localAcked;
+   }
+
+   public void setLocalAcked(boolean ack)
+   {
+      localAcked = ack;
+   }
+
+   public boolean isLocalAcked()
+   {
+      return localAcked;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-openwire-protocol/src/main/resources/META-INF/services/org.hornetq.spi.core.protocol.ProtocolManagerFactory
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-openwire-protocol/src/main/resources/META-INF/services/org.hornetq.spi.core.protocol.ProtocolManagerFactory b/hornetq-protocols/hornetq-openwire-protocol/src/main/resources/META-INF/services/org.hornetq.spi.core.protocol.ProtocolManagerFactory
new file mode 100644
index 0000000..fd06ac6
--- /dev/null
+++ b/hornetq-protocols/hornetq-openwire-protocol/src/main/resources/META-INF/services/org.hornetq.spi.core.protocol.ProtocolManagerFactory
@@ -0,0 +1 @@
+org.hornetq.core.protocol.openwire.OpenWireProtocolManagerFactory

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/pom.xml b/hornetq-protocols/hornetq-proton-plug/pom.xml
new file mode 100644
index 0000000..98ece12
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/pom.xml
@@ -0,0 +1,80 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+   <parent>
+      <artifactId>hornetq-protocols</artifactId>
+      <groupId>org.hornetq</groupId>
+      <version>2.5.0-SNAPSHOT</version>
+   </parent>
+   <modelVersion>4.0.0</modelVersion>
+
+   <artifactId>hornetq-proton-plug</artifactId>
+
+   <properties>
+      <hornetq.basedir>${project.basedir}/../..</hornetq.basedir>
+   </properties>
+
+   <dependencies>
+      <!-- JMS Client because of some Convertions that are done -->
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-jms-client</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-core-client</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.jboss.logging</groupId>
+         <artifactId>jboss-logging-processor</artifactId>
+      </dependency>
+
+      <!--
+          JBoss Logging
+      -->
+      <dependency>
+         <groupId>org.jboss.logging</groupId>
+         <artifactId>jboss-logging</artifactId>
+      </dependency>
+      <dependency>
+         <groupId>org.hornetq</groupId>
+         <artifactId>hornetq-server</artifactId>
+         <version>${project.version}</version>
+      </dependency>
+      <dependency>
+         <groupId>org.apache.qpid</groupId>
+         <artifactId>proton-j</artifactId>
+      </dependency>
+
+      <dependency>
+         <groupId>org.apache.qpid</groupId>
+         <artifactId>qpid-client</artifactId>
+         <version>0.24</version>
+         <scope>test</scope>
+      </dependency>
+      <dependency>
+         <groupId>org.apache.qpid</groupId>
+         <artifactId>qpid-amqp-1-0-client-jms</artifactId>
+         <version>0.24</version>
+         <scope>test</scope>
+      </dependency>
+
+
+
+      <dependency>
+         <groupId>org.jboss.spec.javax.jms</groupId>
+         <artifactId>jboss-jms-api_2.0_spec</artifactId>
+         <scope>provided</scope>
+      </dependency>
+      <dependency>
+         <groupId>junit</groupId>
+         <artifactId>junit</artifactId>
+         <scope>test</scope>
+      </dependency>
+
+
+   </dependencies>
+
+
+</project>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java
new file mode 100644
index 0000000..5678a38
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientConnectionContext.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+/**
+ * This is valid only on a client connection.
+ *
+ * @author Clebert Suconic
+ */
+
+public interface AMQPClientConnectionContext extends AMQPConnectionContext
+{
+   /**
+    * This will send an open and block for its return on AMQP protocol.
+    *
+    * @throws Exception
+    */
+   void clientOpen(ClientSASL sasl) throws Exception;
+
+   AMQPClientSessionContext createClientSession() throws HornetQAMQPException;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java
new file mode 100644
index 0000000..4e94a73
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientReceiverContext.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.qpid.proton.message.ProtonJMessage;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface AMQPClientReceiverContext
+{
+   ProtonJMessage receiveMessage(int time, TimeUnit unit) throws Exception;
+
+   void flow(int credits);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java
new file mode 100644
index 0000000..1fb5375
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSenderContext.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import org.apache.qpid.proton.message.ProtonJMessage;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface AMQPClientSenderContext
+{
+   void send(ProtonJMessage message);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java
new file mode 100644
index 0000000..45cbaad
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPClientSessionContext.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface AMQPClientSessionContext extends AMQPSessionContext
+{
+   AMQPClientSenderContext createSender(String address, boolean preSettled) throws HornetQAMQPException;
+
+   AMQPClientReceiverContext createReceiver(String address) throws HornetQAMQPException;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java
new file mode 100644
index 0000000..d6a1b5a
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionCallback.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import io.netty.buffer.ByteBuf;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface AMQPConnectionCallback
+{
+   void close();
+
+   /**
+    * this is called when bytes are available to be sent to the client.
+    * you have to callback {@link org.proton.plug.AMQPConnectionContext#outputDone(int)} after you're done with this buffer
+    *
+    * @param bytes
+    */
+   void onTransport(ByteBuf bytes, AMQPConnectionContext connection);
+
+   AMQPSessionCallback createSessionCallback(AMQPConnectionContext connection);
+
+   void setConnection(AMQPConnectionContext connection);
+
+   AMQPConnectionContext getConnection();
+
+   ServerSASL[] getSASLMechnisms();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java
new file mode 100644
index 0000000..4969b10
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContext.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import io.netty.buffer.ByteBuf;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface AMQPConnectionContext
+{
+
+   void close();
+
+   Object getLock();
+
+   boolean checkDataReceived();
+
+   long getCreationTime();
+
+   SASLResult getSASLResult();
+
+   /**
+    * Even though we are currently always sending packets asynchronsouly
+    * we have a possibility to start trusting on the network flow control
+    * and always sync on the send of the packet
+    *
+    * This is for future use and should be kept returning false.
+    *
+    * We will have to do some testing before we make this return true
+    * @return
+    */
+   boolean isSyncOnFlush();
+
+   int capacity();
+
+   /**
+    * This is for the Remoting layer to push bytes on the AMQP Connection
+    * The buffer readerIndex should be at the latest read byte after this method is called
+    *
+    * @param buffer
+    * @return
+    */
+   void inputBuffer(ByteBuf buffer);
+
+   void flush();
+
+   /**
+    * To be called when the bytes were sent down the stream (flushed on the socket for example)
+    *
+    * @param numberOfBytes
+    */
+   void outputDone(int numberOfBytes);
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java
new file mode 100644
index 0000000..4f0b127
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPConnectionContextFactory.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public abstract class AMQPConnectionContextFactory
+{
+   /**
+    * @return
+    */
+   public abstract AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java
new file mode 100644
index 0000000..62846a8
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPServerConnectionContext.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface AMQPServerConnectionContext extends AMQPConnectionContext
+{
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java
new file mode 100644
index 0000000..10933a5
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionCallback.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.qpid.proton.amqp.Binary;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.proton.plug.context.ProtonPlugSender;
+
+/**
+ * These are methods where the Proton Plug component will call your server
+ *
+ * @author Clebert Suconic
+ */
+
+public interface AMQPSessionCallback
+{
+
+   void init(AMQPSessionContext session, SASLResult saslResult) throws Exception;
+
+   void start();
+
+   void onFlowConsumer(Object consumer, int credits);
+
+   Object createSender(ProtonPlugSender protonSender, String queue, String filer, boolean browserOnly) throws Exception;
+
+   void startSender(Object brokerConsumer) throws Exception;
+
+   void createTemporaryQueue(String queueName) throws Exception;
+
+   boolean queueQuery(String queueName) throws Exception;
+
+   void closeSender(Object brokerConsumer) throws Exception;
+
+   // This one can be a lot improved
+   ProtonJMessage encodeMessage(Object message, int deliveryCount) throws Exception;
+
+   Binary getCurrentTXID();
+
+   String tempQueueName();
+
+   void commitCurrentTX() throws Exception;
+
+   void rollbackCurrentTX() throws Exception;
+
+   void close() throws Exception;
+
+
+   void ack(Object brokerConsumer, Object message) throws Exception;
+
+   /**
+    * @param brokerConsumer
+    * @param message
+    * @param updateCounts   this identified if the cancel was because of a failure or just cleaning up the
+    *                       client's cache.
+    *                       in some implementations you could call this failed
+    */
+   void cancel(Object brokerConsumer, Object message, boolean updateCounts) throws Exception;
+
+
+   void resumeDelivery(Object consumer);
+
+
+   /**
+    * @param delivery
+    * @param address
+    * @param messageFormat
+    * @param messageEncoded a Heap Buffer ByteBuffer (safe to convert into byte[])
+    */
+   void serverSend(Receiver receiver, Delivery delivery, String address, int messageFormat, ByteBuf messageEncoded) throws Exception;
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java
new file mode 100644
index 0000000..2cc725d
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/AMQPSessionContext.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.engine.Sender;
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface AMQPSessionContext
+{
+   byte[] getTag();
+
+   void replaceTag(byte[] tag);
+
+   void close();
+
+   void removeSender(Sender sender) throws HornetQAMQPException;
+
+   void removeReceiver(Receiver receiver);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ClientSASL.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ClientSASL.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ClientSASL.java
new file mode 100644
index 0000000..ef3af34
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ClientSASL.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+/**
+ * @author Clebert Suconic
+ */
+public interface ClientSASL
+{
+   byte[] getBytes();
+
+   String getName();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/SASLResult.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/SASLResult.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/SASLResult.java
new file mode 100644
index 0000000..e4b697e
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/SASLResult.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface SASLResult
+{
+   String getUser();
+
+   boolean isSuccess();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ServerSASL.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ServerSASL.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ServerSASL.java
new file mode 100644
index 0000000..dbadaca
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/ServerSASL.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface ServerSASL
+{
+   String getName();
+
+   SASLResult processSASL(byte[] bytes);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java
new file mode 100644
index 0000000..45a3ef0
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractConnectionContext.java
@@ -0,0 +1,282 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.qpid.proton.engine.Connection;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Link;
+import org.apache.qpid.proton.engine.Session;
+import org.apache.qpid.proton.engine.Transport;
+import org.proton.plug.AMQPConnectionCallback;
+import org.proton.plug.AMQPConnectionContext;
+import org.proton.plug.SASLResult;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.handler.ProtonHandler;
+import org.proton.plug.handler.impl.DefaultEventHandler;
+import org.proton.plug.util.ByteUtil;
+import org.proton.plug.util.DebugInfo;
+
+/**
+ * Clebert Suconic
+ */
+public abstract class AbstractConnectionContext extends ProtonInitializable implements AMQPConnectionContext
+{
+
+
+   protected ProtonHandler handler = ProtonHandler.Factory.create();
+
+   protected AMQPConnectionCallback connectionCallback;
+
+   private final Map<Session, AbstractProtonSessionContext> sessions = new ConcurrentHashMap<>();
+
+
+   public AbstractConnectionContext(AMQPConnectionCallback connectionCallback)
+   {
+      this.connectionCallback = connectionCallback;
+      connectionCallback.setConnection(this);
+      handler.addEventHandler(new LocalListener());
+   }
+
+   public SASLResult getSASLResult()
+   {
+      return handler.getSASLResult();
+   }
+
+   @Override
+   public void inputBuffer(ByteBuf buffer)
+   {
+      if (DebugInfo.debug)
+      {
+         ByteUtil.debugFrame("Buffer Received ", buffer);
+      }
+
+      handler.inputBuffer(buffer);
+   }
+
+   public void destroy()
+   {
+      connectionCallback.close();
+   }
+
+   /**
+    * See comment at {@link org.proton.plug.AMQPConnectionContext#isSyncOnFlush()}
+    * @return
+    * @See {@link org.proton.plug.AMQPConnectionContext#isSyncOnFlush()}
+    */
+   public boolean isSyncOnFlush()
+   {
+      return false;
+   }
+
+
+   public Object getLock()
+   {
+      return handler.getLock();
+   }
+
+   @Override
+   public int capacity()
+   {
+      return handler.capacity();
+   }
+
+   @Override
+   public void outputDone(int bytes)
+   {
+      handler.outputDone(bytes);
+   }
+
+   public void flush()
+   {
+      handler.flush();
+   }
+
+   public void close()
+   {
+      handler.close();
+   }
+
+   protected AbstractProtonSessionContext getSessionExtension(Session realSession) throws HornetQAMQPException
+   {
+      AbstractProtonSessionContext sessionExtension = sessions.get(realSession);
+      if (sessionExtension == null)
+      {
+         // how this is possible? Log a warn here
+         sessionExtension = newSessionExtension(realSession);
+         realSession.setContext(sessionExtension);
+         sessions.put(realSession, sessionExtension);
+      }
+      return sessionExtension;
+   }
+
+   protected abstract void remoteLinkOpened(Link link) throws Exception;
+
+
+   protected abstract AbstractProtonSessionContext newSessionExtension(Session realSession) throws HornetQAMQPException;
+
+   @Override
+   public boolean checkDataReceived()
+   {
+      return handler.checkDataReceived();
+   }
+
+   @Override
+   public long getCreationTime()
+   {
+      return handler.getCreationTime();
+   }
+
+   protected void flushBytes()
+   {
+      ByteBuf bytes;
+      // handler.outputBuffer has the lock
+      while ((bytes = handler.outputBuffer()) != null)
+      {
+         connectionCallback.onTransport(bytes, AbstractConnectionContext.this);
+      }
+   }
+
+
+   // This listener will perform a bunch of things here
+   class LocalListener extends DefaultEventHandler
+   {
+
+      @Override
+      public void onSASLInit(ProtonHandler handler, Connection connection)
+      {
+         handler.createServerSASL(connectionCallback.getSASLMechnisms());
+      }
+
+      @Override
+      public void onTransport(Transport transport)
+      {
+         flushBytes();
+      }
+
+      @Override
+      public void onRemoteOpen(Connection connection) throws Exception
+      {
+         synchronized (getLock())
+         {
+            connection.setContext(AbstractConnectionContext.this);
+            connection.open();
+         }
+         initialise();
+      }
+
+
+      @Override
+      public void onRemoteClose(Connection connection)
+      {
+         synchronized (getLock())
+         {
+            connection.close();
+            for (AbstractProtonSessionContext protonSession : sessions.values())
+            {
+               protonSession.close();
+            }
+            sessions.clear();
+         }
+         // We must force write the channel before we actually destroy the connection
+         onTransport(handler.getTransport());
+         destroy();
+      }
+
+      @Override
+      public void onLocalOpen(Session session) throws Exception
+      {
+         getSessionExtension(session);
+      }
+
+      @Override
+      public void onRemoteOpen(Session session) throws Exception
+      {
+         getSessionExtension(session).initialise();
+         synchronized (getLock())
+         {
+            session.open();
+         }
+      }
+
+
+      @Override
+      public void onLocalClose(Session session) throws Exception
+      {
+      }
+
+      @Override
+      public void onRemoteClose(Session session) throws Exception
+      {
+         synchronized (getLock())
+         {
+            session.close();
+         }
+
+         AbstractProtonSessionContext sessionContext = (AbstractProtonSessionContext) session.getContext();
+         if (sessionContext != null)
+         {
+            sessionContext.close();
+            sessions.remove(session);
+            session.setContext(null);
+         }
+      }
+
+      @Override
+      public void onRemoteOpen(Link link) throws Exception
+      {
+         remoteLinkOpened(link);
+      }
+
+      @Override
+      public void onFlow(Link link) throws Exception
+      {
+         ((ProtonDeliveryHandler) link.getContext()).onFlow(link.getCredit());
+      }
+
+      @Override
+      public void onRemoteClose(Link link) throws Exception
+      {
+         link.close();
+         ((ProtonDeliveryHandler) link.getContext()).close();
+      }
+
+
+      public void onRemoteDetach(Link link) throws Exception
+      {
+         link.detach();
+      }
+
+      public void onDelivery(Delivery delivery) throws Exception
+      {
+         ProtonDeliveryHandler handler = (ProtonDeliveryHandler) delivery.getLink().getContext();
+         if (handler != null)
+         {
+            handler.onMessage(delivery);
+         }
+         else
+         {
+            // TODO: logs
+
+            System.err.println("Handler is null, can't delivery " + delivery);
+         }
+      }
+
+
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java
new file mode 100644
index 0000000..45b5250
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonContextSender.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.PooledByteBufAllocator;
+import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Sender;
+import org.apache.qpid.proton.message.ProtonJMessage;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.util.CreditsSemaphore;
+import org.proton.plug.util.NettyWritable;
+
+/**
+ * A this is a wrapper around a HornetQ ServerConsumer for handling outgoing messages and incoming acks via a Proton Sender
+ *
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ */
+public abstract class AbstractProtonContextSender extends ProtonInitializable implements ProtonDeliveryHandler
+{
+   protected final AbstractProtonSessionContext protonSession;
+   protected final Sender sender;
+   protected final AbstractConnectionContext connection;
+   protected boolean closed = false;
+   protected final AMQPSessionCallback sessionSPI;
+   protected CreditsSemaphore creditsSemaphore = new CreditsSemaphore(0);
+
+
+   public AbstractProtonContextSender(AbstractConnectionContext connection, Sender sender, AbstractProtonSessionContext protonSession, AMQPSessionCallback server)
+   {
+      this.connection = connection;
+      this.sender = sender;
+      this.protonSession = protonSession;
+      this.sessionSPI = server;
+   }
+
+   public void onFlow(int credits)
+   {
+      this.creditsSemaphore.setCredits(credits);
+   }
+
+   /*
+   * start the session
+   * */
+   public void start() throws HornetQAMQPException
+   {
+      sessionSPI.start();
+      // protonSession.getServerSession().start();
+   }
+
+   /*
+   * close the session
+   * */
+   public void close() throws HornetQAMQPException
+   {
+      closed = true;
+      protonSession.removeSender(sender);
+      synchronized (connection.getLock())
+      {
+         sender.close();
+      }
+
+      connection.flush();
+   }
+
+   @Override
+   /*
+   * handle an incoming Ack from Proton, basically pass to HornetQ to handle
+   * */
+   public abstract void onMessage(Delivery delivery) throws HornetQAMQPException;
+
+   /*
+   * check the state of the consumer, i.e. are there any more messages. only really needed for browsers?
+   * */
+   public void checkState()
+   {
+   }
+
+   public Sender getSender()
+   {
+      return sender;
+   }
+
+   protected int performSend(ProtonJMessage serverMessage, Object context)
+   {
+      if (!creditsSemaphore.tryAcquire())
+      {
+         try
+         {
+            creditsSemaphore.acquire();
+         }
+         catch (InterruptedException e)
+         {
+            Thread.currentThread().interrupt();
+            // nothing to be done here.. we just keep going
+            throw new IllegalStateException(e.getMessage(), e);
+         }
+      }
+
+      //presettle means we can ack the message on the dealer side before we send it, i.e. for browsers
+      boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;
+
+      //we only need a tag if we are going to ack later
+      byte[] tag = preSettle ? new byte[0] : protonSession.getTag();
+
+      ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
+      try
+      {
+         serverMessage.encode(new NettyWritable(nettyBuffer));
+
+         int size = nettyBuffer.writerIndex();
+
+         synchronized (connection.getLock())
+         {
+            final Delivery delivery;
+            delivery = sender.delivery(tag, 0, tag.length);
+            delivery.setContext(context);
+
+            // this will avoid a copy.. patch provided by Norman using buffer.array()
+            sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(), nettyBuffer.readableBytes());
+
+            if (preSettle)
+            {
+               delivery.settle();
+            }
+            else
+            {
+               sender.advance();
+            }
+         }
+
+         connection.flush();
+
+         return size;
+      }
+      finally
+      {
+         nettyBuffer.release();
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java
new file mode 100644
index 0000000..fb4bb07
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonReceiverContext.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context;
+
+import org.apache.qpid.proton.engine.Receiver;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+/**
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ *         <p/>
+ *         handles incoming messages via a Proton Receiver and forwards them to HornetQ
+ */
+public abstract class AbstractProtonReceiverContext extends ProtonInitializable implements ProtonDeliveryHandler
+{
+   protected final AbstractConnectionContext connection;
+
+   protected final AbstractProtonSessionContext protonSession;
+
+   protected final Receiver receiver;
+
+   protected final String address;
+
+   protected final AMQPSessionCallback sessionSPI;
+
+   public AbstractProtonReceiverContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, AbstractProtonSessionContext protonSession, Receiver receiver)
+   {
+      this.connection = connection;
+      this.protonSession = protonSession;
+      this.receiver = receiver;
+      if (receiver.getRemoteTarget() != null)
+      {
+         this.address = receiver.getRemoteTarget().getAddress();
+      }
+      else
+      {
+         this.address = null;
+      }
+      this.sessionSPI = sessionSPI;
+   }
+
+   @Override
+   public void close() throws HornetQAMQPException
+   {
+      protonSession.removeReceiver(receiver);
+   }
+
+   public void flow(int credits)
+   {
+      synchronized (connection.getLock())
+      {
+         receiver.flow(credits);
+      }
+      connection.flush();
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java
new file mode 100644
index 0000000..8f28039
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/AbstractProtonSessionContext.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.qpid.proton.amqp.transport.ErrorCondition;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.engine.Sender;
+import org.apache.qpid.proton.engine.Session;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.AMQPSessionContext;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.exceptions.HornetQAMQPInternalErrorException;
+
+/**
+ * ProtonSession is a direct representation of the session on the broker.
+ * It has a link between a ProtonSession and a Broker or Client Session
+ * The Broker Session is linked through the ProtonSessionSPI
+ *
+ * @author Clebert Suconic
+ */
+public abstract class AbstractProtonSessionContext extends ProtonInitializable implements AMQPSessionContext
+{
+   protected final AbstractConnectionContext connection;
+
+   protected final AMQPSessionCallback sessionSPI;
+
+   protected final Session session;
+
+   private long currentTag = 0;
+
+   protected Map<Receiver, AbstractProtonReceiverContext> receivers = new HashMap<Receiver, AbstractProtonReceiverContext>();
+
+   protected Map<Sender, AbstractProtonContextSender> senders = new HashMap<Sender, AbstractProtonContextSender>();
+
+   protected boolean closed = false;
+
+   public AbstractProtonSessionContext(AMQPSessionCallback sessionSPI, AbstractConnectionContext connection, Session session)
+   {
+      this.connection = connection;
+      this.sessionSPI = sessionSPI;
+      this.session = session;
+   }
+
+   public void initialise() throws Exception
+   {
+      if (!isInitialized())
+      {
+         super.initialise();
+
+         if (sessionSPI != null)
+         {
+            try
+            {
+               sessionSPI.init(this, connection.getSASLResult());
+            }
+            catch (Exception e)
+            {
+               throw new HornetQAMQPInternalErrorException(e.getMessage(), e);
+            }
+         }
+      }
+   }
+
+
+   /**
+    * TODO: maybe it needs to go?
+    *
+    * @param consumer
+    * @param queueName
+    */
+   public void disconnect(Object consumer, String queueName)
+   {
+      AbstractProtonContextSender protonConsumer = senders.remove(consumer);
+      if (protonConsumer != null)
+      {
+         try
+         {
+            protonConsumer.close();
+         }
+         catch (HornetQAMQPException e)
+         {
+            protonConsumer.getSender().setTarget(null);
+            protonConsumer.getSender().setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
+         }
+      }
+   }
+
+
+   @Override
+   public byte[] getTag()
+   {
+      return Long.toHexString(currentTag++).getBytes();
+   }
+
+   @Override
+   public void replaceTag(byte[] tag)
+   {
+      // TODO: do we need to reuse this?
+   }
+
+   @Override
+   public void close()
+   {
+      if (closed)
+      {
+         return;
+      }
+
+
+
+      // Making a copy to avoid ConcurrentModificationException during the iteration
+      Set<AbstractProtonReceiverContext> receiversCopy = new HashSet<>();
+      receiversCopy.addAll(receivers.values());
+
+
+      for (AbstractProtonReceiverContext protonProducer : receiversCopy)
+      {
+         try
+         {
+            protonProducer.close();
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+            // TODO Logging
+         }
+      }
+      receivers.clear();
+
+      Set<AbstractProtonContextSender> protonSendersClone = new HashSet<>();
+      protonSendersClone.addAll(senders.values());
+
+      for (AbstractProtonContextSender protonConsumer : protonSendersClone)
+      {
+         try
+         {
+            protonConsumer.close();
+         }
+         catch (Exception e)
+         {
+            e.printStackTrace();
+            // TODO Logging
+         }
+      }
+      senders.clear();
+      try
+      {
+         if (sessionSPI != null)
+         {
+            sessionSPI.rollbackCurrentTX();
+            sessionSPI.close();
+         }
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+         // TODO logging
+      }
+      closed = true;
+   }
+
+   @Override
+   public void removeSender(Sender sender) throws HornetQAMQPException
+   {
+      senders.remove(sender);
+   }
+
+   @Override
+   public void removeReceiver(Receiver receiver)
+   {
+      receivers.remove(receiver);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java
new file mode 100644
index 0000000..3436c5c
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonDeliveryHandler.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context;
+
+import org.apache.qpid.proton.engine.Delivery;
+import org.proton.plug.exceptions.HornetQAMQPException;
+
+/**
+ * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
+ *         <p/>
+ *         An interface to handle deliveries, either messages, acks or transaction calls
+ */
+public interface ProtonDeliveryHandler
+{
+   void onFlow(int currentCredits);
+
+   void onMessage(Delivery delivery) throws HornetQAMQPException;
+
+   void close() throws HornetQAMQPException;
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java
new file mode 100644
index 0000000..0dad6d7
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonInitializable.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context;
+
+import java.util.concurrent.TimeUnit;
+
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.exceptions.HornetQAMQPIllegalStateException;
+import org.proton.plug.exceptions.HornetQAMQPTimeoutException;
+import org.proton.plug.util.FutureRunnable;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class ProtonInitializable
+{
+
+   private Runnable afterInit;
+
+   private boolean initialized = false;
+
+   public void afterInit(Runnable afterInit)
+   {
+      this.afterInit = afterInit;
+   }
+
+
+   public boolean isInitialized()
+   {
+      return initialized;
+   }
+
+
+   public void initialise() throws Exception
+   {
+      if (!initialized)
+      {
+         initialized = false;
+         try
+         {
+            if (afterInit != null)
+            {
+               afterInit.run();
+            }
+         }
+         finally
+         {
+            afterInit = null;
+         }
+      }
+   }
+
+
+   public void waitWithTimeout(FutureRunnable latch) throws HornetQAMQPException
+   {
+      try
+      {
+         // TODO Configure this
+         if (!latch.await(30, TimeUnit.SECONDS))
+         {
+            throw new HornetQAMQPTimeoutException("Timed out waiting for response");
+         }
+      }
+      catch (InterruptedException e)
+      {
+         Thread.currentThread().interrupt();
+         throw new HornetQAMQPIllegalStateException(e.getMessage());
+      }
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java
new file mode 100644
index 0000000..eff114a
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonPlugSender.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.proton.plug.context;
+
+import org.apache.qpid.proton.engine.Sender;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public interface ProtonPlugSender
+{
+   int deliverMessage(Object message, int deliveryCount) throws Exception;
+
+   Sender getSender();
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java
new file mode 100644
index 0000000..9f53085
--- /dev/null
+++ b/hornetq-protocols/hornetq-proton-plug/src/main/java/org/proton/plug/context/ProtonTransactionHandler.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.proton.plug.context;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.PooledByteBufAllocator;
+import org.apache.qpid.proton.amqp.Binary;
+import org.apache.qpid.proton.amqp.Symbol;
+import org.apache.qpid.proton.amqp.messaging.AmqpValue;
+import org.apache.qpid.proton.amqp.messaging.Rejected;
+import org.apache.qpid.proton.amqp.transaction.Declare;
+import org.apache.qpid.proton.amqp.transaction.Declared;
+import org.apache.qpid.proton.amqp.transaction.Discharge;
+import org.apache.qpid.proton.amqp.transport.ErrorCondition;
+import org.apache.qpid.proton.engine.Delivery;
+import org.apache.qpid.proton.engine.Receiver;
+import org.apache.qpid.proton.message.impl.MessageImpl;
+import org.proton.plug.AMQPSessionCallback;
+import org.proton.plug.exceptions.HornetQAMQPException;
+import org.proton.plug.logger.HornetQAMQPProtocolMessageBundle;
+
+import static org.proton.plug.util.DeliveryUtil.decodeMessageImpl;
+import static org.proton.plug.util.DeliveryUtil.readDelivery;
+
+/**
+ * handles an amqp Coordinator to deal with transaction boundaries etc
+ */
+public class ProtonTransactionHandler implements ProtonDeliveryHandler
+{
+
+   final AMQPSessionCallback sessionSPI;
+
+   public ProtonTransactionHandler(AMQPSessionCallback sessionSPI)
+   {
+      this.sessionSPI = sessionSPI;
+   }
+
+   @Override
+   public void onMessage(Delivery delivery) throws HornetQAMQPException
+   {
+      ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
+
+      final Receiver receiver;
+      try
+      {
+         receiver = ((Receiver) delivery.getLink());
+
+         if (!delivery.isReadable())
+         {
+            return;
+         }
+
+         readDelivery(receiver, buffer);
+
+         receiver.advance();
+
+         MessageImpl msg = decodeMessageImpl(buffer);
+
+         Object action = ((AmqpValue) msg.getBody()).getValue();
+
+         if (action instanceof Declare)
+         {
+            Binary txID = sessionSPI.getCurrentTXID();
+            Declared declared = new Declared();
+            declared.setTxnId(txID);
+            delivery.disposition(declared);
+            delivery.settle();
+         }
+         else if (action instanceof Discharge)
+         {
+            Discharge discharge = (Discharge) action;
+            if (discharge.getFail())
+            {
+               try
+               {
+                  sessionSPI.rollbackCurrentTX();
+               }
+               catch (Exception e)
+               {
+                  throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorRollingbackCoordinator(e.getMessage());
+               }
+            }
+            else
+            {
+               try
+               {
+                  sessionSPI.commitCurrentTX();
+               }
+               catch (Exception e)
+               {
+                  throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCommittingCoordinator(e.getMessage());
+               }
+            }
+            delivery.settle();
+         }
+
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+         Rejected rejected = new Rejected();
+         ErrorCondition condition = new ErrorCondition();
+         condition.setCondition(Symbol.valueOf("failed"));
+         condition.setDescription(e.getMessage());
+         rejected.setError(condition);
+         delivery.disposition(rejected);
+      }
+      finally
+      {
+         buffer.release();
+      }
+   }
+
+   public void onFlow(int credits)
+   {
+
+   }
+
+   @Override
+   public void close() throws HornetQAMQPException
+   {
+      //noop
+   }
+}


[09/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverTest.java
deleted file mode 100644
index de4a7cd..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/ColocatedFailoverTest.java
+++ /dev/null
@@ -1,1403 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.cluster.failover;
-
-
-import org.hornetq.api.core.Message;
-import org.hornetq.api.core.SimpleString;
-import org.hornetq.api.core.TransportConfiguration;
-import org.hornetq.api.core.client.ClientConsumer;
-import org.hornetq.api.core.client.ClientMessage;
-import org.hornetq.api.core.client.ClientProducer;
-import org.hornetq.api.core.client.ClientSession;
-import org.hornetq.api.core.client.ClientSessionFactory;
-import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.api.core.client.SendAcknowledgementHandler;
-import org.hornetq.api.core.client.ServerLocator;
-import org.hornetq.core.config.BackupStrategy;
-import org.hornetq.core.config.Configuration;
-import org.hornetq.core.config.CoreQueueConfiguration;
-import org.hornetq.core.postoffice.Binding;
-import org.hornetq.core.postoffice.Bindings;
-import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.Queue;
-import org.hornetq.core.server.cluster.ClusterConnection;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
-import org.hornetq.core.server.impl.HornetQServerImpl;
-import org.hornetq.core.server.impl.InVMNodeManager;
-import org.hornetq.core.server.impl.QueueImpl;
-import org.hornetq.core.settings.impl.AddressFullMessagePolicy;
-import org.hornetq.core.settings.impl.AddressSettings;
-import org.hornetq.core.transaction.impl.XidImpl;
-import org.hornetq.tests.integration.cluster.util.SameProcessHornetQServer;
-import org.hornetq.tests.integration.cluster.util.TestableServer;
-import org.hornetq.tests.util.ColocatedHornetQServer;
-import org.hornetq.tests.util.ServiceTestBase;
-import org.hornetq.tests.util.UnitTestCase;
-import org.hornetq.utils.UUIDGenerator;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class ColocatedFailoverTest extends ServiceTestBase
-{
-   private TestableServer liveServer1;
-
-   private TestableServer liveServer2;
-
-   protected NodeManager nodeManagerLive1;
-
-   protected NodeManager nodeManagerLive2;
-
-   private ServerLocator locator;
-
-   private SimpleString queue;
-
-   private SimpleString topic;
-
-   private ClientSessionFactory factory1;
-
-   private ClientSessionFactory factory2;
-
-   private ClientSession session1;
-
-   private ClientSession session2;
-
-   @Override
-   @Before
-   public void setUp() throws Exception
-   {
-      super.setUp();
-      deleteDirectory(new File(getTestDir() + ""));
-      createConfigs();
-
-      liveServer1.start();
-      liveServer2.start();
-      waitForServer(liveServer1.getServer());
-      waitForServer(liveServer2.getServer());
-
-      HashMap<String, Object> params = new HashMap<>();
-      params.put("server-id", "1");
-      TransportConfiguration transportConfiguration1 = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params);
-      locator = HornetQClient.createServerLocator(true, transportConfiguration1);
-      locator.setReconnectAttempts(-1);
-      locator.setConfirmationWindowSize(0);
-      factory1 = locator.createSessionFactory(transportConfiguration1);
-
-      HashMap<String, Object> params2 = new HashMap<>();
-      params2.put("server-id", "2");
-
-      TransportConfiguration transportConfiguration2 = new TransportConfiguration(INVM_CONNECTOR_FACTORY, params2);
-      factory2 = locator.createSessionFactory(transportConfiguration2);
-
-      session1 = factory1.createSession(false, true, true);
-      session2 = factory2.createSession(false, true, true);
-      queue = new SimpleString("jms.queue.testQueue");
-      topic = new SimpleString("jms.topic.testTopic");
-   }
-
-   @Override
-   @After
-   public void tearDown() throws Exception
-   {
-      if (locator != null)
-         locator.close();
-      liveServer1.stop();
-      liveServer2.stop();
-      super.tearDown();
-   }
-
-   @Test
-   public void testSend() throws Exception
-   {
-      int numMessages = 100;
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(numMessages);
-      ClientConsumer consumer = session2.createConsumer(queue);
-      session2.start();
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-
-            latch.countDown();
-         }
-      });
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(queue, message);
-      }
-      latch.await(10, TimeUnit.SECONDS);
-      System.out.println(locator.getTopology().describe());
-      liveServer1.crash(true, session1);
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         assertNotNull(cMessage.getBodyBuffer().readString());
-         //NB we dont test for order as they will be round robined and out of order
-      }
-   }
-
-   @Test
-   public void testSendPagingOnReload() throws Exception
-   {
-      AddressSettings addressSettings = new AddressSettings();
-      addressSettings.setMaxSizeBytes(5000);
-      addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE);
-      addressSettings.setPageSizeBytes(1000);
-      String pagedQueue = "jms.queue.pagedQueue";
-      SimpleString ssPagedQueue = new SimpleString(pagedQueue);
-      liveServer2.getServer().getAddressSettingsRepository().addMatch(pagedQueue, addressSettings);
-      session1.createQueue(pagedQueue, pagedQueue, true);
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(2);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-
-            latch.countDown();
-         }
-      });
-      byte[] bytes = new byte[10000];
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeBytes(bytes);
-      producer.send(ssPagedQueue, message);
-      message = session1.createMessage(true);
-      message.getBodyBuffer().writeBytes(bytes);
-      producer.send(ssPagedQueue, message);
-      latch.await(10, TimeUnit.SECONDS);
-      liveServer1.crash(true, session1);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-   }
-
-   @Test
-   public void testLargeMessage() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(2);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-
-            latch.countDown();
-         }
-      });
-      ClientMessage message = session1.createMessage(true);
-
-      message.setBodyInputStream(UnitTestCase.createFakeLargeStream(10000));
-      producer.send(queue, message);
-      ClientConsumer consumer = session1.createConsumer(queue);
-      session1.start();
-      message = consumer.receive(5000);
-      assertNotNull(message);
-      assertTrue(message.isLargeMessage());
-      message.getBodyBuffer().readBytes(10000);
-      session1.close();
-      liveServer1.crash(true, session1);
-      consumer = session2.createConsumer(queue);
-      session2.start();
-      message = consumer.receive(5000);
-      assertNotNull(message);
-      assertTrue(message.isLargeMessage());
-      message.getBodyBuffer().readBytes(10000);
-   }
-
-   @Test
-   public void testSendScheduled() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(1);
-      ClientConsumer consumer = session2.createConsumer(queue);
-      session2.start();
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-
-            latch.countDown();
-         }
-      });
-      ClientMessage message = session1.createMessage(true);
-      long time = System.currentTimeMillis() + 10000;
-      message.putLongProperty(Message.HDR_SCHEDULED_DELIVERY_TIME, time);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      latch.await(10, TimeUnit.SECONDS);
-
-      liveServer1.crash(true, session1);
-      ClientMessage cMessage = consumer.receive(10000);
-      assertNotNull(cMessage);
-      assertTrue(System.currentTimeMillis() >= time);
-      assertNotNull(cMessage.getBodyBuffer().readString());
-   }
-
-
-   @Test
-   public void testSendQueueNotExistOnLive() throws Exception
-   {
-      int numMessages = 100;
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(numMessages);
-      SimpleString dur1 = new SimpleString("myDurSub1");
-      session1.createQueue(topic, dur1, true);
-      SimpleString dur2 = new SimpleString("myDurSub2");
-      session2.createQueue(topic, dur2, true);
-      waitForBindings(liveServer1.getServer(), topic.toString(), false, 2, 0, 5000L);
-      waitForBindings(liveServer2.getServer(), topic.toString(), false, 2, 0, 5000L);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch.countDown();
-         }
-      });
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(topic, message);
-      }
-      latch.await(10, TimeUnit.SECONDS);
-      liveServer1.crash(true, session1);
-
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      ClientConsumer consumer = session2.createConsumer(dur1);
-      ClientConsumer consumer2 = session2.createConsumer(dur2);
-      session2.start();
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         assertNotNull(cMessage.getBodyBuffer().readString());
-      }
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage cMessage = consumer2.receive(5000);
-         String s = cMessage.getBodyBuffer().readString();
-         System.out.println("s = " + s);
-         assertNotNull(s);
-      }
-   }
-
-   @Test
-   public void testSendQueueMessageStillInForwardQueue() throws Exception
-   {
-      int numMessages = 100;
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(numMessages);
-      SimpleString dur1 = new SimpleString("myDurSub1");
-      session2.createQueue(topic, dur1, true);
-      waitForBindings(liveServer1.getServer(), topic.toString(), false, 2, 0, 5000L);
-      waitForBindings(liveServer2.getServer(), topic.toString(), false, 1, 0, 5000L);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch.countDown();
-         }
-      });
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(topic, message);
-      }
-      latch.await(10, TimeUnit.SECONDS);
-      //now disconnect the bridge but readd the binding so we can make sure some messages get marooned
-      Bindings bindingsForAddress = liveServer1.getServer().getPostOffice().getBindingsForAddress(topic);
-      Collection<Binding> bindings = bindingsForAddress.getBindings();
-      Binding binding = null;
-      for (Binding thebinding : bindings)
-      {
-         if (thebinding.getRoutingName().equals(dur1))
-         {
-            binding = thebinding;
-            break;
-         }
-      }
-
-      assertNotNull(binding);
-      Set<ClusterConnection> clusterConnections = liveServer1.getServer().getClusterManager().getClusterConnections();
-      for (ClusterConnection clusterConnection : clusterConnections)
-      {
-         clusterConnection.stop();
-      }
-      liveServer1.getServer().getPostOffice().addBinding(binding);
-      for (int i = 100; i < numMessages + 100; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(topic, message);
-      }
-      liveServer1.crash(true, session1);
-
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      ClientConsumer consumer = session2.createConsumer(dur1);
-      session2.start();
-      for (int i = 0; i < numMessages * 2; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         assertNotNull(cMessage.getBodyBuffer().readString());
-      }
-   }
-
-   @Test
-   public void testSendQueueMessageStillInForwardQueue2Queues() throws Exception
-   {
-      int numMessages = 100;
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(numMessages);
-      SimpleString dur1 = new SimpleString("myDurSub1");
-      session2.createQueue(topic, dur1, true);
-      SimpleString dur2 = new SimpleString("myDurSub2");
-      session1.createQueue(topic, dur2, true);
-      waitForBindings(liveServer1.getServer(), topic.toString(), false, 2, 0, 5000L);
-      waitForBindings(liveServer2.getServer(), topic.toString(), false, 2, 0, 5000L);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch.countDown();
-         }
-      });
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(topic, message);
-      }
-      latch.await(10, TimeUnit.SECONDS);
-      //now disconnect the bridge but readd the binding so we can make sure some messages get marooned
-      Bindings bindingsForAddress = liveServer1.getServer().getPostOffice().getBindingsForAddress(topic);
-      Collection<Binding> bindings = bindingsForAddress.getBindings();
-      Binding binding = null;
-      for (Binding thebinding : bindings)
-      {
-         if (thebinding.getRoutingName().equals(dur1))
-         {
-            binding = thebinding;
-            break;
-         }
-      }
-
-      assertNotNull(binding);
-      Set<ClusterConnection> clusterConnections = liveServer1.getServer().getClusterManager().getClusterConnections();
-      for (ClusterConnection clusterConnection : clusterConnections)
-      {
-         clusterConnection.stop();
-      }
-      liveServer1.getServer().getPostOffice().addBinding(binding);
-      for (int i = 100; i < numMessages + 100; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(topic, message);
-      }
-      liveServer1.crash(true, session1);
-
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      ClientConsumer consumer = session2.createConsumer(dur1);
-      session2.start();
-      for (int i = 0; i < numMessages * 2; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         String s = cMessage.getBodyBuffer().readString();
-         System.out.println("s = " + s);
-         assertNotNull(s);
-      }
-      consumer = session2.createConsumer(dur2);
-      for (int i = 0; i < numMessages * 2; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         String s = cMessage.getBodyBuffer().readString();
-         System.out.println("s = " + s);
-         assertNotNull(s);
-      }
-   }
-
-   @Test
-   public void testSendQueueMessageStillInForwardQueue3Servers() throws Exception
-   {
-      TransportConfiguration liveConnector1 = getConnectorTransportConfiguration(1);
-      TransportConfiguration liveConnector3 = getConnectorTransportConfiguration(3);
-      Configuration liveConfiguration3 = super.createDefaultConfig();
-      liveConfiguration3.getAcceptorConfigurations().clear();
-      liveConfiguration3.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(3));
-      liveConfiguration3.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfiguration3.getHAPolicy().setFailbackDelay(1000);
-      liveConfiguration3.setJournalDirectory(getTestDir() + "/journal3");
-      liveConfiguration3.setBindingsDirectory(getTestDir() + "/bindings3");
-      liveConfiguration3.setLargeMessagesDirectory(getTestDir() + "/largemessage3");
-      liveConfiguration3.setPagingDirectory(getTestDir() + "/paging3");
-      liveConfiguration3.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-      liveConfiguration3.getQueueConfigurations().add(new CoreQueueConfiguration("jms.topic.testTopic", "jms.topic.testTopic", HornetQServerImpl.GENERIC_IGNORED_FILTER, true));
-
-      basicClusterConnectionConfig(liveConfiguration3, liveConnector3.getName(), liveConnector1.getName());
-      liveConfiguration3.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfiguration3.getConnectorConfigurations().put(liveConnector3.getName(), liveConnector3);
-
-      HornetQServer server3 = new HornetQServerImpl(liveConfiguration3);
-      server3.setIdentity("server3");
-      try
-      {
-         server3.start();
-         waitForServer(server3);
-
-         ClientSessionFactory sessionFactory3 = locator.createSessionFactory(liveConnector3);
-         ClientSession session3 = sessionFactory3.createSession();
-         SimpleString dursub3 = new SimpleString("dursub3");
-         session3.createQueue(topic, dursub3, true);
-
-         int numMessages = 100;
-         ClientProducer producer = session1.createProducer();
-         final CountDownLatch latch = new CountDownLatch(numMessages);
-         SimpleString dur1 = new SimpleString("myDurSub1");
-         session2.createQueue(topic, dur1, true);
-         waitForBindings(liveServer1.getServer(), topic.toString(), false, 4, 0, 5000L);
-         waitForBindings(liveServer2.getServer(), topic.toString(), false, 3, 0, 5000L);
-         session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-         {
-            @Override
-            public void sendAcknowledged(org.hornetq.api.core.Message message)
-            {
-               latch.countDown();
-            }
-         });
-         for (int i = 0; i < numMessages; i++)
-         {
-            ClientMessage message = session1.createMessage(true);
-            message.getBodyBuffer().writeString("message:" + i);
-            producer.send(topic, message);
-         }
-         latch.await(10, TimeUnit.SECONDS);
-         //now disconnect the bridge but readd the binding so we can make sure some messages get marooned
-         Bindings bindingsForAddress = liveServer1.getServer().getPostOffice().getBindingsForAddress(topic);
-         Collection<Binding> bindings = bindingsForAddress.getBindings();
-         Binding binding = null;
-         for (Binding thebinding : bindings)
-         {
-            if (thebinding.getRoutingName().equals(dur1))
-            {
-               binding = thebinding;
-               break;
-            }
-         }
-
-         assertNotNull(binding);
-
-         Binding binding2 = null;
-         for (Binding thebinding : bindings)
-         {
-            if (thebinding.getRoutingName().equals(dursub3))
-            {
-               binding2 = thebinding;
-               break;
-            }
-         }
-
-         assertNotNull(binding2);
-
-         Set<ClusterConnection> clusterConnections = liveServer1.getServer().getClusterManager().getClusterConnections();
-         for (ClusterConnection clusterConnection : clusterConnections)
-         {
-            clusterConnection.stop();
-         }
-         liveServer1.getServer().getPostOffice().addBinding(binding);
-         liveServer1.getServer().getPostOffice().addBinding(binding2);
-         for (int i = 100; i < numMessages + 100; i++)
-         {
-            ClientMessage message = session1.createMessage(true);
-            message.getBodyBuffer().writeString("message:" + i);
-            producer.send(topic, message);
-         }
-         liveServer1.crash(true, session1);
-
-         ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-         qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-         ClientConsumer consumer = session2.createConsumer(dur1);
-         session2.start();
-         for (int i = 0; i < numMessages * 2; i++)
-         {
-            ClientMessage cMessage = consumer.receive(5000);
-            assertNotNull(cMessage.getBodyBuffer().readString());
-         }
-         consumer = session3.createConsumer(dursub3);
-         session3.start();
-         for (int i = 0; i < numMessages * 2; i++)
-         {
-            ClientMessage cMessage = consumer.receive(5000);
-            assertNotNull(cMessage.getBodyBuffer().readString());
-         }
-      }
-      finally
-      {
-         server3.stop();
-      }
-   }
-
-   @Test
-   public void testSendTransacted() throws Exception
-   {
-      int numMessages = 100;
-      try
-      (
-         ClientSession session = factory1.createSession(true, false, false)
-      )
-      {
-         ClientProducer producer = session.createProducer();
-         Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-         session.start(xid, XAResource.TMNOFLAGS);
-         for (int i = 0; i < numMessages; i++)
-         {
-            ClientMessage message = session1.createMessage(true);
-            message.getBodyBuffer().writeString("message:" + i);
-            producer.send(queue, message);
-            System.out.println("i = " + i);
-         }
-         session.end(xid, XAResource.TMSUCCESS);
-         session.prepare(xid);
-         liveServer1.crash(true, session);
-         ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-         qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-         try
-         (
-               ClientSession session2 = factory2.createSession(true, true, true)
-         )
-         {
-            session2.getXAResource().commit(xid, false);
-         }
-      }
-      ClientConsumer consumer = session2.createConsumer(queue);
-      session2.start();
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         assertNotNull(cMessage.getBodyBuffer().readString());
-         //NB we dont test for order as they will be round robined and out of order
-      }
-   }
-
-   @Test
-   public void testReceiveTransacted() throws Exception
-   {
-      int numMessages = 100;
-      ClientProducer producer = session1.createProducer();
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(queue, message);
-         System.out.println("i = " + i);
-      }
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      for (int i = 0; i < numMessages / 2; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         cMessage.acknowledge();
-      }
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-         (
-            ClientSession session2 = factory2.createSession(true, true, true)
-         )
-      {
-         session2.getXAResource().commit(xid, false);
-      }
-   }
-
-   @Test
-   public void testSendAndReceiveSameQueueTransacted() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-      (
-            ClientSession session2 = factory2.createSession(true, false, false)
-      )
-      {
-         session2.getXAResource().commit(xid, false);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(q.getMessageCount(), 0);
-      assertEquals(q.getMessagesAdded(), 1);
-   }
-
-   @Test
-   public void testSendAndReceiveSameQueueTransactedRollback() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(q.getMessageCount(), 1);
-      assertEquals(q.getMessagesAdded(), 1);
-      ClientConsumer consumer1 = session2.createConsumer(queue);
-      session2.start();
-      ClientMessage clientMessage = consumer1.receiveImmediate();
-      assertNotNull(clientMessage);
-      String s = clientMessage.getBodyBuffer().readString();
-      assertEquals(s, "message:1");
-   }
-
-   @Test
-   public void testSendAndReceiveSameQueueTransactedRollbackRestart() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(q.getMessageCount(), 1);
-      assertEquals(q.getMessagesAdded(), 1);
-      liveServer2.stop();
-      liveServer2.start();
-      ClientConsumer consumer1 = session2.createConsumer(queue);
-      session2.start();
-      ClientMessage clientMessage = consumer1.receiveImmediate();
-      assertNotNull(clientMessage);
-      String s = clientMessage.getBodyBuffer().readString();
-      assertEquals(s, "message:1");
-   }
-
-   @Test
-   public void testSendAndReceiveSameQueueTransactedManyMessages() throws Exception
-   {
-      int numMessage = 1000;
-      ClientProducer producer = session1.createProducer();
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      for (int i = 0; i < numMessage; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(queue, message);
-
-      }
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      for (int i = 0; i < numMessage / 2; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         cMessage.acknowledge();
-      }
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().commit(xid, false);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(500, q.getMessageCount());
-      assertEquals(1000, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testSendAndReceiveSameQueueTransactedManyMessagesRollback() throws Exception
-   {
-      int numMessage = 1000;
-      ClientProducer producer = session1.createProducer();
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      for (int i = 0; i < numMessage; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(queue, message);
-
-      }
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      for (int i = 0; i < numMessage / 2; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         cMessage.acknowledge();
-      }
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(1000, q.getMessageCount());
-      assertEquals(1000, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testSendAndReceiveSameQueueTransactedManyMessagesRollbackRestart() throws Exception
-   {
-      int numMessage = 1000;
-      ClientProducer producer = session1.createProducer();
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      for (int i = 0; i < numMessage; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(queue, message);
-
-      }
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      for (int i = 0; i < numMessage / 2; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         cMessage.acknowledge();
-      }
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      liveServer2.stop();
-      liveServer2.start();
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(1000, q.getMessageCount());
-      assertEquals(1000, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testReceiveTransacted2Queues1acked() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      SimpleString queue2 = new SimpleString("jms.queue.testQueue2");
-      session1.createQueue(queue, queue2, true);
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-      (
-            ClientSession session2 = factory2.createSession(true, false, false)
-      )
-      {
-         session2.getXAResource().commit(xid, false);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(0, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-      q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue2).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testReceiveTransacted2Queues1ackedRollback() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      SimpleString queue2 = new SimpleString("jms.queue.testQueue2");
-      session1.createQueue(queue, queue2, true);
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-      q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue2).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testReceiveTransacted2Queues1ackedRollbackRestart() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      SimpleString queue2 = new SimpleString("jms.queue.testQueue2");
-      session1.createQueue(queue, queue2, true);
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      liveServer2.stop();
-      liveServer2.start();
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-      q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue2).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testReceiveTransacted2Queues1ackedAndExtraSend() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      SimpleString queue2 = new SimpleString("jms.queue.testQueue2");
-      session1.createQueue(queue, queue2, true);
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      producer = session.createProducer();
-      ClientMessage m = session.createMessage(true);
-      m.getBodyBuffer().writeString("message:2");
-      producer.send(queue, m);
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().commit(xid, false);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(2, q.getMessagesAdded());
-      q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue2).getBindable();
-      assertEquals(2, q.getMessageCount());
-      assertEquals(2, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testReceiveTransacted2Queues1ackedAndExtraSendRollback() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      SimpleString queue2 = new SimpleString("jms.queue.testQueue2");
-      session1.createQueue(queue, queue2, true);
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      producer = session.createProducer();
-      ClientMessage m = session.createMessage(true);
-      m.getBodyBuffer().writeString("message:2");
-      producer.send(queue, m);
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-      (
-            ClientSession session2 = factory2.createSession(true, false, false)
-      )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-      q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue2).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testReceiveTransacted2Queues1ackedAndExtraSendRollbackRestart() throws Exception
-   {
-      ClientProducer producer = session1.createProducer();
-      SimpleString queue2 = new SimpleString("jms.queue.testQueue2");
-      session1.createQueue(queue, queue2, true);
-      ClientSession session = factory1.createSession(true, false, false);
-      ClientConsumer consumer = session.createConsumer(queue);
-      ClientMessage message = session1.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      producer.close();
-
-      Xid xid = new XidImpl("bq1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
-      session.start(xid, XAResource.TMNOFLAGS);
-      session.start();
-      ClientMessage cMessage = consumer.receive(5000);
-      cMessage.acknowledge();
-      producer = session.createProducer();
-      ClientMessage m = session.createMessage(true);
-      m.getBodyBuffer().writeString("message:2");
-      producer.send(queue, m);
-      session.end(xid, XAResource.TMSUCCESS);
-      session.prepare(xid);
-      session.close();
-      liveServer1.crash(true, session);
-      ColocatedHornetQServer qServer = (ColocatedHornetQServer) liveServer2.getServer();
-      qServer.backupServer.waitForActivation(5, TimeUnit.SECONDS);
-      try
-            (
-                  ClientSession session2 = factory2.createSession(true, false, false)
-            )
-      {
-         session2.getXAResource().rollback(xid);
-      }
-      liveServer2.stop();
-      liveServer2.start();
-      Queue q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-      q = (Queue) liveServer2.getServer().getPostOffice().getBinding(queue2).getBindable();
-      assertEquals(1, q.getMessageCount());
-      assertEquals(1, q.getMessagesAdded());
-   }
-
-   @Test
-   public void testReceive() throws Exception
-   {
-      int numMessages = 100;
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(numMessages);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch.countDown();
-         }
-      });
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         producer.send(queue, message);
-      }
-      latch.await(10, TimeUnit.SECONDS);
-
-      ClientConsumer consumer1 = session1.createConsumer(queue);
-      session1.start();
-      for (int i = 0; i < numMessages; i += 2)
-      {
-         ClientMessage cMessage = consumer1.receive(5000);
-         assertNotNull(cMessage.getBodyBuffer().readString());
-      }
-      session1.close();
-      liveServer1.crash();
-      ClientConsumer consumer = session2.createConsumer(queue);
-      session2.start();
-      for (int i = 50; i < numMessages; i++)
-      {
-         ClientMessage cMessage = consumer.receive(5000);
-         String s = cMessage.getBodyBuffer().readString();
-         System.out.println("s = " + s);
-         assertNotNull(s);
-      }
-   }
-
-   @Test
-   public void testReceiveRedelivery() throws Exception
-   {
-      ClientSession session = factory1.createTransactedSession();
-      ClientProducer producer = session1.createProducer();
-      final CountDownLatch latch = new CountDownLatch(1);
-      session.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch.countDown();
-         }
-      });
-      ClientMessage message = session.createMessage(true);
-      message.getBodyBuffer().writeString("message:1");
-      producer.send(queue, message);
-      latch.await(10, TimeUnit.SECONDS);
-
-      ClientConsumer consumer1 = session.createConsumer(queue);
-      session.start();
-      ClientMessage cMessage = consumer1.receive(5000);
-      assertNotNull(cMessage.getBodyBuffer().readString());
-      cMessage.acknowledge();
-      assertEquals(1, cMessage.getDeliveryCount());
-      session.rollback();
-      cMessage = consumer1.receive(5000);
-      assertNotNull(cMessage.getBodyBuffer().readString());
-      cMessage.acknowledge();
-      assertEquals(2, cMessage.getDeliveryCount());
-      session.rollback();
-      session.close();
-      liveServer1.crash();
-      ClientConsumer consumer = session2.createConsumer(queue);
-      session2.start();
-      cMessage = consumer.receive(5000);
-      String s = cMessage.getBodyBuffer().readString();
-      System.out.println("s = " + s);
-      assertNotNull(s);
-      assertEquals(3, cMessage.getDeliveryCount());
-   }
-
-   @Test
-   public void testSendDuplicateIDs() throws Exception
-   {
-      int numMessages = 100;
-      ClientProducer producer = session1.createProducer();
-      ClientProducer producer2 = session2.createProducer();
-      final CountDownLatch latch = new CountDownLatch(numMessages * 2);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch.countDown();
-         }
-      });
-
-      session2.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch.countDown();
-         }
-      });
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         message.putStringProperty(org.hornetq.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString(), "prod1" + ":" + i);
-         producer.send(queue, message);
-
-         message = session2.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         message.putStringProperty(org.hornetq.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString(), "prod2" + ":" + i);
-         producer2.send(queue, message);
-      }
-      latch.await(10, TimeUnit.SECONDS);
-
-      liveServer1.crash();
-
-      final CountDownLatch latch2 = new CountDownLatch(numMessages * 2);
-      session1.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch2.countDown();
-         }
-      });
-      session2.setSendAcknowledgementHandler(new SendAcknowledgementHandler()
-      {
-         @Override
-         public void sendAcknowledged(org.hornetq.api.core.Message message)
-         {
-            latch2.countDown();
-         }
-      });
-
-      Thread.sleep(5000);
-      for (int i = 0; i < numMessages; i++)
-      {
-         ClientMessage message = session1.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         message.putStringProperty(org.hornetq.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString(), "prod1" + ":" + i);
-         producer.send(queue, message);
-
-         message = session2.createMessage(true);
-         message.getBodyBuffer().writeString("message:" + i);
-         message.putStringProperty(org.hornetq.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString(), "prod2" + ":" + i);
-         producer2.send(queue, message);
-      }
-      latch2.await(10, TimeUnit.SECONDS);
-      Binding binding = liveServer2.getServer().getPostOffice().getBinding(new SimpleString("jms.queue.testQueue"));
-      QueueImpl q = (QueueImpl) binding.getBindable();
-      assertEquals(numMessages * 2, q.getMessageCount());
-   }
-
-
-
-   protected void createConfigs() throws Exception
-   {
-      nodeManagerLive1 = new InVMNodeManager(false);
-      nodeManagerLive2 = new InVMNodeManager(false);
-
-      TransportConfiguration liveConnector1 = getConnectorTransportConfiguration(1);
-      Configuration liveConfiguration1 = super.createDefaultConfig();
-      liveConfiguration1.getAcceptorConfigurations().clear();
-      liveConfiguration1.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(1));
-      liveConfiguration1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfiguration1.getHAPolicy().setFailbackDelay(1000);
-      liveConfiguration1.setJournalDirectory(getTestDir() + "/journal1");
-      liveConfiguration1.setBindingsDirectory(getTestDir() + "/bindings1");
-      liveConfiguration1.setLargeMessagesDirectory(getTestDir() + "/largemessage1");
-      liveConfiguration1.setPagingDirectory(getTestDir() + "/paging1");
-      liveConfiguration1.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-      liveConfiguration1.getQueueConfigurations().add(new CoreQueueConfiguration("jms.topic.testTopic", "jms.topic.testTopic", HornetQServerImpl.GENERIC_IGNORED_FILTER, true));
-
-      TransportConfiguration liveConnector2 = getConnectorTransportConfiguration(2);
-      basicClusterConnectionConfig(liveConfiguration1, liveConnector1.getName(), liveConnector2.getName());
-      liveConfiguration1.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfiguration1.getConnectorConfigurations().put(liveConnector2.getName(), liveConnector2);
-
-      Configuration backupConfiguration1 = liveConfiguration1.copy();
-
-      backupConfiguration1.setJournalDirectory(getTestDir() + "/journal2");
-      backupConfiguration1.setBindingsDirectory(getTestDir() + "/bindings2");
-      backupConfiguration1.setLargeMessagesDirectory(getTestDir() + "/largemessage2");
-      backupConfiguration1.setPagingDirectory(getTestDir() + "/paging2");
-      backupConfiguration1.setBackupStrategy(BackupStrategy.SCALE_DOWN);
-      backupConfiguration1.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      HAPolicy haPolicy = new HAPolicy();
-      ArrayList<String> scaleDownConnectors = new ArrayList<>();
-      scaleDownConnectors.add(liveConnector1.getName());
-      haPolicy.setScaleDownConnectors(scaleDownConnectors);
-      backupConfiguration1.setHAPolicy(haPolicy);
-      liveConfiguration1.getBackupServerConfigurations().add(backupConfiguration1);
-
-      liveServer1 = createTestableServer(liveConfiguration1, nodeManagerLive1, nodeManagerLive2, 1);
-
-      Configuration liveConfiguration2 = super.createDefaultConfig();
-      liveConfiguration2.getAcceptorConfigurations().clear();
-      liveConfiguration2.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(2));
-      liveConfiguration2.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfiguration2.getHAPolicy().setFailbackDelay(1000);
-      liveConfiguration2.setJournalDirectory(getTestDir() + "/journal2");
-      liveConfiguration2.setBindingsDirectory(getTestDir() + "/bindings2");
-      liveConfiguration2.setLargeMessagesDirectory(getTestDir() + "/largemessage2");
-      liveConfiguration2.setPagingDirectory(getTestDir() + "/paging2");
-      liveConfiguration2.getQueueConfigurations().add(new CoreQueueConfiguration("jms.queue.testQueue", "jms.queue.testQueue", null, true));
-      liveConfiguration2.getQueueConfigurations().add(new CoreQueueConfiguration("jms.topic.testTopic", "jms.topic.testTopic", HornetQServerImpl.GENERIC_IGNORED_FILTER, true));
-
-      basicClusterConnectionConfig(liveConfiguration2, liveConnector2.getName(), liveConnector1.getName());
-      liveConfiguration2.getConnectorConfigurations().put(liveConnector1.getName(), liveConnector1);
-      liveConfiguration2.getConnectorConfigurations().put(liveConnector2.getName(), liveConnector2);
-
-      Configuration backupConfiguration2 = liveConfiguration2.copy();
-      backupConfiguration2.setJournalDirectory(getTestDir() + "/journal1");
-      backupConfiguration2.setBindingsDirectory(getTestDir() + "/bindings1");
-      backupConfiguration2.setLargeMessagesDirectory(getTestDir() + "/largemessage1");
-      backupConfiguration2.setPagingDirectory(getTestDir() + "/paging1");
-      backupConfiguration2.setBackupStrategy(BackupStrategy.SCALE_DOWN);
-      backupConfiguration2.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      HAPolicy haPolicy2 = new HAPolicy();
-      ArrayList<String> scaleDownConnectors2 = new ArrayList<>();
-      scaleDownConnectors2.add(liveConnector2.getName());
-      haPolicy2.setScaleDownConnectors(scaleDownConnectors2);
-      backupConfiguration2.setHAPolicy(haPolicy2);
-      liveConfiguration2.getBackupServerConfigurations().add(backupConfiguration2);
-
-      liveServer2 = createTestableServer(liveConfiguration2, nodeManagerLive2, nodeManagerLive1, 2);
-   }
-
-   private TransportConfiguration getAcceptorTransportConfiguration(int node)
-   {
-      HashMap<String, Object> params = new HashMap<>();
-      params.put("server-id", "" + node);
-      return new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params);
-   }
-
-   private TransportConfiguration getConnectorTransportConfiguration(int node)
-   {
-      HashMap<String, Object> params = new HashMap<>();
-      params.put("server-id", "" + node);
-      return new TransportConfiguration(INVM_CONNECTOR_FACTORY, params);
-   }
-
-   protected TestableServer createTestableServer(Configuration config, NodeManager liveNodeManager, NodeManager backupNodeManager, int id)
-   {
-      return new SameProcessHornetQServer(
-            createColocatedInVMFailoverServer(true, config, liveNodeManager, backupNodeManager, id));
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackAutoTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackAutoTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackAutoTest.java
index 9debe77..22caa1a 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackAutoTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackAutoTest.java
@@ -25,7 +25,9 @@ import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
+import org.hornetq.core.server.cluster.ha.SharedStoreSlavePolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.jms.client.HornetQTextMessage;
 import org.hornetq.tests.integration.IntegrationTestLogger;
@@ -56,6 +58,7 @@ public class FailBackAutoTest extends FailoverTestBase
    @Test
    public void testAutoFailback() throws Exception
    {
+      ((SharedStoreSlavePolicy)backupServer.getServer().getHAPolicy()).setRestartBackup(false);
       createSessionFactory();
       final CountDownLatch latch = new CountDownLatch(1);
 
@@ -163,7 +166,6 @@ public class FailBackAutoTest extends FailoverTestBase
       listener = new CountDownSessionFailureListener(session);
 
       session.addFailureListener(listener);
-
       log.info("restarting live node now");
       liveServer.start();
 
@@ -202,6 +204,7 @@ public class FailBackAutoTest extends FailoverTestBase
    @Test
    public void testFailBack() throws Exception
    {
+      ((SharedStoreSlavePolicy)backupServer.getServer().getHAPolicy()).setRestartBackup(false);
       createSessionFactory();
       ClientSession session = sendAndConsume(sf, true);
 
@@ -218,8 +221,8 @@ public class FailBackAutoTest extends FailoverTestBase
       producer = session.createProducer(FailoverTestBase.ADDRESS);
       sendMessages(session, producer, 2 * NUM_MESSAGES);
       session.commit();
-      assertFalse("must NOT be a backup", liveServer.getServer().getConfiguration().getHAPolicy().isBackup());
-      adaptLiveConfigForReplicatedFailBack(liveServer.getServer().getConfiguration());
+      assertFalse("must NOT be a backup", liveServer.getServer().getHAPolicy().isBackup());
+      adaptLiveConfigForReplicatedFailBack(liveServer);
 
       CountDownSessionFailureListener listener = new CountDownSessionFailureListener(session);
       session.addFailureListener(listener);
@@ -254,28 +257,32 @@ public class FailBackAutoTest extends FailoverTestBase
    {
       nodeManager = new InVMNodeManager(false);
 
-      backupConfig = super.createDefaultConfig();
-      backupConfig.getAcceptorConfigurations().clear();
-      backupConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(false));
-      backupConfig.setSecurityEnabled(false);
-      backupConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      backupConfig.getHAPolicy().setFailbackDelay(1000);
       TransportConfiguration liveConnector = getConnectorTransportConfiguration(true);
       TransportConfiguration backupConnector = getConnectorTransportConfiguration(false);
-      backupConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      backupConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-      basicClusterConnectionConfig(backupConfig, backupConnector.getName(), liveConnector.getName());
+
+      backupConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(false))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()
+                                      .setFailbackDelay(1000)
+                                      .setRestartBackup(true))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+         .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName()));
+
       backupServer = createTestableServer(backupConfig);
 
-      liveConfig = super.createDefaultConfig();
-      liveConfig.getAcceptorConfigurations().clear();
-      liveConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true));
-      liveConfig.setSecurityEnabled(false);
-      liveConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfig.getHAPolicy().setFailbackDelay(1000);
-      basicClusterConnectionConfig(liveConfig, liveConnector.getName(), backupConnector.getName());
-      liveConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      liveConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
+      liveConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()
+                                      .setFailbackDelay(100))
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName()))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector);
+
       liveServer = createTestableServer(liveConfig);
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackManualTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackManualTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackManualTest.java
index 7575208..366c2ad 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackManualTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailBackManualTest.java
@@ -11,15 +11,9 @@
  * permissions and limitations under the License.
  */
 package org.hornetq.tests.integration.cluster.failover;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
-import org.junit.Before;
-
-import org.junit.Test;
 
 import java.util.concurrent.TimeUnit;
 
-import org.junit.Assert;
-
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientConsumer;
@@ -29,11 +23,16 @@ import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.jms.client.HornetQTextMessage;
 import org.hornetq.tests.integration.cluster.util.TestableServer;
 import org.hornetq.tests.util.CountDownSessionFailureListener;
 import org.hornetq.tests.util.TransportConfigurationUtils;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
 
 /**
  * @author <a href="mailto:andy.taylor@jboss.com">Andy Taylor</a>
@@ -73,7 +72,8 @@ public class FailBackManualTest extends FailoverTestBase
 
       backupServer.start();
 
-      assertTrue(listener.getLatch().await(5, TimeUnit.SECONDS));
+      assertTrue(listener.getLatch()
+                    .await(5, TimeUnit.SECONDS));
 
       ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);
 
@@ -85,8 +85,6 @@ public class FailBackManualTest extends FailoverTestBase
 
       session.removeFailureListener(listener);
 
-      liveConfig.setAllowAutoFailBack(false);
-
       Thread t = new Thread(new ServerStarter(liveServer));
 
       t.start();
@@ -113,29 +111,30 @@ public class FailBackManualTest extends FailoverTestBase
    protected void createConfigs() throws Exception
    {
       nodeManager = new InVMNodeManager(false);
-
-      backupConfig = super.createDefaultConfig();
-      backupConfig.getAcceptorConfigurations().clear();
-      backupConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(false));
-      backupConfig.setSecurityEnabled(false);
-      backupConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
       TransportConfiguration liveConnector = getConnectorTransportConfiguration(true);
       TransportConfiguration backupConnector = getConnectorTransportConfiguration(false);
-      backupConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      backupConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-      basicClusterConnectionConfig(backupConfig, backupConnector.getName(), liveConnector.getName());
-      backupConfig.getHAPolicy().setAllowAutoFailBack(false);
+
+      backupConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(false))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()
+                                      .setAllowFailBack(false))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+         .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName()));
+
       backupServer = createTestableServer(backupConfig);
 
-      liveConfig = super.createDefaultConfig();
-      liveConfig.getAcceptorConfigurations().clear();
-      liveConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true));
-      liveConfig.setSecurityEnabled(false);
-      liveConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      basicClusterConnectionConfig(liveConfig, liveConnector.getName(), backupConnector.getName());
-      liveConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      liveConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-      liveConfig.setAllowAutoFailBack(false);
+      liveConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration())
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName()));
+
       liveServer = createTestableServer(liveConfig);
    }
 
@@ -168,12 +167,13 @@ public class FailBackManualTest extends FailoverTestBase
       for (int i = 0; i < numMessages; i++)
       {
          ClientMessage message = session.createMessage(HornetQTextMessage.TYPE,
-               false,
-               0,
-               System.currentTimeMillis(),
-               (byte) 1);
+                                                       false,
+                                                       0,
+                                                       System.currentTimeMillis(),
+                                                       (byte) 1);
          message.putIntProperty(new SimpleString("count"), i);
-         message.getBodyBuffer().writeString("aardvarks");
+         message.getBodyBuffer()
+            .writeString("aardvarks");
          producer.send(message);
       }
 
@@ -185,7 +185,8 @@ public class FailBackManualTest extends FailoverTestBase
       {
          ClientMessage message2 = consumer.receive();
 
-         Assert.assertEquals("aardvarks", message2.getBodyBuffer().readString());
+         Assert.assertEquals("aardvarks", message2.getBodyBuffer()
+            .readString());
 
          Assert.assertEquals(i, message2.getObjectProperty(new SimpleString("count")));
 
@@ -207,7 +208,8 @@ public class FailBackManualTest extends FailoverTestBase
    @Override
    protected void setBody(final int i, final ClientMessage message)
    {
-      message.getBodyBuffer().writeString("message" + i);
+      message.getBodyBuffer()
+         .writeString("message" + i);
    }
 
    static class ServerStarter implements Runnable

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverListenerTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverListenerTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverListenerTest.java
index d277dc0..ccc3592 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverListenerTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverListenerTest.java
@@ -26,7 +26,8 @@ import org.hornetq.api.core.client.FailoverEventType;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.jms.client.HornetQTextMessage;
 import org.hornetq.tests.integration.IntegrationTestLogger;
@@ -189,29 +190,31 @@ public class FailoverListenerTest extends FailoverTestBase
    protected void createConfigs() throws Exception
    {
       nodeManager = new InVMNodeManager(false);
-
-      backupConfig = super.createDefaultConfig();
-      backupConfig.getAcceptorConfigurations().clear();
-      backupConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(false));
-      backupConfig.setSecurityEnabled(false);
-      backupConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      backupConfig.getHAPolicy().setFailbackDelay(1000);
       TransportConfiguration liveConnector = getConnectorTransportConfiguration(true);
       TransportConfiguration backupConnector = getConnectorTransportConfiguration(false);
-      backupConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      backupConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
-      basicClusterConnectionConfig(backupConfig, backupConnector.getName(), liveConnector.getName());
+
+      backupConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(false))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration()
+                                      .setFailbackDelay(1000))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector)
+         .addClusterConfiguration(basicClusterConnectionConfig(backupConnector.getName(), liveConnector.getName()));
+
       backupServer = createTestableServer(backupConfig);
 
-      liveConfig = super.createDefaultConfig();
-      liveConfig.getAcceptorConfigurations().clear();
-      liveConfig.getAcceptorConfigurations().add(getAcceptorTransportConfiguration(true));
-      liveConfig.setSecurityEnabled(false);
-      liveConfig.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      liveConfig.getHAPolicy().setFailbackDelay(1000);
-      basicClusterConnectionConfig(liveConfig, liveConnector.getName(), backupConnector.getName());
-      liveConfig.getConnectorConfigurations().put(liveConnector.getName(), liveConnector);
-      liveConfig.getConnectorConfigurations().put(backupConnector.getName(), backupConnector);
+      liveConfig = super.createDefaultConfig()
+         .clearAcceptorConfigurations()
+         .addAcceptorConfiguration(getAcceptorTransportConfiguration(true))
+         .setSecurityEnabled(false)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration()
+                                      .setFailbackDelay(1000))
+         .addClusterConfiguration(basicClusterConnectionConfig(liveConnector.getName(), backupConnector.getName()))
+         .addConnectorConfiguration(liveConnector.getName(), liveConnector)
+         .addConnectorConfiguration(backupConnector.getName(), backupConnector);
+
       liveServer = createTestableServer(liveConfig);
    }
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTest.java
index f82725d..c1f262d 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/failover/FailoverTest.java
@@ -41,7 +41,12 @@ import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.MessageHandler;
 import org.hornetq.api.core.client.ServerLocator;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
+import org.hornetq.core.server.cluster.ha.BackupPolicy;
 import org.hornetq.core.server.cluster.ha.HAPolicy;
+import org.hornetq.core.server.cluster.ha.ReplicaPolicy;
+import org.hornetq.core.server.cluster.ha.ReplicatedPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreMasterPolicy;
+import org.hornetq.core.server.cluster.ha.SharedStoreSlavePolicy;
 import org.hornetq.core.server.impl.InVMNodeManager;
 import org.hornetq.core.transaction.impl.XidImpl;
 import org.hornetq.jms.client.HornetQTextMessage;
@@ -585,7 +590,12 @@ public class FailoverTest extends FailoverTestBase
    public void testFailBack() throws Exception
    {
       boolean doFailBack = true;
-      backupServer.getServer().getConfiguration().setMaxSavedReplicatedJournalSize(0);
+      HAPolicy haPolicy = backupServer.getServer().getHAPolicy();
+      if (haPolicy instanceof ReplicaPolicy)
+      {
+         ((ReplicaPolicy)haPolicy).setMaxSavedReplicatedJournalsSize(0);
+      }
+
       simpleReplication(doFailBack);
    }
 
@@ -618,8 +628,8 @@ public class FailoverTest extends FailoverTestBase
       Thread.sleep(100);
       assertFalse("backup is not running", backupServer.isStarted());
 
-      assertFalse("must NOT be a backup", liveServer.getServer().getConfiguration().getHAPolicy().isBackup());
-      adaptLiveConfigForReplicatedFailBack(liveServer.getServer().getConfiguration());
+      assertFalse("must NOT be a backup", liveServer.getServer().getHAPolicy() instanceof BackupPolicy);
+      adaptLiveConfigForReplicatedFailBack(liveServer);
       beforeRestart(liveServer);
       liveServer.start();
       assertTrue("live initialized...", liveServer.getServer().waitForActivation(15, TimeUnit.SECONDS));
@@ -629,7 +639,7 @@ public class FailoverTest extends FailoverTestBase
       ClientSession session2 = createSession(sf, false, false);
       session2.start();
       ClientConsumer consumer2 = session2.createConsumer(FailoverTestBase.ADDRESS);
-      boolean replication = !liveServer.getServer().getConfiguration().getHAPolicy().isSharedStore();
+      boolean replication = liveServer.getServer().getHAPolicy() instanceof ReplicatedPolicy;
       if (replication)
          receiveMessages(consumer2, 0, NUM_MESSAGES, true);
       assertNoMoreMessages(consumer2);
@@ -658,7 +668,8 @@ public class FailoverTest extends FailoverTestBase
 
       backupServer.stop(); // Backup stops!
       backupServer.start();
-      assertTrue(backupServer.getServer().waitForBackupSync(10, TimeUnit.SECONDS));
+
+      waitForRemoteBackupSynchronization(backupServer.getServer());
 
       session.start();
       ClientConsumer consumer = addClientConsumer(session.createConsumer(FailoverTestBase.ADDRESS));
@@ -675,7 +686,7 @@ public class FailoverTest extends FailoverTestBase
       backupServer.stop(); // Backup stops!
       beforeRestart(backupServer);
       backupServer.start();
-      assertTrue(backupServer.getServer().waitForBackupSync(30, TimeUnit.SECONDS));
+      waitForRemoteBackupSynchronization(backupServer.getServer());
       backupServer.stop(); // Backup stops!
 
       liveServer.stop();
@@ -723,8 +734,8 @@ public class FailoverTest extends FailoverTestBase
       assertEquals("backup must be running with the same nodeID", liveId, backupServer.getServer().getNodeID());
       if (doFailBack)
       {
-         assertFalse("must NOT be a backup", liveServer.getServer().getConfiguration().getHAPolicy().isBackup());
-         adaptLiveConfigForReplicatedFailBack(liveServer.getServer().getConfiguration());
+         assertFalse("must NOT be a backup", liveServer.getServer().getHAPolicy().isBackup());
+         adaptLiveConfigForReplicatedFailBack(liveServer);
          beforeRestart(liveServer);
          liveServer.start();
          assertTrue("live initialized...", liveServer.getServer().waitForActivation(40, TimeUnit.SECONDS));
@@ -1838,7 +1849,8 @@ public class FailoverTest extends FailoverTestBase
       receiveMessages(consumer);
    }
 
-   public void _testForceBlockingReturn() throws Exception
+   @Test
+   public void testForceBlockingReturn() throws Exception
    {
       locator.setBlockOnNonDurableSend(true);
       locator.setBlockOnDurableSend(true);
@@ -1847,8 +1859,7 @@ public class FailoverTest extends FailoverTestBase
       createClientSessionFactory();
 
       // Add an interceptor to delay the send method so we can get time to cause failover before it returns
-
-      // liveServer.getRemotingService().addIncomingInterceptor(new DelayInterceptor());
+      liveServer.getServer().getRemotingService().addIncomingInterceptor(new DelayInterceptor());
 
       final ClientSession session = createSession(sf, true, true, 0);
 
@@ -1888,8 +1899,12 @@ public class FailoverTest extends FailoverTestBase
 
       Assert.assertNotNull(sender.e);
 
+      Assert.assertNotNull(sender.e.getCause());
+
       Assert.assertEquals(sender.e.getType(), HornetQExceptionType.UNBLOCKED);
 
+      Assert.assertEquals(((HornetQException)sender.e.getCause()).getType(), HornetQExceptionType.DISCONNECTED);
+
       session.close();
    }
 
@@ -2159,7 +2174,7 @@ public class FailoverTest extends FailoverTestBase
    public void testBackupServerNotRemoved() throws Exception
    {
       // HORNETQ-720 Disabling test for replicating backups.
-      if (!backupServer.getServer().getConfiguration().getHAPolicy().isSharedStore())
+      if (!(backupServer.getServer().getHAPolicy() instanceof SharedStoreSlavePolicy))
       {
          waitForComponent(backupServer, 1);
          return;
@@ -2297,11 +2312,11 @@ public class FailoverTest extends FailoverTestBase
       // To reload security or other settings that are read during startup
       beforeRestart(backupServer);
 
-      if (!backupServer.getServer().getConfiguration().getHAPolicy().isSharedStore())
+      if (!backupServer.getServer().getHAPolicy().isSharedStore())
       {
          // XXX
          // this test would not make sense in the remote replication use case, without the following
-         backupServer.getServer().getConfiguration().getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
+         backupServer.getServer().setHAPolicy(new SharedStoreMasterPolicy());
       }
 
       backupServer.start();


[11/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeStartTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeStartTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeStartTest.java
index cc9d158..edccaf9 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeStartTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeStartTest.java
@@ -13,11 +13,12 @@
 package org.hornetq.tests.integration.cluster.bridge;
 
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.api.core.client.ClientConsumer;
@@ -36,6 +37,8 @@ import org.hornetq.tests.integration.IntegrationTestLogger;
 import org.hornetq.tests.util.ServiceTestBase;
 import org.junit.Assert;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 
 /**
  * A BridgeStartTest
@@ -44,13 +47,31 @@ import org.junit.Test;
  *         <p/>
  *         Created 14 Jan 2009 14:05:01
  */
+@RunWith(value = Parameterized.class)
 public class BridgeStartTest extends ServiceTestBase
 {
+
+   @Parameterized.Parameters(name = "isNetty={0}")
+   public static Collection getParameters()
+   {
+      return Arrays.asList(new Object[][]{
+         {true},
+         {false}
+      });
+   }
+
+   public BridgeStartTest(boolean netty)
+   {
+      this.netty = netty;
+   }
+
+   private final boolean netty;
+
    private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER;
 
    protected boolean isNetty()
    {
-      return false;
+      return netty;
    }
 
    private String getConnector()
@@ -98,37 +119,30 @@ public class BridgeStartTest extends ServiceTestBase
 
          final String bridgeName = "bridge1";
 
-         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName,
-                                                                           queueName0,
-                                                                           forwardAddress,
-                                                                           null,
-                                                                           null,
-                                                                           HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                           HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                           HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                           1000,
-                                                                           HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                           1d,
-                                                                           -1,
-                                                                           0,
-                                                                           0,
-                                                                           true,
-                                                                           1024,
-                                                                           staticConnectors,
-                                                                           false,
-                                                                           HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                           HornetQDefaultConfiguration.getDefaultClusterPassword());
+         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+            .setName(bridgeName)
+            .setQueueName(queueName0)
+            .setForwardingAddress(forwardAddress)
+            .setRetryInterval(1000)
+            .setReconnectAttempts(0)
+            .setReconnectAttemptsOnSameNode(0)
+            .setConfirmationWindowSize(1024)
+            .setStaticConnectors(staticConnectors);
 
          List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
          bridgeConfigs.add(bridgeConfiguration);
          server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+            .setAddress(testAddress)
+            .setName(queueName0);
          List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs0.add(queueConfig0);
          server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+            .setAddress(forwardAddress)
+            .setName(queueName1);
          List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs1.add(queueConfig1);
          server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -272,37 +286,30 @@ public class BridgeStartTest extends ServiceTestBase
 
       final String bridgeName = "bridge1";
 
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName,
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        500,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        0,
-                                                                        true,
-                                                                        1024,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName(bridgeName)
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setRetryInterval(500)
+         .setReconnectAttempts(-1)
+         .setReconnectAttemptsOnSameNode(0)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(staticConnectors);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName1);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -492,37 +499,31 @@ public class BridgeStartTest extends ServiceTestBase
 
          final String bridgeName = "bridge1";
 
-         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName,
-                                                                           queueName0,
-                                                                           forwardAddress,
-                                                                           null,
-                                                                           null,
-                                                                           HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                           HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                           HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                           1000,
-                                                                           HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                           1d,
-                                                                           -1,
-                                                                           0,
-                                                                           0,
-                                                                           false,
-                                                                           1024,
-                                                                           staticConnectors,
-                                                                           false,
-                                                                           HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                           HornetQDefaultConfiguration.getDefaultClusterPassword());
+         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+            .setName(bridgeName)
+            .setQueueName(queueName0)
+            .setForwardingAddress(forwardAddress)
+            .setRetryInterval(1000)
+            .setReconnectAttempts(0)
+            .setReconnectAttemptsOnSameNode(0)
+            .setUseDuplicateDetection(false)
+            .setConfirmationWindowSize(1024)
+            .setStaticConnectors(staticConnectors);
 
          List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
          bridgeConfigs.add(bridgeConfiguration);
          server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+            .setAddress(testAddress)
+            .setName(queueName0);
          List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs0.add(queueConfig0);
          server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+            .setAddress(forwardAddress)
+            .setName(queueName1);
          List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs1.add(queueConfig1);
          server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -652,37 +653,30 @@ public class BridgeStartTest extends ServiceTestBase
 
          final String bridgeName = "bridge1";
 
-         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName,
-                                                                           queueName0,
-                                                                           forwardAddress,
-                                                                           null,
-                                                                           null,
-                                                                           HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                           HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                           HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                           1000,
-                                                                           HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                           1d,
-                                                                           -1,
-                                                                           1,
-                                                                           0,
-                                                                           true,
-                                                                           1024,
-                                                                           staticConnectors,
-                                                                           false,
-                                                                           HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                           HornetQDefaultConfiguration.getDefaultClusterPassword());
+         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+            .setName(bridgeName)
+            .setQueueName(queueName0)
+            .setForwardingAddress(forwardAddress)
+            .setRetryInterval(1000)
+            .setReconnectAttempts(1)
+            .setReconnectAttemptsOnSameNode(0)
+            .setConfirmationWindowSize(1024)
+            .setStaticConnectors(staticConnectors);
 
          List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
          bridgeConfigs.add(bridgeConfiguration);
          server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+            .setAddress(testAddress)
+            .setName(queueName0);
          List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs0.add(queueConfig0);
          server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+            .setAddress(forwardAddress)
+            .setName(queueName1);
          List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs1.add(queueConfig1);
          server1.getConfiguration().setQueueConfigurations(queueConfigs1);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTest.java
index b6da77a..f2f0966 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTest.java
@@ -13,6 +13,8 @@
 package org.hornetq.tests.integration.cluster.bridge;
 
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -21,7 +23,6 @@ import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Interceptor;
@@ -40,6 +41,7 @@ import org.hornetq.core.postoffice.DuplicateIDCache;
 import org.hornetq.core.postoffice.impl.PostOfficeImpl;
 import org.hornetq.core.protocol.core.Packet;
 import org.hornetq.core.protocol.core.impl.wireformat.SessionSendContinuationMessage;
+import org.hornetq.core.protocol.core.impl.wireformat.SessionSendLargeMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.SessionSendMessage;
 import org.hornetq.core.remoting.impl.invm.TransportConstants;
 import org.hornetq.core.server.HornetQServer;
@@ -56,6 +58,8 @@ import org.hornetq.utils.ReusableLatch;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 
 /**
  * A JMSBridgeTest
@@ -65,6 +69,7 @@ import org.junit.Test;
  *         <p/>
  *         Created 14 Jan 2009 14:05:01
  */
+@RunWith(value = Parameterized.class)
 public class BridgeTest extends ServiceTestBase
 {
 
@@ -72,9 +77,26 @@ public class BridgeTest extends ServiceTestBase
    private HornetQServer server1;
    private ServerLocator locator;
 
+   private final boolean netty;
+
+
+   @Parameterized.Parameters(name = "isNetty={0}")
+   public static Collection getParameters()
+   {
+      return Arrays.asList(new Object[][]{
+         {true},
+         {false}
+      });
+   }
+
+   public BridgeTest(boolean isNetty)
+   {
+      this.netty = isNetty;
+   }
+
    protected boolean isNetty()
    {
-      return false;
+      return netty;
    }
 
 
@@ -152,39 +174,30 @@ public class BridgeTest extends ServiceTestBase
 
       ArrayList<String> connectorConfig = new ArrayList<String>();
       connectorConfig.add(server1tc.getName());
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        1000,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        false,
-                                                                        // Choose confirmation size to make sure acks
-                                                                        // are sent
-                                                                        numMessages * messageSize / 2,
-                                                                        connectorConfig,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setRetryInterval(1000)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setUseDuplicateDetection(false)
+         .setConfirmationWindowSize(numMessages * messageSize / 2)
+         .setStaticConnectors(connectorConfig);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName1);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -228,7 +241,7 @@ public class BridgeTest extends ServiceTestBase
 
       for (int i = 0; i < numMessages; i++)
       {
-         ClientMessage message = consumer1.receive(200);
+         ClientMessage message = consumer1.receive(5000);
 
          Assert.assertNotNull(message);
 
@@ -290,6 +303,7 @@ public class BridgeTest extends ServiceTestBase
          public boolean intercept(Packet packet, RemotingConnection connection) throws HornetQException
          {
             if (ignoreSends && packet instanceof SessionSendMessage ||
+               ignoreSends && packet instanceof SessionSendLargeMessage ||
                ignoreSends && packet instanceof SessionSendContinuationMessage && !((SessionSendContinuationMessage) packet).isContinues())
             {
                System.out.println("Ignored");
@@ -298,6 +312,7 @@ public class BridgeTest extends ServiceTestBase
             }
             else
             {
+               System.out.println(packet);
                return true;
             }
          }
@@ -331,28 +346,16 @@ public class BridgeTest extends ServiceTestBase
 
       ArrayList<String> connectorConfig = new ArrayList<String>();
       connectorConfig.add(server1tc.getName());
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        1000,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        false,
-                                                                        // Choose confirmation size to make sure acks
-                                                                        // are sent
-                                                                        numMessages * messageSize / 2,
-                                                                        connectorConfig,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setRetryInterval(1000)
+         .setReconnectAttempts(-1)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setUseDuplicateDetection(false)
+         .setConfirmationWindowSize(numMessages * messageSize / 2)
+         .setStaticConnectors(connectorConfig);
 
       bridgeConfiguration.setCallTimeout(500);
 
@@ -360,12 +363,16 @@ public class BridgeTest extends ServiceTestBase
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName1);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -522,37 +529,31 @@ public class BridgeTest extends ServiceTestBase
 
       ArrayList<String> staticConnectors = new ArrayList<String>();
       staticConnectors.add(server1tc.getName());
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        filterString,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        1000,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        false,
-                                                                        0,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setFilterString(filterString)
+         .setRetryInterval(1000)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setUseDuplicateDetection(false)
+         .setConfirmationWindowSize(0)
+         .setStaticConnectors(staticConnectors);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName1);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -684,32 +685,23 @@ public class BridgeTest extends ServiceTestBase
 
       ArrayList<String> staticConnectors = new ArrayList<String>();
       staticConnectors.add(server1tc.getName());
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        100,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        false,
-                                                                        1024,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setRetryInterval(100)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setUseDuplicateDetection(false)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(staticConnectors);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
@@ -817,32 +809,22 @@ public class BridgeTest extends ServiceTestBase
 
       ArrayList<String> staticConnectors = new ArrayList<String>();
       staticConnectors.add(server1tc.getName());
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        100,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        true,
-                                                                        0,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setRetryInterval(100)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setConfirmationWindowSize(0)
+         .setStaticConnectors(staticConnectors);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
@@ -998,37 +980,32 @@ public class BridgeTest extends ServiceTestBase
       ArrayList<String> staticConnectors = new ArrayList<String>();
       staticConnectors.add(server1tc.getName());
 
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        SimpleTransformer.class.getName(),
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        1000,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        false,
-                                                                        1024,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setTransformerClassName(SimpleTransformer.class.getName())
+         .setRetryInterval(1000)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setUseDuplicateDetection(false)
+         .setConfirmationWindowSize(1024)
+         .setStaticConnectors(staticConnectors);
+
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName1);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -1126,37 +1103,30 @@ public class BridgeTest extends ServiceTestBase
       ArrayList<String> staticConnectors = new ArrayList<String>();
       staticConnectors.add(server1tc.getName());
 
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                        queueName0,
-                                                                        forwardAddress,
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        1000,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        false,
-                                                                        0,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setForwardingAddress(forwardAddress)
+         .setRetryInterval(1000)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setUseDuplicateDetection(false)
+         .setConfirmationWindowSize(0)
+         .setStaticConnectors(staticConnectors);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(forwardAddress)
+         .setName(queueName1);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -1380,26 +1350,15 @@ public class BridgeTest extends ServiceTestBase
          ArrayList<String> staticConnectors = new ArrayList<String>();
          staticConnectors.add(server1tc.getName());
 
-         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                           queueName0,
-                                                                           forwardAddress,
-                                                                           null,
-                                                                           null,
-                                                                           HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                           HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                           HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                           1,
-                                                                           HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                           1d,
-                                                                           -1,
-                                                                           -1,
-                                                                           -1,
-                                                                           false,
-                                                                           1,
-                                                                           staticConnectors,
-                                                                           false,
-                                                                           HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                           HornetQDefaultConfiguration.getDefaultClusterPassword());
+         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+            .setName("bridge1")
+            .setQueueName(queueName0)
+            .setForwardingAddress(forwardAddress)
+            .setRetryInterval(1)
+            .setReconnectAttemptsOnSameNode(-1)
+            .setUseDuplicateDetection(false)
+            .setConfirmationWindowSize(1)
+            .setStaticConnectors(staticConnectors);
 
          bridgeConfiguration.setCallTimeout(1000);
 
@@ -1409,12 +1368,16 @@ public class BridgeTest extends ServiceTestBase
          bridgeConfigs.add(bridgeConfiguration);
          server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+            .setAddress(testAddress)
+            .setName(queueName0);
          List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs0.add(queueConfig0);
          server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+            .setAddress(forwardAddress)
+            .setName(queueName1);
          List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs1.add(queueConfig1);
          server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -1671,37 +1634,30 @@ public class BridgeTest extends ServiceTestBase
          ArrayList<String> staticConnectors = new ArrayList<String>();
          staticConnectors.add(server1tc.getName());
 
-         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1",
-                                                                           queueName0,
-                                                                           forwardAddress,
-                                                                           null,
-                                                                           null,
-                                                                           HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                           HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                           HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                           1000,
-                                                                           HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                           1d,
-                                                                           -1,
-                                                                           -1,
-                                                                           -1,
-                                                                           false,
-                                                                           1024,
-                                                                           staticConnectors,
-                                                                           false,
-                                                                           HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                           HornetQDefaultConfiguration.getDefaultClusterPassword());
+         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+            .setName("bridge1")
+            .setQueueName(queueName0)
+            .setForwardingAddress(forwardAddress)
+            .setRetryInterval(1000)
+            .setReconnectAttemptsOnSameNode(-1)
+            .setUseDuplicateDetection(false)
+            .setConfirmationWindowSize(1024)
+            .setStaticConnectors(staticConnectors);
 
          List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
          bridgeConfigs.add(bridgeConfiguration);
          server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+            .setAddress(testAddress)
+            .setName(queueName0);
          List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs0.add(queueConfig0);
          server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+            .setAddress(forwardAddress)
+            .setName(queueName1);
          List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs1.add(queueConfig1);
          server1.getConfiguration().setQueueConfigurations(queueConfigs1);
@@ -1827,43 +1783,31 @@ public class BridgeTest extends ServiceTestBase
 
       ArrayList<String> staticConnectors = new ArrayList<String>();
       staticConnectors.add(server1tc.getName());
-      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration("bridge1", queueName0, null, // pass a null
-                                                                        // forwarding
-                                                                        // address to
-                                                                        // use messages'
-                                                                        // original
-                                                                        // address
-                                                                        null,
-                                                                        null,
-                                                                        HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                        HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                        1000,
-                                                                        HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                        1d,
-                                                                        -1,
-                                                                        -1,
-                                                                        -1,
-                                                                        false,
-                                                                        // Choose confirmation size to make sure acks
-                                                                        // are sent
-                                                                        numMessages * messageSize / 2,
-                                                                        staticConnectors,
-                                                                        false,
-                                                                        HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                        HornetQDefaultConfiguration.getDefaultClusterPassword());
+      // do not set forwarding address (defaults to null) to use messages' original address
+      BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+         .setName("bridge1")
+         .setQueueName(queueName0)
+         .setRetryInterval(1000)
+         .setReconnectAttemptsOnSameNode(-1)
+         .setUseDuplicateDetection(false)
+         .setConfirmationWindowSize(numMessages * messageSize / 2)
+         .setStaticConnectors(staticConnectors);
 
       List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
       bridgeConfigs.add(bridgeConfiguration);
       server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+      CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName0);
       List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs0.add(queueConfig0);
       server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
       // on server #1, we bind queueName1 to same address testAddress
-      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(testAddress, queueName1, null, true);
+      CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+         .setAddress(testAddress)
+         .setName(queueName1);
       List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
       queueConfigs1.add(queueConfig1);
       server1.getConfiguration().setQueueConfigurations(queueConfigs1);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTestBase.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTestBase.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTestBase.java
index 12518fe..316e98e 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTestBase.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeTestBase.java
@@ -17,11 +17,12 @@ import java.util.concurrent.TimeUnit;
 
 import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.config.Configuration;
+import org.hornetq.core.config.ha.SharedStoreMasterPolicyConfiguration;
+import org.hornetq.core.config.ha.SharedStoreSlavePolicyConfiguration;
 import org.hornetq.core.remoting.impl.invm.InVMConnector;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServers;
 import org.hornetq.core.server.NodeManager;
-import org.hornetq.core.server.cluster.ha.HAPolicy;
 import org.hornetq.tests.util.InVMNodeManagerServer;
 import org.hornetq.tests.util.UnitTestCase;
 import org.junit.After;
@@ -60,30 +61,32 @@ public abstract class BridgeTestBase extends UnitTestCase
                                                final boolean netty,
                                                final NodeManager nodeManager) throws Exception
    {
-      Configuration serviceConf = createBasicConfig();
-      serviceConf.setSecurityEnabled(false);
-      serviceConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.SHARED_STORE);
-      serviceConf.setJournalType(getDefaultJournalType());
-      serviceConf.setBindingsDirectory(getBindingsDir(id, false));
-      serviceConf.setJournalMinFiles(2);
-      serviceConf.setJournalDirectory(getJournalDir(id, false));
-      serviceConf.setPagingDirectory(getPageDir(id, false));
-      serviceConf.setLargeMessagesDirectory(getLargeMessagesDir(id, false));
-      // these tests don't need any big storage so limiting the size of the journal files to speed up the test
-      serviceConf.setJournalFileSize(100 * 1024);
+      TransportConfiguration tc = new TransportConfiguration();
 
       if (netty)
       {
          params.put(org.hornetq.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME,
                     org.hornetq.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + id);
-         serviceConf.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params));
+         tc = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params);
 
       }
       else
       {
          params.put(org.hornetq.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, id);
-         serviceConf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params));
+         tc = new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params);
       }
+      Configuration serviceConf = createBasicConfig()
+         .setJournalType(getDefaultJournalType())
+         .setBindingsDirectory(getBindingsDir(id, false))
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir(id, false))
+         .setPagingDirectory(getPageDir(id, false))
+         .setLargeMessagesDirectory(getLargeMessagesDir(id, false))
+         // these tests don't need any big storage so limiting the size of the journal files to speed up the test
+         .setJournalFileSize(100 * 1024)
+         .addAcceptorConfiguration(tc)
+         .setHAPolicyConfiguration(new SharedStoreMasterPolicyConfiguration());
+
       HornetQServer service;
       if (nodeManager == null)
       {
@@ -93,6 +96,7 @@ public abstract class BridgeTestBase extends UnitTestCase
       {
          service = new InVMNodeManagerServer(serviceConf, nodeManager);
       }
+
       return addServer(service);
    }
 
@@ -102,30 +106,33 @@ public abstract class BridgeTestBase extends UnitTestCase
                                                      final int liveId,
                                                      final NodeManager nodeManager) throws Exception
    {
-      Configuration serviceConf = createBasicConfig();
-      serviceConf.setSecurityEnabled(false);
-      serviceConf.getHAPolicy().setPolicyType(HAPolicy.POLICY_TYPE.BACKUP_SHARED_STORE);
-      serviceConf.setJournalType(getDefaultJournalType());
-      serviceConf.setBindingsDirectory(getBindingsDir(liveId, false));
-      serviceConf.setJournalMinFiles(2);
-      serviceConf.setJournalDirectory(getJournalDir(liveId, false));
-      serviceConf.setPagingDirectory(getPageDir(liveId, false));
-      serviceConf.setLargeMessagesDirectory(getLargeMessagesDir(liveId, false));
-      // these tests don't need any big storage so limiting the size of the journal files to speed up the test
-      serviceConf.setJournalFileSize(100 * 1024);
+      TransportConfiguration tc = new TransportConfiguration();
 
       if (netty)
       {
          params.put(org.hornetq.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME,
                     org.hornetq.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + id);
-         serviceConf.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params));
+         tc = new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params);
 
       }
       else
       {
          params.put(org.hornetq.core.remoting.impl.invm.TransportConstants.SERVER_ID_PROP_NAME, id);
-         serviceConf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params));
+         tc = new TransportConfiguration(INVM_ACCEPTOR_FACTORY, params);
       }
+
+      Configuration serviceConf = createBasicConfig()
+         .setJournalType(getDefaultJournalType())
+         .setBindingsDirectory(getBindingsDir(liveId, false))
+         .setJournalMinFiles(2)
+         .setJournalDirectory(getJournalDir(liveId, false))
+         .setPagingDirectory(getPageDir(liveId, false))
+         .setLargeMessagesDirectory(getLargeMessagesDir(liveId, false))
+         // these tests don't need any big storage so limiting the size of the journal files to speed up the test
+         .setJournalFileSize(100 * 1024)
+         .addAcceptorConfiguration(tc)
+         .setHAPolicyConfiguration(new SharedStoreSlavePolicyConfiguration());
+
       HornetQServer service;
       if (nodeManager == null)
       {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java
index 1fa4feb..c904484 100644
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java
+++ b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/BridgeWithDiscoveryGroupStartTest.java
@@ -13,11 +13,12 @@
 package org.hornetq.tests.integration.cluster.bridge;
 
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.BroadcastGroupConfiguration;
 import org.hornetq.api.core.DiscoveryGroupConfiguration;
 import org.hornetq.api.core.SimpleString;
@@ -40,20 +41,42 @@ import org.hornetq.core.server.cluster.Bridge;
 import org.hornetq.tests.util.ServiceTestBase;
 import org.junit.Assert;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
 
 /**
  * A BridgeWithDiscoveryGroupStartTest
  *
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  */
+@RunWith(value = Parameterized.class)
 public class BridgeWithDiscoveryGroupStartTest extends ServiceTestBase
 {
 
+   @Parameterized.Parameters(name = "isNetty={0}")
+   public static Collection getParameters()
+   {
+      return Arrays.asList(new Object[][]{
+         {true},
+         {false}
+      });
+   }
+
+   public BridgeWithDiscoveryGroupStartTest(boolean netty)
+   {
+      this.netty = netty;
+   }
+
+
+   private final boolean netty;
+
+
+
    private static final int TIMEOUT = 2000;
 
    protected boolean isNetty()
    {
-      return false;
+      return netty;
    }
 
    @Test
@@ -94,16 +117,21 @@ public class BridgeWithDiscoveryGroupStartTest extends ServiceTestBase
          ArrayList<String> list = new ArrayList<String>();
          list.add(server1tc.getName());
 
-         UDPBroadcastGroupConfiguration endpoint = new UDPBroadcastGroupConfiguration(groupAddress, port, null, -1);
+         UDPBroadcastGroupConfiguration endpoint = new UDPBroadcastGroupConfiguration().setGroupAddress(groupAddress).setGroupPort(port);
 
-         BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration("bg1",
-                                                                                250,
-                                                                                list,
-                                                                                endpoint);
+         BroadcastGroupConfiguration bcConfig = new BroadcastGroupConfiguration()
+            .setName("bg1")
+            .setBroadcastPeriod(250)
+            .setConnectorInfos(list)
+            .setEndpointFactoryConfiguration(endpoint);
 
          server0.getConfiguration().getBroadcastGroupConfigurations().add(bcConfig);
 
-         DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration("dg1", 5000, 5000, endpoint);
+         DiscoveryGroupConfiguration dcConfig = new DiscoveryGroupConfiguration()
+            .setName("dg1")
+            .setRefreshTimeout(5000)
+            .setDiscoveryInitialWaitTimeout(5000)
+            .setBroadcastEndpointFactoryConfiguration(endpoint);
 
          server0.getConfiguration().getDiscoveryGroupConfigurations().put(dcConfig.getName(), dcConfig);
 
@@ -111,37 +139,30 @@ public class BridgeWithDiscoveryGroupStartTest extends ServiceTestBase
 
          ArrayList<String> staticConnectors = new ArrayList<String>();
          staticConnectors.add(server1tc.getName());
-         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration(bridgeName,
-                                                                           queueName0,
-                                                                           forwardAddress,
-                                                                           null,
-                                                                           null,
-                                                                           HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                                           HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
-                                                                           HornetQClient.DEFAULT_CONNECTION_TTL,
-                                                                           1000,
-                                                                           HornetQClient.DEFAULT_MAX_RETRY_INTERVAL,
-                                                                           1d,
-                                                                           -1,
-                                                                           0,
-                                                                           0,
-                                                                           true,
-                                                                           1024,
-                                                                           staticConnectors,
-                                                                           false,
-                                                                           HornetQDefaultConfiguration.getDefaultClusterUser(),
-                                                                           HornetQDefaultConfiguration.getDefaultClusterPassword());
+         BridgeConfiguration bridgeConfiguration = new BridgeConfiguration()
+            .setName(bridgeName)
+            .setQueueName(queueName0)
+            .setForwardingAddress(forwardAddress)
+            .setRetryInterval(1000)
+            .setReconnectAttempts(0)
+            .setReconnectAttemptsOnSameNode(0)
+            .setConfirmationWindowSize(1024)
+            .setStaticConnectors(staticConnectors);
 
          List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
          bridgeConfigs.add(bridgeConfiguration);
          server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);
 
-         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration(testAddress, queueName0, null, true);
+         CoreQueueConfiguration queueConfig0 = new CoreQueueConfiguration()
+            .setAddress(testAddress)
+            .setName(queueName0);
          List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs0.add(queueConfig0);
          server0.getConfiguration().setQueueConfigurations(queueConfigs0);
 
-         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration(forwardAddress, queueName1, null, true);
+         CoreQueueConfiguration queueConfig1 = new CoreQueueConfiguration()
+            .setAddress(forwardAddress)
+            .setName(queueName1);
          List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
          queueConfigs1.add(queueConfig1);
          server1.getConfiguration().setQueueConfigurations(queueConfigs1);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeReconnectTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeReconnectTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeReconnectTest.java
deleted file mode 100644
index 35504cb..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeReconnectTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.cluster.bridge;
-
-/**
- * A NettyBridgeReconnectTest
- *
- * @author <mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- */
-public class NettyBridgeReconnectTest extends BridgeReconnectTest
-{
-
-   @Override
-   protected boolean isNetty()
-   {
-      return true;
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeStartTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeStartTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeStartTest.java
deleted file mode 100644
index 1356da0..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeStartTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.cluster.bridge;
-
-/**
- * A NettyBridgeStartTest
- *
- * @author <mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- *
- *
- */
-public class NettyBridgeStartTest extends BridgeStartTest
-{
-
-   @Override
-   protected boolean isNetty()
-   {
-      return true;
-   }
-
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeTest.java
deleted file mode 100644
index 73b56c9..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.cluster.bridge;
-
-/**
- * A NettyBridgeTest
- *
- * @author <mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- *
- *
- */
-public class NettyBridgeTest extends BridgeTest
-{
-   @Override
-   protected boolean isNetty()
-   {
-      return true;
-   }
-
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeWithDiscoveryGroupStartTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeWithDiscoveryGroupStartTest.java b/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeWithDiscoveryGroupStartTest.java
deleted file mode 100644
index 5b37eb0..0000000
--- a/tests/integration-tests/src/test/java/org/hornetq/tests/integration/cluster/bridge/NettyBridgeWithDiscoveryGroupStartTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-package org.hornetq.tests.integration.cluster.bridge;
-
-/**
- * A NettyBridgeWithDiscoveryGroupStartTest
- *
- * @author <mailto:clebert.suconic@jboss.org">Clebert Suconic</a>
- *
- *
- */
-public class NettyBridgeWithDiscoveryGroupStartTest extends BridgeWithDiscoveryGroupStartTest
-{
-   @Override
-   protected boolean isNetty()
-   {
-      return true;
-   }
-}


[20/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupHandlingAbstract.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupHandlingAbstract.java b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupHandlingAbstract.java
index eeb5a49..83d72cb 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupHandlingAbstract.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupHandlingAbstract.java
@@ -19,8 +19,8 @@ import java.util.WeakHashMap;
 import java.util.concurrent.Executor;
 
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.postoffice.BindingType;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.group.GroupingHandler;
@@ -110,7 +110,7 @@ public abstract class GroupHandlingAbstract implements GroupingHandler
       props.putIntProperty(ManagementHelper.HDR_BINDING_TYPE, BindingType.LOCAL_QUEUE_INDEX);
       props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, address);
       props.putIntProperty(ManagementHelper.HDR_DISTANCE, distance);
-      Notification notification = new Notification(null, NotificationType.UNPROPOSAL, props);
+      Notification notification = new Notification(null, CoreNotificationType.UNPROPOSAL, props);
       try
       {
          managementService.sendNotification(notification);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupingHandlerConfiguration.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupingHandlerConfiguration.java b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupingHandlerConfiguration.java
index 5f4ce80..8851259 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupingHandlerConfiguration.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/GroupingHandlerConfiguration.java
@@ -14,6 +14,7 @@ package org.hornetq.core.server.group.impl;
 
 import java.io.Serializable;
 
+import org.hornetq.api.config.HornetQDefaultConfiguration;
 import org.hornetq.api.core.SimpleString;
 
 /**
@@ -25,75 +26,24 @@ public final class GroupingHandlerConfiguration implements Serializable
 {
    public static final long serialVersionUID = -4600283023652477326L;
 
-   public static final int DEFAULT_TIMEOUT = 5000;
-
-   public static final long DEFAULT_GROUP_TIMEOUT = -1;
-
-   public static final long DEFAULT_REAPER_PERIOD = 30000;
-
    public static final String GROUP_TIMEOUT_PROP_NAME = "org.hornetq.GroupingHandlerConfiguration.groupTimeout";
 
    public static final String REAPER_PERIOD_PROP_NAME = "org.hornetq.GroupingHandlerConfiguration.reaperPeriod";
 
-   private final SimpleString name;
-
-   private final TYPE type;
-
-   private final SimpleString address;
-
-   private final long timeout;
+   private SimpleString name = null;
 
-   private long groupTimeout;
+   private TYPE type = null;
 
-   private final long reaperPeriod;
+   private SimpleString address = null;
 
+   private long timeout = HornetQDefaultConfiguration.getDefaultGroupingHandlerTimeout();
 
-   public GroupingHandlerConfiguration(final SimpleString name, final TYPE type, final SimpleString address)
-   {
-      this(name, type, address,
-            GroupingHandlerConfiguration.DEFAULT_TIMEOUT,
-            GroupingHandlerConfiguration.DEFAULT_GROUP_TIMEOUT,
-            GroupingHandlerConfiguration.DEFAULT_REAPER_PERIOD);
-   }
+   private long groupTimeout = HornetQDefaultConfiguration.getDefaultGroupingHandlerGroupTimeout();
 
-   public GroupingHandlerConfiguration(final SimpleString name,
-                                       final TYPE type,
-                                       final SimpleString address,
-                                       final int timeout)
-   {
-      this(name, type, address, timeout,
-            GroupingHandlerConfiguration.DEFAULT_GROUP_TIMEOUT,
-            GroupingHandlerConfiguration.DEFAULT_REAPER_PERIOD);
-   }
+   private long reaperPeriod = HornetQDefaultConfiguration.getDefaultGroupingHandlerReaperPeriod();
 
-   public GroupingHandlerConfiguration(final SimpleString name,
-                                       final TYPE type,
-                                       final SimpleString address,
-                                       final int timeout,
-                                       final long groupTimeout,
-                                       final long reaperPeriod)
+   public GroupingHandlerConfiguration()
    {
-      this.type = type;
-      this.name = name;
-      this.address = address;
-      this.timeout = timeout;
-      if (System.getProperty(GROUP_TIMEOUT_PROP_NAME) != null)
-      {
-         this.groupTimeout = Long.parseLong(System.getProperty(GROUP_TIMEOUT_PROP_NAME));
-      }
-      else
-      {
-         this.groupTimeout = groupTimeout;
-      }
-
-      if (System.getProperty(REAPER_PERIOD_PROP_NAME) != null)
-      {
-         this.reaperPeriod = Long.parseLong(System.getProperty(REAPER_PERIOD_PROP_NAME));
-      }
-      else
-      {
-         this.reaperPeriod = reaperPeriod;
-      }
    }
 
    public SimpleString getName()
@@ -126,6 +76,42 @@ public final class GroupingHandlerConfiguration implements Serializable
       return reaperPeriod;
    }
 
+   public GroupingHandlerConfiguration setName(SimpleString name)
+   {
+      this.name = name;
+      return this;
+   }
+
+   public GroupingHandlerConfiguration setType(TYPE type)
+   {
+      this.type = type;
+      return this;
+   }
+
+   public GroupingHandlerConfiguration setAddress(SimpleString address)
+   {
+      this.address = address;
+      return this;
+   }
+
+   public GroupingHandlerConfiguration setTimeout(long timeout)
+   {
+      this.timeout = timeout;
+      return this;
+   }
+
+   public GroupingHandlerConfiguration setGroupTimeout(long groupTimeout)
+   {
+      this.groupTimeout = groupTimeout;
+      return this;
+   }
+
+   public GroupingHandlerConfiguration setReaperPeriod(long reaperPeriod)
+   {
+      this.reaperPeriod = reaperPeriod;
+      return this;
+   }
+
    public enum TYPE
    {
       LOCAL("LOCAL"), REMOTE("REMOTE");

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/LocalGroupingHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/LocalGroupingHandler.java b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/LocalGroupingHandler.java
index a817f70..7255c9f 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/LocalGroupingHandler.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/LocalGroupingHandler.java
@@ -25,8 +25,8 @@ import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.persistence.OperationContext;
 import org.hornetq.core.persistence.StorageManager;
 import org.hornetq.core.postoffice.BindingType;
@@ -140,7 +140,7 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract
             {
                addRecord = true;
                groupBinding = new GroupBinding(proposal.getGroupId(), proposal.getClusterName());
-               groupBinding.setId(storageManager.generateUniqueID());
+               groupBinding.setId(storageManager.generateID());
                List<GroupBinding> newList = new ArrayList<GroupBinding>();
                List<GroupBinding> oldList = groupMap.putIfAbsent(groupBinding.getClusterName(), newList);
                if (oldList != null)
@@ -193,7 +193,7 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract
       props.putIntProperty(ManagementHelper.HDR_BINDING_TYPE, BindingType.LOCAL_QUEUE_INDEX);
       props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, address);
       props.putIntProperty(ManagementHelper.HDR_DISTANCE, distance);
-      Notification notification = new Notification(null, NotificationType.PROPOSAL_RESPONSE, props);
+      Notification notification = new Notification(null, CoreNotificationType.PROPOSAL_RESPONSE, props);
       managementService.sendNotification(notification);
    }
 
@@ -243,7 +243,7 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract
          groupBindings.remove(groupBinding);
          try
          {
-            long tx = storageManager.generateUniqueID();
+            long tx = storageManager.generateID();
             storageManager.deleteGrouping(tx, groupBinding);
             storageManager.commitBindings(tx);
          }
@@ -265,7 +265,7 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract
          {
             waitingForBindings = true;
 
-            //make a copy of the bindings added so far from the cluster via onNotification().
+            //make a copy of the bindings added so far from the cluster via onNotification()
             List<SimpleString> bindingsAlreadyAdded;
             if (expectedBindings == null)
             {
@@ -307,13 +307,15 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract
 
    public void onNotification(final Notification notification)
    {
-      if (notification.getType() == NotificationType.BINDING_REMOVED)
+      if (!(notification.getType() instanceof CoreNotificationType)) return;
+
+      if (notification.getType() == CoreNotificationType.BINDING_REMOVED)
       {
          SimpleString clusterName = notification.getProperties()
             .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME);
          removeGrouping(clusterName);
       }
-      else if (notification.getType() == NotificationType.BINDING_ADDED)
+      else if (notification.getType() == CoreNotificationType.BINDING_ADDED)
       {
          SimpleString clusterName = notification.getProperties()
             .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME);
@@ -426,7 +428,7 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract
                      {
                         if (txID < 0)
                         {
-                           txID = storageManager.generateUniqueID();
+                           txID = storageManager.generateID();
                         }
                         storageManager.deleteGrouping(txID, val);
                      }
@@ -496,7 +498,7 @@ public final class LocalGroupingHandler extends GroupHandlingAbstract
                   {
                      if (txID < 0)
                      {
-                        txID = storageManager.generateUniqueID();
+                        txID = storageManager.generateID();
                      }
                      storageManager.deleteGrouping(txID, groupBinding);
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/RemoteGroupingHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/RemoteGroupingHandler.java b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/RemoteGroupingHandler.java
index 1187c33..ddbef27 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/RemoteGroupingHandler.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/group/impl/RemoteGroupingHandler.java
@@ -23,8 +23,8 @@ import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
 import org.hornetq.api.core.SimpleString;
+import org.hornetq.api.core.management.CoreNotificationType;
 import org.hornetq.api.core.management.ManagementHelper;
-import org.hornetq.api.core.management.NotificationType;
 import org.hornetq.core.postoffice.BindingType;
 import org.hornetq.core.server.HornetQMessageBundle;
 import org.hornetq.core.server.HornetQServerLogger;
@@ -229,7 +229,7 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract
 
       props.putIntProperty(ManagementHelper.HDR_DISTANCE, 0);
 
-      return new Notification(null, NotificationType.PROPOSAL, props);
+      return new Notification(null, CoreNotificationType.PROPOSAL, props);
    }
 
    public Response getProposal(final SimpleString fullID, boolean touchTime)
@@ -294,7 +294,7 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract
       props.putIntProperty(ManagementHelper.HDR_BINDING_TYPE, BindingType.LOCAL_QUEUE_INDEX);
       props.putSimpleStringProperty(ManagementHelper.HDR_ADDRESS, address);
       props.putIntProperty(ManagementHelper.HDR_DISTANCE, distance);
-      Notification notification = new Notification(null, NotificationType.PROPOSAL, props);
+      Notification notification = new Notification(null, CoreNotificationType.PROPOSAL, props);
       managementService.sendNotification(notification);
       return null;
    }
@@ -311,8 +311,9 @@ public final class RemoteGroupingHandler extends GroupHandlingAbstract
 
    public void onNotification(final Notification notification)
    {
+      if (!(notification.getType() instanceof CoreNotificationType)) return;
       // removing the groupid if the binding has been removed
-      if (notification.getType() == NotificationType.BINDING_REMOVED)
+      if (notification.getType() == CoreNotificationType.BINDING_REMOVED)
       {
          SimpleString clusterName = notification.getProperties()
             .getSimpleStringProperty(ManagementHelper.HDR_CLUSTER_NAME);

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/Activation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/Activation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/Activation.java
new file mode 100644
index 0000000..dc39d7a
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/Activation.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.core.config.Configuration;
+import org.hornetq.core.paging.PagingManager;
+import org.hornetq.core.persistence.StorageManager;
+import org.hornetq.core.postoffice.PostOffice;
+import org.hornetq.core.protocol.core.Channel;
+import org.hornetq.core.protocol.core.ChannelHandler;
+import org.hornetq.core.remoting.server.RemotingService;
+import org.hornetq.core.replication.ReplicationManager;
+import org.hornetq.core.server.HornetQServer;
+import org.hornetq.core.server.NodeManager;
+import org.hornetq.core.server.QueueFactory;
+import org.hornetq.core.server.cluster.ha.HAManager;
+import org.hornetq.core.server.cluster.ha.StandaloneHAManager;
+import org.hornetq.core.server.group.GroupingHandler;
+import org.hornetq.core.server.management.ManagementService;
+import org.hornetq.spi.core.remoting.Acceptor;
+
+/**
+* An activation controls the lifecycle of the server and any components specific to the Activation itself.
+*/
+public abstract class Activation implements Runnable
+{
+   public abstract void close(boolean permanently, boolean restarting) throws Exception;
+
+   /*
+   * freeze the connection but allow the Activation to over ride this and decide if any connections should be left open.
+   * */
+   public void freezeConnections(RemotingService remotingService)
+   {
+      if (remotingService != null)
+      {
+         remotingService.freeze(null, null);
+      }
+   }
+
+   /*
+   * allow the activation t ooverride this if it needs to tidy up after freezing the connection. its a different method as
+   * its called outside of the lock that the previous method is.
+   * */
+   public void postConnectionFreeze()
+   {
+   }
+
+   /*
+   * called before the server is closing the journals so the activation can tidy up stuff
+   * */
+   public void preStorageClose() throws Exception
+   {
+   }
+
+   /*
+   * called by the server to notify the Activation that the server is stopping
+   * */
+   public void sendLiveIsStopping()
+   {
+   }
+
+   /*
+   * called by the ha manager to notify the Activation that HA is now active
+   * */
+   public void haStarted()
+   {
+   }
+
+   /*
+   * allows the Activation to register a channel handler so it can handle any packets that are unique to the Activation
+   * */
+   public ChannelHandler getActivationChannelHandler(Channel channel, Acceptor acceptorUsed)
+   {
+      return null;
+   }
+
+   /*
+   * returns the HA manager used for this Activation
+   * */
+   public HAManager getHAManager()
+   {
+      return new StandaloneHAManager();
+   }
+
+   /*
+   * create the Journal loader needed for this Activation.
+   * */
+   public JournalLoader createJournalLoader(PostOffice postOffice, PagingManager pagingManager, StorageManager storageManager, QueueFactory queueFactory, NodeManager nodeManager, ManagementService managementService, GroupingHandler groupingHandler, Configuration configuration, HornetQServer parentServer) throws HornetQException
+   {
+      return new PostOfficeJournalLoader(postOffice,
+            pagingManager,
+            storageManager,
+            queueFactory,
+            nodeManager,
+            managementService,
+            groupingHandler,
+            configuration);
+   }
+
+   /*
+   * todo, remove this, its only needed for JMSServerManagerImpl, it should be sought elsewhere
+   * */
+   public ReplicationManager getReplicationManager()
+   {
+      return null;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/BackupRecoveryJournalLoader.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/BackupRecoveryJournalLoader.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/BackupRecoveryJournalLoader.java
index 24a4816..021b1dc 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/BackupRecoveryJournalLoader.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/BackupRecoveryJournalLoader.java
@@ -16,7 +16,6 @@ import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.api.core.client.ServerLocator;
-import org.hornetq.core.client.impl.ServerLocatorImpl;
 import org.hornetq.core.client.impl.ServerLocatorInternal;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.journal.Journal;
@@ -24,12 +23,12 @@ import org.hornetq.core.paging.PagingManager;
 import org.hornetq.core.persistence.GroupingInfo;
 import org.hornetq.core.persistence.StorageManager;
 import org.hornetq.core.postoffice.PostOffice;
-import org.hornetq.core.protocol.ServerPacketDecoder;
 import org.hornetq.core.server.HornetQServer;
 import org.hornetq.core.server.HornetQServerLogger;
 import org.hornetq.core.server.NodeManager;
 import org.hornetq.core.server.QueueFactory;
 import org.hornetq.core.server.cluster.ClusterController;
+import org.hornetq.core.server.cluster.HornetQServerSideProtocolManagerFactory;
 import org.hornetq.core.server.group.GroupingHandler;
 import org.hornetq.core.server.management.ManagementService;
 import org.hornetq.core.transaction.ResourceManager;
@@ -88,7 +87,8 @@ public class BackupRecoveryJournalLoader extends PostOfficeJournalLoader
    public void postLoad(Journal messageJournal, ResourceManager resourceManager, Map<SimpleString, List<Pair<byte[], Long>>> duplicateIDMap) throws Exception
    {
       ScaleDownHandler scaleDownHandler = new ScaleDownHandler(pagingManager, postOffice, nodeManager, clusterController);
-      ((ServerLocatorImpl)locator).setPacketDecoder(ServerPacketDecoder.INSTANCE);
+      locator.setProtocolManagerFactory(HornetQServerSideProtocolManagerFactory.getInstance());
+
       try (ClientSessionFactory sessionFactory = locator.createSessionFactory())
       {
          scaleDownHandler.scaleDown(sessionFactory, resourceManager, duplicateIDMap, parentServer.getConfiguration().getManagementAddress(), parentServer.getNodeID());

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ColocatedActivation.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ColocatedActivation.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ColocatedActivation.java
new file mode 100644
index 0000000..92412a3
--- /dev/null
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ColocatedActivation.java
@@ -0,0 +1,331 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.server.impl;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.Pair;
+import org.hornetq.api.core.SimpleString;
+import org.hornetq.core.client.impl.Topology;
+import org.hornetq.core.client.impl.TopologyMemberImpl;
+import org.hornetq.core.protocol.core.Channel;
+import org.hornetq.core.protocol.core.ChannelHandler;
+import org.hornetq.core.protocol.core.Packet;
+import org.hornetq.core.protocol.core.impl.PacketImpl;
+import org.hornetq.core.protocol.core.impl.wireformat.BackupRequestMessage;
+import org.hornetq.core.protocol.core.impl.wireformat.BackupResponseMessage;
+import org.hornetq.core.remoting.server.RemotingService;
+import org.hornetq.core.replication.ReplicationManager;
+import org.hornetq.core.server.cluster.ha.ColocatedHAManager;
+import org.hornetq.core.server.cluster.ha.ColocatedPolicy;
+import org.hornetq.core.server.cluster.ha.HAManager;
+import org.hornetq.core.server.cluster.qourum.QuorumVote;
+import org.hornetq.core.server.cluster.qourum.QuorumVoteHandler;
+import org.hornetq.core.server.cluster.qourum.Vote;
+import org.hornetq.spi.core.remoting.Acceptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+public class ColocatedActivation extends LiveActivation
+{
+   private static final SimpleString REQUEST_BACKUP_QUORUM_VOTE = new SimpleString("RequestBackupQuorumVote");
+
+   private final ColocatedHAManager colocatedHAManager;
+
+   private final ColocatedPolicy colocatedPolicy;
+
+   LiveActivation liveActivation;
+
+   private final HornetQServerImpl server;
+
+   public ColocatedActivation(HornetQServerImpl hornetQServer, ColocatedPolicy colocatedPolicy, LiveActivation liveActivation)
+   {
+      server = hornetQServer;
+      this.colocatedPolicy = colocatedPolicy;
+      this.liveActivation = liveActivation;
+      colocatedHAManager = new ColocatedHAManager(colocatedPolicy, server);
+   }
+
+
+   @Override
+   public void haStarted()
+   {
+      server.getClusterManager().getQuorumManager().registerQuorumHandler(new RequestBackupQuorumVoteHandler());
+      //vote for a backup if required
+      if (colocatedPolicy.isRequestBackup())
+      {
+         server.getClusterManager().getQuorumManager().vote(new RequestBackupQuorumVote());
+      }
+   }
+
+   @Override
+   public void freezeConnections(RemotingService remotingService)
+   {
+      liveActivation.freezeConnections(remotingService);
+   }
+
+   @Override
+   public void postConnectionFreeze()
+   {
+      liveActivation.postConnectionFreeze();
+   }
+
+   @Override
+   public void preStorageClose() throws Exception
+   {
+      liveActivation.preStorageClose();
+   }
+
+   @Override
+   public void sendLiveIsStopping()
+   {
+      liveActivation.sendLiveIsStopping();
+   }
+
+   @Override
+   public ReplicationManager getReplicationManager()
+   {
+      return liveActivation.getReplicationManager();
+   }
+
+   @Override
+   public HAManager getHAManager()
+   {
+      return colocatedHAManager;
+   }
+
+   @Override
+   public void run()
+   {
+      liveActivation.run();
+   }
+
+   @Override
+   public void close(boolean permanently, boolean restarting) throws Exception
+   {
+      liveActivation.close(permanently, restarting);
+   }
+
+   @Override
+   public ChannelHandler getActivationChannelHandler(final Channel channel, final Acceptor acceptorUsed)
+   {
+      final ChannelHandler activationChannelHandler = liveActivation.getActivationChannelHandler(channel, acceptorUsed);
+      return new ChannelHandler()
+      {
+         @Override
+         public void handlePacket(Packet packet)
+         {
+            if (packet.getType() == PacketImpl.BACKUP_REQUEST)
+            {
+               BackupRequestMessage backupRequestMessage = (BackupRequestMessage) packet;
+               boolean started = false;
+               try
+               {
+                  started = colocatedHAManager.activateBackup(backupRequestMessage.getBackupSize(),
+                        backupRequestMessage.getJournalDirectory(),
+                        backupRequestMessage.getBindingsDirectory(),
+                        backupRequestMessage.getLargeMessagesDirectory(),
+                        backupRequestMessage.getPagingDirectory(),
+                        backupRequestMessage.getNodeID());
+               }
+               catch (Exception e)
+               {
+                  e.printStackTrace();
+               }
+               channel.send(new BackupResponseMessage(started));
+            }
+            else if (activationChannelHandler != null)
+            {
+               activationChannelHandler.handlePacket(packet);
+            }
+         }
+      };
+   }
+
+   /**
+    * A vote handler for incoming backup request votes
+    */
+   private final class RequestBackupQuorumVoteHandler implements QuorumVoteHandler
+   {
+      @Override
+      public Vote vote(Vote vote)
+      {
+         int size = colocatedHAManager.getBackupServers().size();
+         return new RequestBackupVote(size, server.getNodeID().toString(), size < colocatedPolicy.getMaxBackups());
+      }
+
+      @Override
+      public SimpleString getQuorumName()
+      {
+         return REQUEST_BACKUP_QUORUM_VOTE;
+      }
+
+      @Override
+      public Vote decode(HornetQBuffer voteBuffer)
+      {
+         RequestBackupVote requestBackupVote = new RequestBackupVote();
+         requestBackupVote.decode(voteBuffer);
+         return requestBackupVote;
+      }
+   }
+   /**
+    * a quorum vote for backup requests
+    */
+   private final class RequestBackupQuorumVote extends QuorumVote<RequestBackupVote, Pair<String, Integer>>
+   {
+      //the available nodes that we can request
+      private final List<Pair<String, Integer>> nodes = new ArrayList<>();
+
+      public RequestBackupQuorumVote()
+      {
+         super(REQUEST_BACKUP_QUORUM_VOTE);
+      }
+
+      @Override
+      public Vote connected()
+      {
+         return new RequestBackupVote();
+      }
+
+      @Override
+      public Vote notConnected()
+      {
+         return new RequestBackupVote();
+      }
+
+      @Override
+      public void vote(RequestBackupVote vote)
+      {
+         //if the returned vote is available add it to the nodes we can request
+         if (vote.backupAvailable)
+         {
+            nodes.add(vote.getVote());
+         }
+      }
+
+      @Override
+      public Pair<String, Integer> getDecision()
+      {
+         //sort the nodes by how many backups they have and choose the first
+         Collections.sort(nodes, new Comparator<Pair<String, Integer>>()
+         {
+            @Override
+            public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2)
+            {
+               return o1.getB().compareTo(o2.getB());
+            }
+         });
+         return nodes.get(0);
+      }
+
+      @Override
+      public void allVotesCast(Topology voteTopology)
+      {
+         //if we have any nodes that we can request then send a request
+         if (nodes.size() > 0)
+         {
+            Pair<String, Integer> decision = getDecision();
+            TopologyMemberImpl member = voteTopology.getMember(decision.getA());
+            try
+            {
+               boolean backupStarted = colocatedHAManager.requestBackup(member.getConnector(), decision.getB().intValue(), !colocatedPolicy.isSharedStore());
+               if (!backupStarted)
+               {
+                  nodes.clear();
+                  server.getScheduledPool().schedule(new Runnable()
+                  {
+                     @Override
+                     public void run()
+                     {
+                        server.getClusterManager().getQuorumManager().vote(new RequestBackupQuorumVote());
+                     }
+                  }, colocatedPolicy.getBackupRequestRetryInterval(), TimeUnit.MILLISECONDS);
+               }
+            }
+            catch (Exception e)
+            {
+               e.printStackTrace();
+               //todo
+            }
+         }
+         else
+         {
+            nodes.clear();
+            server.getScheduledPool().schedule(new Runnable()
+            {
+               @Override
+               public void run()
+               {
+                  server.getClusterManager().getQuorumManager().vote(RequestBackupQuorumVote.this);
+               }
+            }, colocatedPolicy.getBackupRequestRetryInterval(), TimeUnit.MILLISECONDS);
+         }
+      }
+
+      @Override
+      public SimpleString getName()
+      {
+         return REQUEST_BACKUP_QUORUM_VOTE;
+      }
+   }
+
+   class RequestBackupVote extends Vote<Pair<String, Integer>>
+   {
+      private int backupsSize;
+      private String nodeID;
+      private boolean backupAvailable;
+
+      public RequestBackupVote()
+      {
+         backupsSize = -1;
+      }
+
+      public RequestBackupVote(int backupsSize, String nodeID, boolean backupAvailable)
+      {
+         this.backupsSize = backupsSize;
+         this.nodeID = nodeID;
+         this.backupAvailable = backupAvailable;
+      }
+
+      @Override
+      public void encode(HornetQBuffer buff)
+      {
+         buff.writeInt(backupsSize);
+         buff.writeNullableString(nodeID);
+         buff.writeBoolean(backupAvailable);
+      }
+
+      @Override
+      public void decode(HornetQBuffer buff)
+      {
+         backupsSize = buff.readInt();
+         nodeID = buff.readNullableString();
+         backupAvailable = buff.readBoolean();
+      }
+
+      @Override
+      public boolean isRequestServerVote()
+      {
+         return true;
+      }
+
+      @Override
+      public Pair<String, Integer> getVote()
+      {
+         return new Pair<>(nodeID, backupsSize);
+      }
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/ConnectorsService.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ConnectorsService.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ConnectorsService.java
index 094efc9..2cc6f2d 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/ConnectorsService.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/ConnectorsService.java
@@ -12,11 +12,13 @@
  */
 package org.hornetq.core.server.impl;
 
+import java.util.Collection;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.ScheduledExecutorService;
 
+import org.hornetq.api.core.Pair;
 import org.hornetq.core.config.Configuration;
 import org.hornetq.core.config.ConnectorServiceConfiguration;
 import org.hornetq.core.persistence.StorageManager;
@@ -51,48 +53,36 @@ public final class ConnectorsService implements HornetQComponent
 
    private final Set<ConnectorService> connectors = new HashSet<ConnectorService>();
 
+   private final ServiceRegistry serviceRegistry;
+
    public ConnectorsService(final Configuration configuration,
                             final StorageManager storageManager,
                             final ScheduledExecutorService scheduledPool,
-                            final PostOffice postOffice)
+                            final PostOffice postOffice,
+                            final ServiceRegistry serviceRegistry)
    {
       this.configuration = configuration;
       this.storageManager = storageManager;
       this.scheduledPool = scheduledPool;
       this.postOffice = postOffice;
+      this.serviceRegistry = serviceRegistry;
    }
 
    public void start() throws Exception
    {
       List<ConnectorServiceConfiguration> configurationList = configuration.getConnectorServiceConfigurations();
 
-      for (ConnectorServiceConfiguration info : configurationList)
-      {
-         ConnectorServiceFactory factory = (ConnectorServiceFactory)ClassloadingUtil.newInstanceFromClassLoader(info.getFactoryClassName());
-
-         if (info.getParams() != null)
-         {
-            Set<String> invalid = ConfigurationHelper.checkKeys(factory.getAllowableProperties(), info.getParams()
-               .keySet());
-
-            if (!invalid.isEmpty())
-            {
-               HornetQServerLogger.LOGGER.connectorKeysInvalid(ConfigurationHelper.stringSetToCommaListString(invalid));
-
-               continue;
-            }
-         }
-         Set<String> invalid = ConfigurationHelper.checkKeysExist(factory.getRequiredProperties(), info.getParams()
-            .keySet());
+      Collection<Pair<ConnectorServiceFactory, ConnectorServiceConfiguration>> connectorServiceFactories = serviceRegistry.getConnectorServices();
 
-         if (!invalid.isEmpty())
-         {
-            HornetQServerLogger.LOGGER.connectorKeysMissing(ConfigurationHelper.stringSetToCommaListString(invalid));
+      for (Pair<ConnectorServiceFactory, ConnectorServiceConfiguration> pair : connectorServiceFactories)
+      {
+         createService(pair.getB(), pair.getA());
+      }
 
-            continue;
-         }
-         ConnectorService connectorService = factory.createConnectorService(info.getConnectorName(), info.getParams(), storageManager, postOffice, scheduledPool);
-         connectors.add(connectorService);
+      for (ConnectorServiceConfiguration info : configurationList)
+      {
+         ConnectorServiceFactory factory = (ConnectorServiceFactory) ClassloadingUtil.newInstanceFromClassLoader(info.getFactoryClassName());
+         createService(info, factory);
       }
 
       for (ConnectorService connector : connectors)
@@ -109,6 +99,28 @@ public final class ConnectorsService implements HornetQComponent
       isStarted = true;
    }
 
+   public void createService(ConnectorServiceConfiguration info, ConnectorServiceFactory factory)
+   {
+      if (info.getParams() != null)
+      {
+         Set<String> invalid = ConfigurationHelper.checkKeys(factory.getAllowableProperties(), info.getParams().keySet());
+         if (!invalid.isEmpty())
+         {
+            HornetQServerLogger.LOGGER.connectorKeysInvalid(ConfigurationHelper.stringSetToCommaListString(invalid));
+            return;
+         }
+      }
+
+      Set<String> invalid = ConfigurationHelper.checkKeysExist(factory.getRequiredProperties(), info.getParams().keySet());
+      if (!invalid.isEmpty())
+      {
+         HornetQServerLogger.LOGGER.connectorKeysMissing(ConfigurationHelper.stringSetToCommaListString(invalid));
+         return;
+      }
+      ConnectorService connectorService = factory.createConnectorService(info.getConnectorName(), info.getParams(), storageManager, postOffice, scheduledPool);
+      connectors.add(connectorService);
+   }
+
    public void stop() throws Exception
    {
       if (!isStarted)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-server/src/main/java/org/hornetq/core/server/impl/DivertImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-server/src/main/java/org/hornetq/core/server/impl/DivertImpl.java b/hornetq-server/src/main/java/org/hornetq/core/server/impl/DivertImpl.java
index 627f1c1..4e63d14 100644
--- a/hornetq-server/src/main/java/org/hornetq/core/server/impl/DivertImpl.java
+++ b/hornetq-server/src/main/java/org/hornetq/core/server/impl/DivertImpl.java
@@ -85,7 +85,7 @@ public class DivertImpl implements Divert
          HornetQServerLogger.LOGGER.trace("Diverting message " + message + " into " + this);
       }
 
-      long id = storageManager.generateUniqueID();
+      long id = storageManager.generateID();
 
       ServerMessage copy = null;
 
@@ -100,6 +100,8 @@ public class DivertImpl implements Divert
 
          copy.setAddress(forwardAddress);
 
+         copy.setExpiration(message.getExpiration());
+
          if (transformer != null)
          {
             copy = transformer.transform(copy);


[37/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonConsumer.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonConsumer.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonConsumer.java
deleted file mode 100644
index 4bf52a7..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonConsumer.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton;
-
-import java.util.Map;
-
-import org.apache.qpid.proton.amqp.DescribedType;
-import org.apache.qpid.proton.amqp.Symbol;
-import org.apache.qpid.proton.amqp.messaging.Accepted;
-import org.apache.qpid.proton.amqp.messaging.Modified;
-import org.apache.qpid.proton.amqp.messaging.Rejected;
-import org.apache.qpid.proton.amqp.messaging.Released;
-import org.apache.qpid.proton.amqp.transport.DeliveryState;
-import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
-import org.apache.qpid.proton.engine.Delivery;
-import org.apache.qpid.proton.engine.Sender;
-import org.apache.qpid.proton.jms.EncodedMessage;
-import org.hornetq.api.core.SimpleString;
-import org.hornetq.core.client.impl.ClientConsumerImpl;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPException;
-import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.QueueQueryResult;
-import org.hornetq.core.server.ServerMessage;
-
-/**
- * A this is a wrapper around a HornetQ ServerConsumer for handling outgoing messages and incoming acks via a Proton Sender
- *
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- */
-public class ProtonConsumer implements ProtonDeliveryHandler
-{
-   private static final Symbol SELECTOR = Symbol.getSymbol("jms-selector");
-   private static final Symbol COPY = Symbol.valueOf("copy");
-   private final ProtonSession protonSession;
-   private final HornetQServer server;
-   private final Sender sender;
-   private final ProtonRemotingConnection connection;
-   private final ProtonProtocolManager protonProtocolManager;
-   private long consumerID;
-   private boolean closed = false;
-   private long forcedDeliveryCount = 0;
-   private boolean forcingDelivery = false;
-   private boolean receivedForcedDelivery = true;
-
-   public ProtonConsumer(ProtonRemotingConnection connection, Sender sender, ProtonSession protonSession, HornetQServer server,
-                         ProtonProtocolManager protonProtocolManager)
-   {
-      this.connection = connection;
-      this.sender = sender;
-      this.protonSession = protonSession;
-      this.server = server;
-      this.protonProtocolManager = protonProtocolManager;
-   }
-
-   /*
-   * start the session
-   * */
-   public void start() throws HornetQAMQPException
-   {
-      protonSession.getServerSession().start();
-
-      //todo add flow control
-      try
-      {
-         protonSession.getServerSession().receiveConsumerCredits(consumerID, -1);
-      }
-      catch (Exception e)
-      {
-         throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorStartingConsumer(e.getMessage());
-      }
-   }
-
-   /*
-   * create the actual underlying HornetQ Server Consumer
-   * */
-   public void init() throws HornetQAMQPException
-   {
-      org.apache.qpid.proton.amqp.messaging.Source source = (org.apache.qpid.proton.amqp.messaging.Source) sender.getRemoteSource();
-
-      SimpleString queue;
-
-      consumerID = server.getStorageManager().generateUniqueID();
-
-      SimpleString selector = null;
-      Map filter = source.getFilter();
-      if (filter != null)
-      {
-         DescribedType value = (DescribedType) filter.get(SELECTOR);
-         if (value != null)
-         {
-            selector = new SimpleString(value.getDescribed().toString());
-         }
-      }
-
-      if (source.getDynamic())
-      {
-         //if dynamic we have to create the node (queue) and set the address on the target, the node is temporary and
-         // will be deleted on closing of the session
-         queue = new SimpleString(java.util.UUID.randomUUID().toString());
-         try
-         {
-            protonSession.getServerSession().createQueue(queue, queue, null, true, false);
-         }
-         catch (Exception e)
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCreatingTemporaryQueue(e.getMessage());
-         }
-         source.setAddress(queue.toString());
-      }
-      else
-      {
-         //if not dynamic then we use the targets address as the address to forward the messages to, however there has to
-         //be a queue bound to it so we nee to check this.
-         String address = source.getAddress();
-         if (address == null)
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.sourceAddressNotSet();
-         }
-
-         queue = new SimpleString(source.getAddress());
-         QueueQueryResult queryResult;
-         try
-         {
-            queryResult = protonSession.getServerSession().executeQueueQuery(new SimpleString(address));
-         }
-         catch (Exception e)
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorFindingTemporaryQueue(e.getMessage());
-         }
-         if (!queryResult.isExists())
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.sourceAddressDoesntExist();
-         }
-      }
-      boolean browseOnly = source.getDistributionMode() != null && source.getDistributionMode().equals(COPY);
-      try
-      {
-         protonSession.getServerSession().createConsumer(consumerID, queue, selector, browseOnly);
-      }
-      catch (Exception e)
-      {
-         throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCreatingHornetQConsumer(e.getMessage());
-      }
-   }
-
-   /*
-   * close the session
-   * */
-   public synchronized void close() throws HornetQAMQPException
-   {
-      closed = true;
-      protonSession.removeConsumer(consumerID);
-   }
-
-   public long getConsumerID()
-   {
-      return consumerID;
-   }
-
-   /*
-   * handle an out going message from HornetQ, send via the Proton Sender
-   * */
-   public synchronized int handleDelivery(ServerMessage message, int deliveryCount)
-   {
-      if (closed)
-      {
-         return 0;
-      }
-      if (message.containsProperty(ClientConsumerImpl.FORCED_DELIVERY_MESSAGE))
-      {
-         if (forcingDelivery)
-         {
-            sender.drained();
-         }
-         else
-         {
-            receivedForcedDelivery = true;
-            forcingDelivery = false;
-         }
-         return 0;
-      }
-      //if we get here then a forced delivery has pushed some messages thru and we continue
-      if (forcingDelivery)
-      {
-         forcingDelivery = false;
-      }
-      //presettle means we can ack the message on the proton side before we send it, i.e. for browsers
-      boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;
-      //we only need a tag if we are going to ack later
-      byte[] tag = preSettle ? new byte[0] : protonSession.getTag();
-      //encode the message
-      EncodedMessage encodedMessage = ProtonUtils.OUTBOUND.transform(message, deliveryCount);
-      //now handle the delivery
-      protonProtocolManager.handleDelivery(sender, tag, encodedMessage, message, connection, preSettle);
-
-      return encodedMessage.getLength();
-   }
-
-   @Override
-   /*
-   * handle an incoming Ack from Proton, basically pass to HornetQ to handle
-   * */
-   public void onMessage(Delivery delivery) throws HornetQAMQPException
-   {
-      ServerMessage message = (ServerMessage) delivery.getContext();
-
-      boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;
-
-
-      DeliveryState remoteState = delivery.getRemoteState();
-
-      if (remoteState != null)
-      {
-         if (remoteState instanceof Accepted)
-         {
-            //we have to individual ack as we can't guarantee we will get the delivery updates (including acks) in order
-            // from proton, a perf hit but a must
-            try
-            {
-               protonSession.getServerSession().individualAcknowledge(consumerID, message.getMessageID());
-            }
-            catch (Exception e)
-            {
-               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorAcknowledgingMessage(message.getMessageID(), e.getMessage());
-            }
-         }
-         else if (remoteState instanceof Released)
-         {
-            try
-            {
-               protonSession.getServerSession().individualCancel(consumerID, message.getMessageID(), false);
-            }
-            catch (Exception e)
-            {
-               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCancellingMessage(message.getMessageID(), e.getMessage());
-            }
-         }
-         else if (remoteState instanceof Rejected || remoteState instanceof Modified)
-         {
-            try
-            {
-               protonSession.getServerSession().individualCancel(consumerID, message.getMessageID(), true);
-            }
-            catch (Exception e)
-            {
-               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCancellingMessage(message.getMessageID(), e.getMessage());
-            }
-         }
-
-         synchronized (connection.getDeliveryLock())
-         {
-            delivery.settle();
-         }
-         //todo add tag caching
-         if (!preSettle)
-         {
-            protonSession.replaceTag(delivery.getTag());
-         }
-         sender.offer(1);
-      }
-      else
-      {
-         //todo not sure if we need to do anything here
-      }
-   }
-
-   /*
-   * check the state of the consumer, i.e. are there any more messages. only really needed for browsers?
-   * */
-   public synchronized void checkState()
-   {
-      if (!forcingDelivery && receivedForcedDelivery)
-      {
-         try
-         {
-            forcingDelivery = true;
-            receivedForcedDelivery = false;
-            protonSession.getServerSession().forceConsumerDelivery(consumerID, forcedDeliveryCount++);
-         }
-         catch (Exception e)
-         {
-            e.printStackTrace();
-         }
-      }
-   }
-
-   public Sender getSender()
-   {
-      return sender;
-   }
-
-   private String formatTag(byte[] tag)
-   {
-      StringBuffer sb = new StringBuffer();
-      for (byte b : tag)
-      {
-         sb.append(b).append(":");
-      }
-      return sb.toString();
-   }
-
-   int x = 5;
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonDeliveryHandler.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonDeliveryHandler.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonDeliveryHandler.java
deleted file mode 100644
index 9b7a605..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonDeliveryHandler.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton;
-
-import org.apache.qpid.proton.engine.Delivery;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPException;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         <p/>
- *         An interface to handle deliveries, either messages, acks or transaction calls
- */
-public interface ProtonDeliveryHandler
-{
-   void onMessage(Delivery delivery) throws HornetQAMQPException;
-
-   void checkState();
-
-   void close() throws HornetQAMQPException;
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProducer.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProducer.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProducer.java
deleted file mode 100644
index 71f3a83..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProducer.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton;
-
-import org.apache.qpid.proton.amqp.Symbol;
-import org.apache.qpid.proton.amqp.messaging.Rejected;
-import org.apache.qpid.proton.amqp.messaging.Target;
-import org.apache.qpid.proton.amqp.transport.ErrorCondition;
-import org.apache.qpid.proton.engine.Delivery;
-import org.apache.qpid.proton.engine.Receiver;
-import org.hornetq.api.core.HornetQBuffer;
-import org.hornetq.api.core.SimpleString;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPException;
-import org.hornetq.core.server.QueueQueryResult;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         <p/>
- *         handles incoming messages via a Proton Receiver and forwards them to HornetQ
- */
-public class ProtonProducer implements ProtonDeliveryHandler
-{
-   private final ProtonRemotingConnection connection;
-
-   private final ProtonSession protonSession;
-
-   private final ProtonProtocolManager protonProtocolManager;
-
-   private final Receiver receiver;
-
-   private final String address;
-
-   private HornetQBuffer buffer;
-
-   public ProtonProducer(ProtonRemotingConnection connection, ProtonSession protonSession, ProtonProtocolManager protonProtocolManager, Receiver receiver)
-   {
-      this.connection = connection;
-      this.protonSession = protonSession;
-      this.protonProtocolManager = protonProtocolManager;
-      this.receiver = receiver;
-      this.address = ((Target) receiver.getRemoteTarget()).getAddress();
-      buffer = connection.createBuffer(1024);
-   }
-
-   /*
-   * called when Proton receives a message to be delivered via a Delivery.
-   *
-   * This may be called more than once per deliver so we have to cache the buffer until we have received it all.
-   *
-   * */
-   public void onMessage(Delivery delivery) throws HornetQAMQPException
-   {
-      Receiver receiver;
-      try
-      {
-         receiver = ((Receiver) delivery.getLink());
-
-         if (!delivery.isReadable())
-         {
-            return;
-         }
-
-         protonProtocolManager.handleMessage(receiver, buffer, delivery, connection, protonSession, address);
-
-      }
-      catch (Exception e)
-      {
-         e.printStackTrace();
-         Rejected rejected = new Rejected();
-         ErrorCondition condition = new ErrorCondition();
-         condition.setCondition(Symbol.valueOf("failed"));
-         condition.setDescription(e.getMessage());
-         rejected.setError(condition);
-         delivery.disposition(rejected);
-      }
-   }
-
-   @Override
-   public void checkState()
-   {
-      //no op
-   }
-
-   @Override
-   public void close() throws HornetQAMQPException
-   {
-      protonSession.removeProducer(receiver);
-   }
-
-   public void init() throws HornetQAMQPException
-   {
-      org.apache.qpid.proton.amqp.messaging.Target target = (org.apache.qpid.proton.amqp.messaging.Target) receiver.getRemoteTarget();
-      if (target.getDynamic())
-      {
-         //if dynamic we have to create the node (queue) and set the address on the target, the node is temporary and
-         // will be deleted on closing of the session
-         SimpleString queue = new SimpleString(java.util.UUID.randomUUID().toString());
-         try
-         {
-            protonSession.getServerSession().createQueue(queue, queue, null, true, false);
-         }
-         catch (Exception e)
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCreatingTemporaryQueue(e.getMessage());
-         }
-         target.setAddress(queue.toString());
-      }
-      else
-      {
-         //if not dynamic then we use the targets address as the address to forward the messages to, however there has to
-         //be a queue bound to it so we nee to check this.
-         String address = target.getAddress();
-         if (address == null)
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.targetAddressNotSet();
-         }
-         try
-         {
-            QueueQueryResult queryResult = protonSession.getServerSession().executeQueueQuery(new SimpleString(address));
-            if (!queryResult.isExists())
-            {
-               throw HornetQAMQPProtocolMessageBundle.BUNDLE.addressDoesntExist();
-            }
-         }
-         catch (Exception e)
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorFindingTemporaryQueue(e.getMessage());
-         }
-      }
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProtocolManager.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProtocolManager.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProtocolManager.java
index ae06aa1..8086925 100644
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProtocolManager.java
+++ b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonProtocolManager.java
@@ -13,46 +13,25 @@
 
 package org.hornetq.core.protocol.proton;
 
-import java.nio.ByteBuffer;
-import java.nio.charset.StandardCharsets;
-import java.util.EnumSet;
+import java.util.concurrent.Executor;
 
 import io.netty.channel.ChannelPipeline;
-import org.apache.qpid.proton.amqp.Binary;
-import org.apache.qpid.proton.amqp.messaging.AmqpValue;
-import org.apache.qpid.proton.amqp.transaction.Coordinator;
-import org.apache.qpid.proton.amqp.transaction.Declare;
-import org.apache.qpid.proton.amqp.transaction.Declared;
-import org.apache.qpid.proton.amqp.transaction.Discharge;
-import org.apache.qpid.proton.amqp.transport.AmqpError;
-import org.apache.qpid.proton.amqp.transport.ErrorCondition;
-import org.apache.qpid.proton.engine.Delivery;
-import org.apache.qpid.proton.engine.EndpointState;
-import org.apache.qpid.proton.engine.Link;
-import org.apache.qpid.proton.engine.Receiver;
-import org.apache.qpid.proton.engine.Sender;
-import org.apache.qpid.proton.engine.impl.LinkImpl;
-import org.apache.qpid.proton.engine.impl.TransportImpl;
-import org.apache.qpid.proton.jms.EncodedMessage;
-import org.apache.qpid.proton.message.impl.MessageImpl;
 import org.hornetq.api.core.HornetQBuffer;
-import org.hornetq.api.core.SimpleString;
-import org.hornetq.core.journal.IOAsyncTask;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPException;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPIllegalStateException;
+import org.hornetq.api.core.client.HornetQClient;
+import org.hornetq.core.protocol.proton.converter.ProtonMessageConverter;
+import org.hornetq.core.protocol.proton.plug.HornetQProtonConnectionCallback;
 import org.hornetq.core.remoting.impl.netty.NettyServerConnection;
 import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.ServerMessage;
-import org.hornetq.core.server.impl.ServerMessageImpl;
 import org.hornetq.core.server.management.Notification;
 import org.hornetq.core.server.management.NotificationListener;
-import org.hornetq.core.transaction.Transaction;
 import org.hornetq.spi.core.protocol.ConnectionEntry;
+import org.hornetq.spi.core.protocol.MessageConverter;
 import org.hornetq.spi.core.protocol.ProtocolManager;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.spi.core.remoting.Acceptor;
 import org.hornetq.spi.core.remoting.Connection;
-import org.hornetq.utils.UUIDGenerator;
+import org.proton.plug.AMQPServerConnectionContext;
+import org.proton.plug.context.server.ProtonServerConnectionContextFactory;
 
 /**
  * A proton protocol manager, basically reads the Proton Input and maps proton resources to HornetQ resources
@@ -61,272 +40,83 @@ import org.hornetq.utils.UUIDGenerator;
  */
 public class ProtonProtocolManager implements ProtocolManager, NotificationListener
 {
-   public static final EnumSet<EndpointState> UNINITIALIZED = EnumSet.of(EndpointState.UNINITIALIZED);
-
-   public static final EnumSet<EndpointState> INITIALIZED = EnumSet.complementOf(UNINITIALIZED);
-
-   public static final EnumSet<EndpointState> ACTIVE = EnumSet.of(EndpointState.ACTIVE);
-
-   public static final EnumSet<EndpointState> CLOSED = EnumSet.of(EndpointState.CLOSED);
-
-   public static final EnumSet<EndpointState> ANY_ENDPOINT_STATE = EnumSet.of(EndpointState.CLOSED, EndpointState.ACTIVE, EndpointState.UNINITIALIZED);
-
    private final HornetQServer server;
 
+   private MessageConverter protonConverter;
+
    public ProtonProtocolManager(HornetQServer server)
    {
       this.server = server;
+      this.protonConverter = new ProtonMessageConverter(server.getStorageManager());
    }
 
-   @Override
-   public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection connection)
+   public HornetQServer getServer()
    {
-      ProtonRemotingConnection conn = new ProtonRemotingConnection(acceptorUsed, connection, this);
-      //todo do we have a ttl?
-      return new ConnectionEntry(conn, null, System.currentTimeMillis(), 1 * 60 * 1000);
+      return server;
    }
 
-   @Override
-   public void removeHandler(String name)
-   {
-   }
 
    @Override
-   public void handleBuffer(RemotingConnection connection, HornetQBuffer buffer)
+   public MessageConverter getConverter()
    {
-      ProtonRemotingConnection protonRemotingConnection = (ProtonRemotingConnection) connection;
-      protonRemotingConnection.setDataReceived();
-      byte[] frame = new byte[buffer.readableBytes()];
-      buffer.readBytes(frame);
-
-      protonRemotingConnection.handleFrame(frame);
+      return protonConverter;
    }
 
    @Override
-   public void addChannelHandlers(ChannelPipeline pipeliner)
+   public void onNotification(Notification notification)
    {
-      //we don't need any we do our own decoding
-   }
 
-   @Override
-   public boolean isProtocol(byte[] array)
-   {
-      String startFrame = new String(array, StandardCharsets.US_ASCII);
-      return startFrame.startsWith("AMQP");
    }
 
    @Override
-   public void handshake(NettyServerConnection connection, HornetQBuffer buffer)
+   public ConnectionEntry createConnectionEntry(Acceptor acceptorUsed, Connection remotingConnection)
    {
-      //todo move handshake to here
-   }
+      HornetQProtonConnectionCallback connectionCallback = new HornetQProtonConnectionCallback(this, remotingConnection);
 
-   @Override
-   public void onNotification(Notification notification)
-   {
-      //noop
-   }
+      AMQPServerConnectionContext amqpConnection = ProtonServerConnectionContextFactory.getFactory().createConnection(connectionCallback);
 
-   public ServerMessageImpl createServerMessage()
-   {
-      return new ServerMessageImpl(server.getStorageManager().generateUniqueID(), 512);
-   }
+      Executor executor = server.getExecutorFactory().getExecutor();
 
-   public void handleMessage(final Receiver receiver, HornetQBuffer buffer, final Delivery delivery,
-                             final ProtonRemotingConnection connection, ProtonSession protonSession,
-                             String address) throws Exception
-   {
-      synchronized (connection.getDeliveryLock())
-      {
-         int count;
-         byte[] data = new byte[1024];
-         //todo an optimisation here would be to only use the buffer if we need more that one recv
-         while ((count = receiver.recv(data, 0, data.length)) > 0)
-         {
-            buffer.writeBytes(data, 0, count);
-         }
+      HornetQProtonRemotingConnection delegate = new HornetQProtonRemotingConnection(this, amqpConnection, remotingConnection, executor);
+
+      connectionCallback.setProtonConnectionDelegate(delegate);
 
-         // we keep reading until we get end of messages, i.e. -1
-         if (count == 0)
-         {
-            return;
-         }
-         receiver.advance();
-         byte[] bytes = new byte[buffer.readableBytes()];
-         buffer.readBytes(bytes);
-         buffer.clear();
-         EncodedMessage encodedMessage = new EncodedMessage(delivery.getMessageFormat(), bytes, 0, bytes.length);
-         ServerMessage message = ProtonUtils.INBOUND.transform(connection, encodedMessage);
-         //use the address on the receiver if not null, if null let's hope it was set correctly on the message
-         if (address != null)
-         {
-            message.setAddress(new SimpleString(address));
-         }
-         //todo decide on whether to deliver direct
-         protonSession.getServerSession().send(message, true);
-         server.getStorageManager().afterCompleteOperations(new IOAsyncTask()
-         {
-            @Override
-            public void done()
-            {
-               synchronized (connection.getDeliveryLock())
-               {
-                  receiver.flow(1);
-                  delivery.settle();
-               }
-            }
+      ConnectionEntry entry = new ConnectionEntry(delegate, executor,
+                                                  System.currentTimeMillis(), HornetQClient.DEFAULT_CONNECTION_TTL);
 
-            @Override
-            public void onError(int errorCode, String errorMessage)
-            {
-               receiver.setCondition(new ErrorCondition(AmqpError.ILLEGAL_STATE, errorCode + ":" + errorMessage));
-            }
-         });
-      }
+      return entry;
    }
 
-   public void handleDelivery(final Sender sender, byte[] tag, EncodedMessage encodedMessage, ServerMessage message, ProtonRemotingConnection connection, final boolean preSettle)
+   @Override
+   public void removeHandler(String name)
    {
-      synchronized (connection.getDeliveryLock())
-      {
-         final Delivery delivery;
-         delivery = sender.delivery(tag, 0, tag.length);
-         delivery.setContext(message);
-         sender.send(encodedMessage.getArray(), 0, encodedMessage.getLength());
-         server.getStorageManager().afterCompleteOperations(new IOAsyncTask()
-         {
-            @Override
-            public void done()
-            {
-               if (preSettle)
-               {
-                  delivery.settle();
-                  ((LinkImpl) sender).addCredit(1);
-               }
-               else
-               {
-                  sender.advance();
-               }
-            }
 
-            @Override
-            public void onError(int errorCode, String errorMessage)
-            {
-               sender.setCondition(new ErrorCondition(AmqpError.ILLEGAL_STATE, errorCode + ":" + errorMessage));
-            }
-         });
-      }
-      connection.write();
    }
 
-   void handleNewLink(Link link, ProtonSession protonSession) throws HornetQAMQPException
+   @Override
+   public void handleBuffer(RemotingConnection connection, HornetQBuffer buffer)
    {
-      link.setSource(link.getRemoteSource());
-      link.setTarget(link.getRemoteTarget());
-      if (link instanceof Receiver)
-      {
-         Receiver receiver = (Receiver) link;
-         if (link.getRemoteTarget() instanceof Coordinator)
-         {
-            protonSession.initialise(true);
-            Coordinator coordinator = (Coordinator) link.getRemoteTarget();
-            protonSession.addTransactionHandler(coordinator, receiver);
-         }
-         else
-         {
-            protonSession.initialise(false);
-            protonSession.addProducer(receiver);
-            //todo do this using the server session flow control
-            receiver.flow(100);
-         }
-      }
-      else
-      {
-         protonSession.initialise(false);
-         Sender sender = (Sender) link;
-         protonSession.addConsumer(sender);
-         sender.offer(1);
-      }
-   }
+      HornetQProtonRemotingConnection protonConnection = (HornetQProtonRemotingConnection)connection;
 
-   public ProtonSession createSession(ProtonRemotingConnection protonConnection, TransportImpl protonTransport) throws HornetQAMQPException
-   {
-      String name = UUIDGenerator.getInstance().generateStringUUID();
-      return new ProtonSession(name, protonConnection, this, server.getStorageManager()
-         .newContext(server.getExecutorFactory().getExecutor()), server, protonTransport);
+      protonConnection.bufferReceived(protonConnection.getID(), buffer);
    }
 
-   void handleActiveLink(Link link) throws HornetQAMQPException
+   @Override
+   public void addChannelHandlers(ChannelPipeline pipeline)
    {
-      link.setSource(link.getRemoteSource());
-      link.setTarget(link.getRemoteTarget());
-      ProtonDeliveryHandler handler = (ProtonDeliveryHandler) link.getContext();
-      handler.checkState();
+
    }
 
-   public void handleTransaction(Receiver receiver, HornetQBuffer buffer, Delivery delivery, ProtonSession protonSession) throws HornetQAMQPIllegalStateException
+   @Override
+   public boolean isProtocol(byte[] array)
    {
-      int count;
-      byte[] data = new byte[1024];
-      //todo an optimisation here would be to only use the buffer if we need more that one recv
-      while ((count = receiver.recv(data, 0, data.length)) > 0)
-      {
-         buffer.writeBytes(data, 0, count);
-      }
-
-      // we keep reading until we get end of messages, i.e. -1
-      if (count == 0)
-      {
-         return;
-      }
-      receiver.advance();
-      byte[] bytes = new byte[buffer.readableBytes()];
-      buffer.readBytes(bytes);
-      buffer.clear();
-      MessageImpl msg = new MessageImpl();
-      msg.decode(bytes, 0, bytes.length);
-      Object action = ((AmqpValue) msg.getBody()).getValue();
-      if (action instanceof Declare)
-      {
-         Transaction tx = protonSession.getServerSession().getCurrentTransaction();
-         Declared declared = new Declared();
-         declared.setTxnId(new Binary(longToBytes(tx.getID())));
-         delivery.disposition(declared);
-         delivery.settle();
-      }
-      else if (action instanceof Discharge)
-      {
-         Discharge discharge = (Discharge) action;
-         if (discharge.getFail())
-         {
-            try
-            {
-               protonSession.getServerSession().rollback(false);
-            }
-            catch (Exception e)
-            {
-               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorRollingbackCoordinator(e.getMessage());
-            }
-         }
-         else
-         {
-            try
-            {
-               protonSession.getServerSession().commit();
-            }
-            catch (Exception e)
-            {
-               throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCommittingCoordinator(e.getMessage());
-            }
-         }
-         delivery.settle();
-      }
+      return array.length >= 4 && array[0] == (byte) 'A' && array[1] == (byte) 'M' && array[2] == (byte) 'Q' && array[3] == (byte) 'P';
    }
 
-   public byte[] longToBytes(long x)
+   @Override
+   public void handshake(NettyServerConnection connection, HornetQBuffer buffer)
    {
-      ByteBuffer buffer = ByteBuffer.allocate(8);
-      buffer.putLong(x);
-      return buffer.array();
    }
+
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonRemotingConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonRemotingConnection.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonRemotingConnection.java
deleted file mode 100644
index fab1886..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonRemotingConnection.java
+++ /dev/null
@@ -1,670 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.apache.qpid.proton.amqp.transport.AmqpError;
-import org.apache.qpid.proton.amqp.transport.ErrorCondition;
-import org.apache.qpid.proton.engine.EndpointState;
-import org.apache.qpid.proton.engine.Sasl;
-import org.apache.qpid.proton.engine.Session;
-import org.apache.qpid.proton.engine.impl.ConnectionImpl;
-import org.apache.qpid.proton.engine.impl.DeliveryImpl;
-import org.apache.qpid.proton.engine.impl.LinkImpl;
-import org.apache.qpid.proton.engine.impl.TransportImpl;
-import org.hornetq.api.core.HornetQBuffer;
-import org.hornetq.api.core.HornetQException;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPException;
-import org.hornetq.core.remoting.CloseListener;
-import org.hornetq.core.remoting.FailureListener;
-import org.hornetq.core.server.HornetQServerLogger;
-import org.hornetq.core.server.impl.ServerMessageImpl;
-import org.hornetq.spi.core.protocol.RemotingConnection;
-import org.hornetq.spi.core.remoting.Acceptor;
-import org.hornetq.spi.core.remoting.Connection;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- */
-public class ProtonRemotingConnection implements RemotingConnection
-{
-   private TransportImpl protonTransport;
-
-   private ConnectionImpl protonConnection;
-
-   private final Map<Object, ProtonSession> sessions = new HashMap<Object, ProtonSession>();
-
-   /*
-   * Proton is not thread safe therefore we need to make sure we aren't updating the deliveries on the connection from
-   * the input of proton transport and asynchronously back from HornetQ at the same time.
-   * (this probably needs to be fixed on Proton)
-   * */
-   private final Object deliveryLock = new Object();
-
-   private boolean destroyed = false;
-
-   private String clientId;
-
-   private final Acceptor acceptorUsed;
-
-   private final long creationTime;
-
-   private final Connection connection;
-
-   private final ProtonProtocolManager protonProtocolManager;
-
-   private final List<FailureListener> failureListeners = new CopyOnWriteArrayList<FailureListener>();
-
-   private final List<CloseListener> closeListeners = new CopyOnWriteArrayList<CloseListener>();
-
-   private boolean initialised = false;
-
-   private static final byte[] VERSION_HEADER = new byte[]{
-      'A', 'M', 'Q', 'P', 0, 1, 0, 0
-   };
-   private Sasl sasl;
-
-   private String username;
-
-   private String passcode;
-
-   private boolean dataReceived;
-
-   public ProtonRemotingConnection(Acceptor acceptorUsed, Connection connection, ProtonProtocolManager protonProtocolManager)
-   {
-      this.protonProtocolManager = protonProtocolManager;
-
-      this.connection = connection;
-
-      this.creationTime = System.currentTimeMillis();
-
-      this.acceptorUsed = acceptorUsed;
-
-      this.protonTransport = new TransportImpl();
-
-      this.protonConnection = new ConnectionImpl();
-
-      protonTransport.bind(protonConnection);
-   }
-
-   @Override
-   public Object getID()
-   {
-      return connection.getID();
-   }
-
-   @Override
-   public long getCreationTime()
-   {
-      return creationTime;
-   }
-
-   @Override
-   public String getRemoteAddress()
-   {
-      return connection.getRemoteAddress();
-   }
-
-   @Override
-   public void addFailureListener(final FailureListener listener)
-   {
-      if (listener == null)
-      {
-         throw new IllegalStateException("FailureListener cannot be null");
-      }
-
-      failureListeners.add(listener);
-   }
-
-   @Override
-   public boolean removeFailureListener(final FailureListener listener)
-   {
-      if (listener == null)
-      {
-         throw new IllegalStateException("FailureListener cannot be null");
-      }
-
-      return failureListeners.remove(listener);
-   }
-
-   @Override
-   public void addCloseListener(final CloseListener listener)
-   {
-      if (listener == null)
-      {
-         throw new IllegalStateException("CloseListener cannot be null");
-      }
-
-      closeListeners.add(listener);
-   }
-
-   @Override
-   public boolean removeCloseListener(final CloseListener listener)
-   {
-      if (listener == null)
-      {
-         throw new IllegalStateException("CloseListener cannot be null");
-      }
-
-      return closeListeners.remove(listener);
-   }
-
-   @Override
-   public List<CloseListener> removeCloseListeners()
-   {
-      List<CloseListener> ret = new ArrayList<CloseListener>(closeListeners);
-
-      closeListeners.clear();
-
-      return ret;
-   }
-
-   @Override
-   public List<FailureListener> removeFailureListeners()
-   {
-      List<FailureListener> ret = new ArrayList<FailureListener>(failureListeners);
-
-      failureListeners.clear();
-
-      return ret;
-   }
-
-   @Override
-   public void setCloseListeners(List<CloseListener> listeners)
-   {
-      closeListeners.clear();
-
-      closeListeners.addAll(listeners);
-   }
-
-   @Override
-   public void setFailureListeners(final List<FailureListener> listeners)
-   {
-      failureListeners.clear();
-
-      failureListeners.addAll(listeners);
-   }
-
-   public List<FailureListener> getFailureListeners()
-   {
-      // we do not return the listeners otherwise the remoting service
-      // would NOT destroy the connection.
-      return Collections.emptyList();
-   }
-
-   @Override
-   public HornetQBuffer createBuffer(int size)
-   {
-      return connection.createBuffer(size);
-   }
-
-   @Override
-   public void fail(HornetQException me)
-   {
-      HornetQServerLogger.LOGGER.connectionFailureDetected(me.getMessage(), me.getType());
-      // Then call the listeners
-      callFailureListeners(me);
-
-      callClosingListeners();
-
-      destroyed = true;
-
-      connection.close();
-   }
-
-   @Override
-   public void fail(HornetQException me, String scaleDownTargetNodeID)
-   {
-      fail(me);
-   }
-
-   @Override
-   public void destroy()
-   {
-      destroyed = true;
-
-      connection.close();
-
-      synchronized (deliveryLock)
-      {
-         callClosingListeners();
-      }
-   }
-
-   @Override
-   public Connection getTransportConnection()
-   {
-      return connection;
-   }
-
-   @Override
-   public boolean isClient()
-   {
-      return false;
-   }
-
-   @Override
-   public boolean isDestroyed()
-   {
-      return destroyed;
-   }
-
-   @Override
-   public void disconnect(final boolean criticalError)
-   {
-      disconnect(null, criticalError);
-   }
-
-   @Override
-   public void disconnect(final String scaleDownNodeID, final boolean criticalError)
-   {
-      destroy();
-   }
-
-   @Override
-   public boolean checkDataReceived()
-   {
-      boolean res = dataReceived;
-
-      dataReceived = false;
-
-      return res;
-   }
-
-   @Override
-   public void flush()
-   {
-      //no op
-   }
-
-   @Override
-   public void bufferReceived(Object connectionID, HornetQBuffer buffer)
-   {
-      if (initialised)
-      {
-         protonProtocolManager.handleBuffer(this, buffer);
-      }
-      else
-      {
-         byte[] prot = new byte[4];
-         buffer.readBytes(prot);
-         String headerProt = new String(prot);
-         checkProtocol(headerProt);
-         int protocolId = buffer.readByte();
-         int major = buffer.readByte();
-         int minor = buffer.readByte();
-         int revision = buffer.readByte();
-         if (!(checkVersion(major, minor, revision) && checkProtocol(headerProt)))
-         {
-            protonTransport.close();
-            protonConnection.close();
-            write();
-            destroy();
-            return;
-         }
-         if (protocolId == 3)
-         {
-            sasl = protonTransport.sasl();
-            sasl.setMechanisms(new String[]{"ANONYMOUS", "PLAIN"});
-            sasl.server();
-         }
-
-         ///its only 8 bytes, there's always going to always be enough in the buffer, isn't there?
-         protonTransport.input(VERSION_HEADER, 0, VERSION_HEADER.length);
-
-         write();
-
-         initialised = true;
-
-         if (buffer.readableBytes() > 0)
-         {
-            protonProtocolManager.handleBuffer(this, buffer.copy(buffer.readerIndex(), buffer.readableBytes()));
-         }
-
-         if (sasl != null)
-         {
-            if (sasl.getRemoteMechanisms().length > 0)
-            {
-               if ("PLAIN".equals(sasl.getRemoteMechanisms()[0]))
-               {
-                  byte[] data = new byte[sasl.pending()];
-                  sasl.recv(data, 0, data.length);
-                  sasl.done(Sasl.SaslOutcome.PN_SASL_OK);
-                  sasl = null;
-               }
-               else if ("ANONYMOUS".equals(sasl.getRemoteMechanisms()[0]))
-               {
-                  sasl.done(Sasl.SaslOutcome.PN_SASL_OK);
-                  sasl = null;
-               }
-            }
-
-            write();
-         }
-      }
-   }
-
-   private boolean checkProtocol(String headerProt)
-   {
-      boolean ok = "AMQP".equals(headerProt);
-      if (!ok)
-      {
-         protonConnection.setCondition(new ErrorCondition(AmqpError.ILLEGAL_STATE, "Unknown Protocol " + headerProt));
-      }
-      return ok;
-   }
-
-   private boolean checkVersion(int major, int minor, int revision)
-   {
-      if (major < 1)
-      {
-         protonConnection.setCondition(new ErrorCondition(AmqpError.ILLEGAL_STATE,
-                                                          "Version not supported " + major + "." + minor + "." + revision));
-         return false;
-      }
-      return true;
-   }
-
-   void write()
-   {
-      synchronized (deliveryLock)
-      {
-         int size = 1024 * 64;
-         byte[] data = new byte[size];
-         boolean done = false;
-         while (!done)
-         {
-            int count = protonTransport.output(data, 0, size);
-            if (count > 0)
-            {
-               final HornetQBuffer buffer;
-               buffer = connection.createBuffer(count);
-               buffer.writeBytes(data, 0, count);
-               connection.write(buffer);
-            }
-            else
-            {
-               done = true;
-            }
-         }
-      }
-   }
-
-   public String getLogin()
-   {
-      return username;
-   }
-
-   public String getPasscode()
-   {
-      return passcode;
-   }
-
-   public ServerMessageImpl createServerMessage()
-   {
-      return protonProtocolManager.createServerMessage();
-   }
-
-   protected synchronized void setDataReceived()
-   {
-      dataReceived = true;
-   }
-
-   public void handleFrame(byte[] frame)
-   {
-      int read = 0;
-      while (read < frame.length)
-      {
-         synchronized (deliveryLock)
-         {
-            try
-            {
-               int count = protonTransport.input(frame, read, frame.length - read);
-               read += count;
-            }
-            catch (Exception e)
-            {
-               protonTransport.setCondition(new ErrorCondition(AmqpError.DECODE_ERROR, HornetQAMQPProtocolMessageBundle.BUNDLE.decodeError()));
-               write();
-               protonConnection.close();
-               return;
-            }
-         }
-
-         if (sasl != null)
-         {
-            if (sasl.getRemoteMechanisms().length > 0)
-            {
-               if ("PLAIN".equals(sasl.getRemoteMechanisms()[0]))
-               {
-                  byte[] data = new byte[sasl.pending()];
-                  sasl.recv(data, 0, data.length);
-                  setUserPass(data);
-                  sasl.done(Sasl.SaslOutcome.PN_SASL_OK);
-                  sasl = null;
-               }
-               else if ("ANONYMOUS".equals(sasl.getRemoteMechanisms()[0]))
-               {
-                  sasl.done(Sasl.SaslOutcome.PN_SASL_OK);
-                  sasl = null;
-               }
-            }
-         }
-
-         //handle opening of connection
-         if (protonConnection.getLocalState() == EndpointState.UNINITIALIZED && protonConnection.getRemoteState() != EndpointState.UNINITIALIZED)
-         {
-            clientId = protonConnection.getRemoteContainer();
-            protonConnection.open();
-            write();
-         }
-
-         //handle any new sessions
-         Session session = protonConnection.sessionHead(ProtonProtocolManager.UNINITIALIZED, ProtonProtocolManager.INITIALIZED);
-         while (session != null)
-         {
-            try
-            {
-               ProtonSession protonSession = getSession(session);
-               session.setContext(protonSession);
-               session.open();
-
-            }
-            catch (HornetQAMQPException e)
-            {
-               protonConnection.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-               session.close();
-            }
-            write();
-            session = protonConnection.sessionHead(ProtonProtocolManager.UNINITIALIZED, ProtonProtocolManager.INITIALIZED);
-         }
-
-         //handle new link (producer or consumer
-         LinkImpl link = (LinkImpl) protonConnection.linkHead(ProtonProtocolManager.UNINITIALIZED, ProtonProtocolManager.INITIALIZED);
-         while (link != null)
-         {
-            try
-            {
-               protonProtocolManager.handleNewLink(link, getSession(link.getSession()));
-            }
-            catch (HornetQAMQPException e)
-            {
-               link.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-               link.close();
-            }
-            link = (LinkImpl) protonConnection.linkHead(ProtonProtocolManager.UNINITIALIZED, ProtonProtocolManager.INITIALIZED);
-         }
-
-         //handle any deliveries
-         DeliveryImpl delivery;
-
-         Iterator<DeliveryImpl> iterator = protonConnection.getWorkSequence();
-
-         while (iterator.hasNext())
-         {
-            delivery = iterator.next();
-            ProtonDeliveryHandler handler = (ProtonDeliveryHandler) delivery.getLink().getContext();
-            try
-            {
-               handler.onMessage(delivery);
-            }
-            catch (HornetQAMQPException e)
-            {
-               delivery.getLink().setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-            }
-         }
-
-         link = (LinkImpl) protonConnection.linkHead(ProtonProtocolManager.ACTIVE, ProtonProtocolManager.ANY_ENDPOINT_STATE);
-         while (link != null)
-         {
-            try
-            {
-               protonProtocolManager.handleActiveLink(link);
-            }
-            catch (HornetQAMQPException e)
-            {
-               link.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-            }
-            link = (LinkImpl) link.next(ProtonProtocolManager.ACTIVE, ProtonProtocolManager.ANY_ENDPOINT_STATE);
-         }
-
-         link = (LinkImpl) protonConnection.linkHead(ProtonProtocolManager.ACTIVE, ProtonProtocolManager.CLOSED);
-         while (link != null)
-         {
-            try
-            {
-               ((ProtonDeliveryHandler) link.getContext()).close();
-            }
-            catch (HornetQAMQPException e)
-            {
-               link.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-            }
-            link.close();
-
-            link = (LinkImpl) link.next(ProtonProtocolManager.ACTIVE, ProtonProtocolManager.CLOSED);
-         }
-
-         session = protonConnection.sessionHead(ProtonProtocolManager.ACTIVE, ProtonProtocolManager.CLOSED);
-         while (session != null)
-         {
-            ProtonSession protonSession = (ProtonSession) session.getContext();
-            protonSession.close();
-            sessions.remove(session);
-            session.close();
-            session = session.next(ProtonProtocolManager.ACTIVE, ProtonProtocolManager.CLOSED);
-         }
-
-         if (protonConnection.getLocalState() == EndpointState.ACTIVE && protonConnection.getRemoteState() == EndpointState.CLOSED)
-         {
-            for (ProtonSession protonSession : sessions.values())
-            {
-               protonSession.close();
-            }
-            sessions.clear();
-            protonConnection.close();
-            write();
-            destroy();
-         }
-
-         write();
-      }
-   }
-
-   private void setUserPass(byte[] data)
-   {
-      String bytes = new String(data);
-      String[] credentials = bytes.split(Character.toString((char) 0));
-      int offSet = 0;
-      if (credentials.length > 0)
-      {
-         if (credentials[0].length() == 0)
-         {
-            offSet = 1;
-         }
-
-         if (credentials.length >= offSet)
-         {
-            username = credentials[offSet];
-         }
-         if (credentials.length >= (offSet + 1))
-         {
-            passcode = credentials[offSet + 1];
-         }
-      }
-   }
-
-   private ProtonSession getSession(Session realSession) throws HornetQAMQPException
-   {
-      ProtonSession protonSession = sessions.get(realSession);
-      if (protonSession == null)
-      {
-         protonSession = protonProtocolManager.createSession(this, protonTransport);
-         sessions.put(realSession, protonSession);
-      }
-      return protonSession;
-
-   }
-
-   private void callFailureListeners(final HornetQException me)
-   {
-      final List<FailureListener> listenersClone = new ArrayList<FailureListener>(failureListeners);
-
-      for (final FailureListener listener : listenersClone)
-      {
-         try
-         {
-            listener.connectionFailed(me, false);
-         }
-         catch (final Throwable t)
-         {
-            // Failure of one listener to execute shouldn't prevent others
-            // from
-            // executing
-            HornetQServerLogger.LOGGER.errorCallingFailureListener(t);
-         }
-      }
-   }
-
-   private void callClosingListeners()
-   {
-      final List<CloseListener> listenersClone = new ArrayList<CloseListener>(closeListeners);
-
-      for (final CloseListener listener : listenersClone)
-      {
-         try
-         {
-            listener.connectionClosed();
-         }
-         catch (final Throwable t)
-         {
-            // Failure of one listener to execute shouldn't prevent others
-            // from
-            // executing
-            HornetQServerLogger.LOGGER.errorCallingFailureListener(t);
-         }
-      }
-   }
-
-   public Object getDeliveryLock()
-   {
-      return deliveryLock;
-   }
-}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonSession.java
----------------------------------------------------------------------
diff --git a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonSession.java b/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonSession.java
deleted file mode 100644
index 6c46f2f..0000000
--- a/hornetq-protocols/hornetq-amqp-protocol/src/main/java/org/hornetq/core/protocol/proton/ProtonSession.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * Copyright 2005-2014 Red Hat, Inc.
- * Red Hat licenses this file to you under the Apache License, version
- * 2.0 (the "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *    http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- * implied.  See the License for the specific language governing
- * permissions and limitations under the License.
- */
-
-package org.hornetq.core.protocol.proton;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.qpid.proton.amqp.transaction.Coordinator;
-import org.apache.qpid.proton.amqp.transport.ErrorCondition;
-import org.apache.qpid.proton.engine.Receiver;
-import org.apache.qpid.proton.engine.Sender;
-import org.apache.qpid.proton.engine.impl.TransportImpl;
-import org.hornetq.api.core.SimpleString;
-import org.hornetq.api.core.client.HornetQClient;
-import org.hornetq.core.persistence.OperationContext;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPException;
-import org.hornetq.core.protocol.proton.exceptions.HornetQAMQPInternalErrorException;
-import org.hornetq.core.server.HornetQServer;
-import org.hornetq.core.server.HornetQServerLogger;
-import org.hornetq.core.server.ServerMessage;
-import org.hornetq.core.server.ServerSession;
-import org.hornetq.spi.core.protocol.SessionCallback;
-import org.hornetq.spi.core.remoting.ReadyListener;
-
-/**
- * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         4/10/13
- */
-public class ProtonSession implements SessionCallback
-{
-   private final String name;
-
-   private final ProtonRemotingConnection connection;
-
-   private final HornetQServer server;
-
-   private final TransportImpl protonTransport;
-
-   private final ProtonProtocolManager protonProtocolManager;
-
-   private ServerSession serverSession;
-
-   private OperationContext context;
-
-   //todo make this configurable
-   private int tagCacheSize = 1000;
-
-   private long currentTag = 0;
-
-   private final List<byte[]> tagCache = new ArrayList<byte[]>();
-
-   private Map<Object, ProtonProducer> producers = new HashMap<Object, ProtonProducer>();
-
-   private Map<Long, ProtonConsumer> consumers = new HashMap<Long, ProtonConsumer>();
-
-   private boolean closed = false;
-
-   public ProtonSession(String name, ProtonRemotingConnection connection, ProtonProtocolManager protonProtocolManager, OperationContext operationContext, HornetQServer server, TransportImpl protonTransport)
-   {
-      this.name = name;
-      this.connection = connection;
-      context = operationContext;
-      this.server = server;
-      this.protonTransport = protonTransport;
-      this.protonProtocolManager = protonProtocolManager;
-   }
-
-   public ServerSession getServerSession()
-   {
-      return serverSession;
-   }
-
-   /*
-   * we need to initialise the actual server session when we receive the first linkas this tells us whether or not the
-   * session is transactional
-   * */
-   public void initialise(boolean transacted) throws HornetQAMQPInternalErrorException
-   {
-      if (serverSession == null)
-      {
-         try
-         {
-            serverSession = server.createSession(name,
-                                                 connection.getLogin(),
-                                                 connection.getPasscode(),
-                                                 HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
-                                                 connection,
-                                                 !transacted,
-                                                 !transacted,
-                                                 false,
-                                                 false,
-                                                 null,
-                                                 this);
-         }
-         catch (Exception e)
-         {
-            throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorCreatingHornetQSession(e.getMessage());
-         }
-      }
-   }
-
-   @Override
-   public void sendProducerCreditsMessage(int credits, SimpleString address)
-   {
-   }
-
-   @Override
-   public void sendProducerCreditsFailMessage(int credits, SimpleString address)
-   {
-   }
-
-   @Override
-   public int sendMessage(ServerMessage message, long consumerID, int deliveryCount)
-   {
-      ProtonConsumer protonConsumer = consumers.get(consumerID);
-      if (protonConsumer != null)
-      {
-         return protonConsumer.handleDelivery(message, deliveryCount);
-      }
-      return 0;
-   }
-
-   @Override
-   public int sendLargeMessage(ServerMessage message, long consumerID, long bodySize, int deliveryCount)
-   {
-      return 0;
-   }
-
-   @Override
-   public int sendLargeMessageContinuation(long consumerID, byte[] body, boolean continues, boolean requiresResponse)
-   {
-      return 0;
-   }
-
-   @Override
-   public void closed()
-   {
-      //To change body of implemented methods use File | Settings | File Templates.
-   }
-
-   @Override
-   public void addReadyListener(ReadyListener listener)
-   {
-      //To change body of implemented methods use File | Settings | File Templates.
-   }
-
-   @Override
-   public void removeReadyListener(ReadyListener listener)
-   {
-      //To change body of implemented methods use File | Settings | File Templates.
-   }
-
-   @Override
-   public void disconnect(long consumerId, String queueName)
-   {
-      ProtonConsumer protonConsumer = consumers.remove(consumerId);
-      if (protonConsumer != null)
-      {
-         try
-         {
-            protonConsumer.close();
-         }
-         catch (HornetQAMQPException e)
-         {
-            protonConsumer.getSender().setTarget(null);
-            protonConsumer.getSender().setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-         }
-         connection.write();
-      }
-   }
-
-   public OperationContext getContext()
-   {
-      return context;
-   }
-
-   public void addProducer(Receiver receiver) throws HornetQAMQPException
-   {
-      try
-      {
-         ProtonProducer producer = new ProtonProducer(connection, this, protonProtocolManager, receiver);
-         producer.init();
-         producers.put(receiver, producer);
-         receiver.setContext(producer);
-         receiver.open();
-      }
-      catch (HornetQAMQPException e)
-      {
-         producers.remove(receiver);
-         receiver.setTarget(null);
-         receiver.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-         receiver.close();
-      }
-   }
-
-
-   public void addTransactionHandler(Coordinator coordinator, Receiver receiver)
-   {
-      TransactionHandler transactionHandler = new TransactionHandler(connection, coordinator, protonProtocolManager, this);
-      receiver.setContext(transactionHandler);
-      receiver.open();
-      receiver.flow(100);
-   }
-
-   public void addConsumer(Sender sender) throws HornetQAMQPException
-   {
-      ProtonConsumer protonConsumer = new ProtonConsumer(connection, sender, this, server, protonProtocolManager);
-
-      try
-      {
-         protonConsumer.init();
-         consumers.put(protonConsumer.getConsumerID(), protonConsumer);
-         sender.setContext(protonConsumer);
-         sender.open();
-         protonConsumer.start();
-      }
-      catch (HornetQAMQPException e)
-      {
-         consumers.remove(protonConsumer.getConsumerID());
-         sender.setSource(null);
-         sender.setCondition(new ErrorCondition(e.getAmqpError(), e.getMessage()));
-         sender.close();
-      }
-   }
-
-   public byte[] getTag()
-   {
-      synchronized (tagCache)
-      {
-         byte[] bytes;
-         if (tagCache.size() > 0)
-         {
-            bytes = tagCache.remove(0);
-         }
-         else
-         {
-            bytes = Long.toHexString(currentTag++).getBytes();
-         }
-         return bytes;
-      }
-   }
-
-   public void replaceTag(byte[] tag)
-   {
-      synchronized (tagCache)
-      {
-         if (tagCache.size() < tagCacheSize)
-         {
-            tagCache.add(tag);
-         }
-      }
-   }
-
-   public void close()
-   {
-      if (closed)
-      {
-         return;
-      }
-
-      for (ProtonProducer protonProducer : producers.values())
-      {
-         try
-         {
-            protonProducer.close();
-         }
-         catch (Exception e)
-         {
-            HornetQServerLogger.LOGGER.errorClosingSession(e);
-         }
-      }
-      producers.clear();
-      for (ProtonConsumer protonConsumer : consumers.values())
-      {
-         try
-         {
-            protonConsumer.close();
-         }
-         catch (Exception e)
-         {
-            HornetQServerLogger.LOGGER.errorClosingConsumer(e);
-         }
-      }
-      consumers.clear();
-      try
-      {
-         getServerSession().rollback(true);
-         getServerSession().close(false);
-      }
-      catch (Exception e)
-      {
-         HornetQServerLogger.LOGGER.errorClosingSession(e);
-      }
-      closed = true;
-   }
-
-   public void removeConsumer(long consumerID) throws HornetQAMQPException
-   {
-      consumers.remove(consumerID);
-      try
-      {
-         getServerSession().closeConsumer(consumerID);
-      }
-      catch (Exception e)
-      {
-         throw HornetQAMQPProtocolMessageBundle.BUNDLE.errorClosingConsumer(consumerID, e.getMessage());
-      }
-   }
-
-   public void removeProducer(Receiver receiver)
-   {
-      producers.remove(receiver);
-   }
-}


[39/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQStreamMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQStreamMessage.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQStreamMessage.java
index 199df55..4f3e899 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQStreamMessage.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQStreamMessage.java
@@ -19,11 +19,24 @@ import javax.jms.StreamMessage;
 
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.Message;
+import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientSession;
 import org.hornetq.core.client.impl.ClientMessageImpl;
 import org.hornetq.utils.DataConstants;
 
+import static org.hornetq.reader.StreamMessageUtil.streamReadBoolean;
+import static org.hornetq.reader.StreamMessageUtil.streamReadByte;
+import static org.hornetq.reader.StreamMessageUtil.streamReadBytes;
+import static org.hornetq.reader.StreamMessageUtil.streamReadChar;
+import static org.hornetq.reader.StreamMessageUtil.streamReadDouble;
+import static org.hornetq.reader.StreamMessageUtil.streamReadFloat;
+import static org.hornetq.reader.StreamMessageUtil.streamReadInteger;
+import static org.hornetq.reader.StreamMessageUtil.streamReadLong;
+import static org.hornetq.reader.StreamMessageUtil.streamReadObject;
+import static org.hornetq.reader.StreamMessageUtil.streamReadShort;
+import static org.hornetq.reader.StreamMessageUtil.streamReadString;
+
 /**
  * HornetQ implementation of a JMS StreamMessage.
  *
@@ -92,18 +105,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-
-         switch (type)
-         {
-            case DataConstants.BOOLEAN:
-               return getBuffer().readBoolean();
-            case DataConstants.STRING:
-               String s = getBuffer().readNullableString();
-               return Boolean.valueOf(s);
-            default:
-               throw new MessageFormatException("Invalid conversion, type byte was " + type);
-         }
+         return streamReadBoolean(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -114,29 +120,18 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
    public byte readByte() throws JMSException
    {
       checkRead();
-      int index = getBuffer().readerIndex();
+
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.BYTE:
-               return getBuffer().readByte();
-            case DataConstants.STRING:
-               String s = getBuffer().readNullableString();
-               return Byte.parseByte(s);
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadByte(message);
       }
-      catch (IndexOutOfBoundsException e)
+      catch (IllegalStateException e)
       {
-         throw new MessageEOFException("");
+         throw new MessageFormatException(e.getMessage());
       }
-      catch (NumberFormatException e)
+      catch (IndexOutOfBoundsException e)
       {
-         getBuffer().readerIndex(index);
-         throw e;
+         throw new MessageEOFException("");
       }
    }
 
@@ -145,19 +140,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.BYTE:
-               return getBuffer().readByte();
-            case DataConstants.SHORT:
-               return getBuffer().readShort();
-            case DataConstants.STRING:
-               String s = getBuffer().readNullableString();
-               return Short.parseShort(s);
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadShort(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -170,24 +157,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.CHAR:
-               return (char)getBuffer().readShort();
-            case DataConstants.STRING:
-               String str = getBuffer().readNullableString();
-               if (str == null)
-               {
-                  throw new NullPointerException("Invalid conversion");
-               }
-               else
-               {
-                  throw new MessageFormatException("Invalid conversion");
-               }
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadChar(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -200,21 +174,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.BYTE:
-               return getBuffer().readByte();
-            case DataConstants.SHORT:
-               return getBuffer().readShort();
-            case DataConstants.INT:
-               return getBuffer().readInt();
-            case DataConstants.STRING:
-               String s = getBuffer().readNullableString();
-               return Integer.parseInt(s);
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadInteger(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -227,23 +191,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.BYTE:
-               return getBuffer().readByte();
-            case DataConstants.SHORT:
-               return getBuffer().readShort();
-            case DataConstants.INT:
-               return getBuffer().readInt();
-            case DataConstants.LONG:
-               return getBuffer().readLong();
-            case DataConstants.STRING:
-               String s = getBuffer().readNullableString();
-               return Long.parseLong(s);
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadLong(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -256,17 +208,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.FLOAT:
-               return Float.intBitsToFloat(getBuffer().readInt());
-            case DataConstants.STRING:
-               String s = getBuffer().readNullableString();
-               return Float.parseFloat(s);
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadFloat(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -279,19 +225,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.FLOAT:
-               return Float.intBitsToFloat(getBuffer().readInt());
-            case DataConstants.DOUBLE:
-               return Double.longBitsToDouble(getBuffer().readLong());
-            case DataConstants.STRING:
-               String s = getBuffer().readNullableString();
-               return Double.parseDouble(s);
-            default:
-               throw new MessageFormatException("Invalid conversion: " + type);
-         }
+         return streamReadDouble(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -304,30 +242,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.BOOLEAN:
-               return String.valueOf(getBuffer().readBoolean());
-            case DataConstants.BYTE:
-               return String.valueOf(getBuffer().readByte());
-            case DataConstants.SHORT:
-               return String.valueOf(getBuffer().readShort());
-            case DataConstants.CHAR:
-               return String.valueOf((char)getBuffer().readShort());
-            case DataConstants.INT:
-               return String.valueOf(getBuffer().readInt());
-            case DataConstants.LONG:
-               return String.valueOf(getBuffer().readLong());
-            case DataConstants.FLOAT:
-               return String.valueOf(Float.intBitsToFloat(getBuffer().readInt()));
-            case DataConstants.DOUBLE:
-               return String.valueOf(Double.longBitsToDouble(getBuffer().readLong()));
-            case DataConstants.STRING:
-               return getBuffer().readNullableString();
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadString(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -335,35 +254,24 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       }
    }
 
-   private int len;
+   /**
+    * len here is used to control how many more bytes to read
+    */
+   private int len = 0;
 
    public int readBytes(final byte[] value) throws JMSException
    {
       checkRead();
       try
       {
-         if (len == -1)
-         {
-            len = 0;
-            return -1;
-         }
-         else if (len == 0)
-         {
-            byte type = getBuffer().readByte();
-            if (type != DataConstants.BYTES)
-            {
-               throw new MessageFormatException("Invalid conversion");
-            }
-            len = getBuffer().readInt();
-         }
-         int read = Math.min(value.length, len);
-         getBuffer().readBytes(value, 0, read);
-         len -= read;
-         if (len == 0)
-         {
-            len = -1;
-         }
-         return read;
+         Pair<Integer, Integer> pairRead = streamReadBytes(message, len, value);
+
+         len = pairRead.getA();
+         return pairRead.getB();
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -376,35 +284,11 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
       checkRead();
       try
       {
-         byte type = getBuffer().readByte();
-         switch (type)
-         {
-            case DataConstants.BOOLEAN:
-               return getBuffer().readBoolean();
-            case DataConstants.BYTE:
-               return getBuffer().readByte();
-            case DataConstants.SHORT:
-               return getBuffer().readShort();
-            case DataConstants.CHAR:
-               return (char)getBuffer().readShort();
-            case DataConstants.INT:
-               return getBuffer().readInt();
-            case DataConstants.LONG:
-               return getBuffer().readLong();
-            case DataConstants.FLOAT:
-               return Float.intBitsToFloat(getBuffer().readInt());
-            case DataConstants.DOUBLE:
-               return Double.longBitsToDouble(getBuffer().readLong());
-            case DataConstants.STRING:
-               return getBuffer().readNullableString();
-            case DataConstants.BYTES:
-               int bufferLen = getBuffer().readInt();
-               byte[] bytes = new byte[bufferLen];
-               getBuffer().readBytes(bytes);
-               return bytes;
-            default:
-               throw new MessageFormatException("Invalid conversion");
-         }
+         return streamReadObject(message);
+      }
+      catch (IllegalStateException e)
+      {
+         throw new MessageFormatException(e.getMessage());
       }
       catch (IndexOutOfBoundsException e)
       {
@@ -555,7 +439,7 @@ public final class HornetQStreamMessage extends HornetQMessage implements Stream
    // HornetQRAMessage overrides ----------------------------------------
 
    @Override
-   public void clearBody()
+   public void clearBody() throws JMSException
    {
       super.clearBody();
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQTextMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQTextMessage.java b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQTextMessage.java
index 35b587b..96b7a45 100644
--- a/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQTextMessage.java
+++ b/hornetq-jms-client/src/main/java/org/hornetq/jms/client/HornetQTextMessage.java
@@ -15,13 +15,16 @@ package org.hornetq.jms.client;
 import javax.jms.JMSException;
 import javax.jms.TextMessage;
 
-import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.Message;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.client.ClientMessage;
 import org.hornetq.api.core.client.ClientSession;
 
+import static org.hornetq.reader.TextMessageUtil.readBodyText;
+import static org.hornetq.reader.TextMessageUtil.writeBodyText;
+
+
 /**
  * HornetQ implementation of a JMS TextMessage.
  * <br>
@@ -85,10 +88,6 @@ public class HornetQTextMessage extends HornetQMessage implements TextMessage
    {
       checkWrite();
 
-      HornetQBuffer buff = message.getBodyBuffer();
-
-      buff.clear();
-
       if (text != null)
       {
          this.text = new SimpleString(text);
@@ -98,7 +97,7 @@ public class HornetQTextMessage extends HornetQMessage implements TextMessage
          this.text = null;
       }
 
-      buff.writeNullableSimpleString(this.text);
+      writeBodyText(message, this.text);
    }
 
    public String getText()
@@ -114,7 +113,7 @@ public class HornetQTextMessage extends HornetQMessage implements TextMessage
    }
 
    @Override
-   public void clearBody()
+   public void clearBody() throws JMSException
    {
       super.clearBody();
 
@@ -128,7 +127,7 @@ public class HornetQTextMessage extends HornetQMessage implements TextMessage
    {
       super.doBeforeReceive();
 
-      text = message.getBodyBuffer().readNullableSimpleString();
+      text = readBodyText(message);
    }
 
    @Override

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/pom.xml
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/pom.xml b/hornetq-jms-server/pom.xml
index c0323f6..60a7c46 100644
--- a/hornetq-jms-server/pom.xml
+++ b/hornetq-jms-server/pom.xml
@@ -42,7 +42,7 @@
       </dependency>
       <dependency>
          <groupId>org.jboss.spec.javax.transaction</groupId>
-         <artifactId>jboss-transaction-api_1.1_spec</artifactId>
+         <artifactId>jboss-transaction-api_1.2_spec</artifactId>
       </dependency>
       <dependency>
          <groupId>org.jboss.jbossts.jts</groupId>

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/HornetQJMSBridgeLogger.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/HornetQJMSBridgeLogger.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/HornetQJMSBridgeLogger.java
new file mode 100644
index 0000000..688c7d0
--- /dev/null
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/HornetQJMSBridgeLogger.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.jms.bridge;
+
+import javax.management.ObjectName;
+
+import org.jboss.logging.BasicLogger;
+import org.jboss.logging.Logger;
+import org.jboss.logging.annotations.Cause;
+import org.jboss.logging.annotations.LogMessage;
+import org.jboss.logging.annotations.Message;
+import org.jboss.logging.annotations.MessageLogger;
+
+/**
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
+ *
+ * Logger Code 34
+ *
+ * each message id must be 6 digits long starting with 12, the 3rd digit donates the level so
+ *
+ * INF0  1
+ * WARN  2
+ * DEBUG 3
+ * ERROR 4
+ * TRACE 5
+ * FATAL 6
+ *
+ * so an INFO message would be 341000 to 341999
+ */
+@MessageLogger(projectCode = "HQ")
+public interface HornetQJMSBridgeLogger extends BasicLogger
+{
+   /**
+    * The default logger.
+    */
+   HornetQJMSBridgeLogger LOGGER = Logger.getMessageLogger(HornetQJMSBridgeLogger.class, HornetQJMSBridgeLogger.class.getPackage().getName());
+
+   @LogMessage(level = Logger.Level.INFO)
+   @Message(id = 341000, value = "Failed to set up JMS bridge connections. Most probably the source or target servers are unavailable." +
+         " Will retry after a pause of {0} ms", format = Message.Format.MESSAGE_FORMAT)
+   void failedToSetUpBridge(long failureRetryInterval);
+
+   @LogMessage(level = Logger.Level.INFO)
+   @Message(id = 341001, value = "JMS Bridge Succeeded in reconnecting to servers" , format = Message.Format.MESSAGE_FORMAT)
+   void bridgeReconnected();
+
+   @LogMessage(level = Logger.Level.INFO)
+   @Message(id = 341002, value = "Succeeded in connecting to servers" , format = Message.Format.MESSAGE_FORMAT)
+   void bridgeConnected();
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342000, value = "Attempt to start JMS Bridge, but is already started" , format = Message.Format.MESSAGE_FORMAT)
+   void errorBridgeAlreadyStarted();
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342001, value = "Failed to start JMS Bridge" , format = Message.Format.MESSAGE_FORMAT)
+   void errorStartingBridge();
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342002, value = "Failed to unregisted JMS Bridge {0}" , format = Message.Format.MESSAGE_FORMAT)
+   void errorUnregisteringBridge(ObjectName objectName);
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342003, value = "JMS Bridge unable to set up connections, bridge will be stopped" , format = Message.Format.MESSAGE_FORMAT)
+   void errorConnectingBridge();
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342004, value = "JMS Bridge Will retry after a pause of {0} ms" , format = Message.Format.MESSAGE_FORMAT)
+   void bridgeRetry(long failureRetryInterval);
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342005, value = "JMS Bridge unable to set up connections, bridge will not be started" , format = Message.Format.MESSAGE_FORMAT)
+   void bridgeNotStarted();
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342006, value = "Detected failure on bridge connection" , format = Message.Format.MESSAGE_FORMAT)
+   void bridgeFailure(@Cause Exception e);
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342009, value = "JMS Bridge failed to send + acknowledge batch, closing JMS objects"  , format = Message.Format.MESSAGE_FORMAT)
+   void bridgeAckError(@Cause Exception e);
+
+   @LogMessage(level = Logger.Level.WARN)
+   @Message(id = 342010, value = "Failed to connect JMS Bridge", format = Message.Format.MESSAGE_FORMAT)
+   void bridgeConnectError(@Cause Exception e);
+
+   @LogMessage(level = Logger.Level.ERROR)
+   @Message(id = 344001, value = "Failed to start source connection" , format = Message.Format.MESSAGE_FORMAT)
+   void jmsBridgeSrcConnectError(@Cause Exception e);
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/impl/JMSBridgeImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/impl/JMSBridgeImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/impl/JMSBridgeImpl.java
index 09eec8c..ace70ef 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/impl/JMSBridgeImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/bridge/impl/JMSBridgeImpl.java
@@ -52,6 +52,7 @@ import org.hornetq.api.core.client.FailoverEventType;
 import org.hornetq.api.jms.HornetQJMSConstants;
 import org.hornetq.jms.bridge.ConnectionFactoryFactory;
 import org.hornetq.jms.bridge.DestinationFactory;
+import org.hornetq.jms.bridge.HornetQJMSBridgeLogger;
 import org.hornetq.jms.bridge.JMSBridge;
 import org.hornetq.jms.bridge.JMSBridgeControl;
 import org.hornetq.jms.bridge.QualityOfServiceMode;
@@ -59,7 +60,6 @@ import org.hornetq.jms.client.HornetQConnection;
 import org.hornetq.jms.client.HornetQConnectionFactory;
 import org.hornetq.jms.client.HornetQMessage;
 import org.hornetq.jms.server.HornetQJMSServerBundle;
-import org.hornetq.jms.server.HornetQJMSServerLogger;
 import org.hornetq.jms.server.recovery.HornetQRegistryBase;
 import org.hornetq.jms.server.recovery.XARecoveryConfig;
 import org.hornetq.utils.ClassloadingUtil;
@@ -71,13 +71,14 @@ import org.hornetq.utils.SensitiveDataCodec;
  * A JMSBridge
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  * @version <tt>$Revision:4566 $</tt>
  */
 public final class JMSBridgeImpl implements JMSBridge
 {
    private static final String[] RESOURCE_RECOVERY_CLASS_NAMES = new String[]{"org.jboss.as.messaging.jms.AS7RecoveryRegistry"};
 
-   private static boolean trace = HornetQJMSServerLogger.LOGGER.isTraceEnabled();
+   private static boolean trace = HornetQJMSBridgeLogger.LOGGER.isTraceEnabled();
 
    private static final int TEN_YEARS = 60 * 60 * 24 * 365 * 10; // in ms
 
@@ -156,6 +157,10 @@ public final class JMSBridgeImpl implements JMSBridge
 
    private boolean failed;
 
+   private boolean connectedSource = false;
+
+   private boolean connectedTarget = false;
+
    private int forwardMode;
 
    private String transactionManagerLocatorClass = "org.hornetq.integration.jboss.tm.JBoss5TransactionManagerLocator";
@@ -344,7 +349,7 @@ public final class JMSBridgeImpl implements JMSBridge
                this.objectName = ObjectName.getInstance(objectName);
                StandardMBean mbean = new StandardMBean(controlBean, JMSBridgeControl.class);
                mbeanServer.registerMBean(mbean, this.objectName);
-               HornetQJMSServerLogger.LOGGER.debug("Registered JMSBridge instance as: " + this.objectName.getCanonicalName());
+               HornetQJMSBridgeLogger.LOGGER.debug("Registered JMSBridge instance as: " + this.objectName.getCanonicalName());
             }
             catch (Exception e)
             {
@@ -359,7 +364,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Created " + this);
+         HornetQJMSBridgeLogger.LOGGER.trace("Created " + this);
       }
    }
 
@@ -376,13 +381,13 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (started)
       {
-         HornetQJMSServerLogger.LOGGER.errorBridgeAlreadyStarted();
+         HornetQJMSBridgeLogger.LOGGER.errorBridgeAlreadyStarted();
          return;
       }
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Starting " + this);
+         HornetQJMSBridgeLogger.LOGGER.trace("Starting " + this);
       }
 
       // bridge has been stopped and is restarted
@@ -418,11 +423,13 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (ok)
       {
+         connectedSource = true;
+         connectedTarget = true;
          startSource();
       }
       else
       {
-         HornetQJMSServerLogger.LOGGER.errorStartingBridge();
+         HornetQJMSBridgeLogger.LOGGER.errorStartingBridge();
          handleFailureOnStartup();
       }
 
@@ -440,7 +447,7 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Starting time checker thread");
+            HornetQJMSBridgeLogger.LOGGER.trace("Starting time checker thread");
          }
 
          timeChecker = new BatchTimeChecker();
@@ -450,7 +457,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Started time checker thread");
+            HornetQJMSBridgeLogger.LOGGER.trace("Started time checker thread");
          }
       }
 
@@ -458,7 +465,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Started " + this);
+         HornetQJMSBridgeLogger.LOGGER.trace("Started " + this);
       }
    }
 
@@ -505,9 +512,16 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Stopping " + this);
+            HornetQJMSBridgeLogger.LOGGER.trace("Stopping " + this);
+         }
+         if (!connectedSource && sourceConn != null)
+         {
+            sourceConn.close();
+         }
+         if (!connectedTarget && targetConn != null)
+         {
+            targetConn.close();
          }
-
          synchronized (lock)
          {
             started = false;
@@ -527,7 +541,7 @@ public final class JMSBridgeImpl implements JMSBridge
             // Terminate any transaction
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Rolling back remaining tx");
+               HornetQJMSBridgeLogger.LOGGER.trace("Rolling back remaining tx");
             }
 
             try
@@ -538,13 +552,13 @@ public final class JMSBridgeImpl implements JMSBridge
             {
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace("Failed to rollback", ignore);
+                  HornetQJMSBridgeLogger.LOGGER.trace("Failed to rollback", ignore);
                }
             }
 
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Rolled back remaining tx");
+               HornetQJMSBridgeLogger.LOGGER.trace("Rolled back remaining tx");
             }
          }
 
@@ -556,7 +570,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Failed to close source conn", ignore);
+               HornetQJMSBridgeLogger.LOGGER.trace("Failed to close source conn", ignore);
             }
          }
 
@@ -570,14 +584,14 @@ public final class JMSBridgeImpl implements JMSBridge
             {
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace("Failed to close target conn", ignore);
+                  HornetQJMSBridgeLogger.LOGGER.trace("Failed to close target conn", ignore);
                }
             }
          }
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Stopped " + this);
+            HornetQJMSBridgeLogger.LOGGER.trace("Stopped " + this);
          }
       }
    }
@@ -597,7 +611,7 @@ public final class JMSBridgeImpl implements JMSBridge
          }
          catch (Exception e)
          {
-            HornetQJMSServerLogger.LOGGER.errorUnregisteringBridge(objectName);
+            HornetQJMSBridgeLogger.LOGGER.errorUnregisteringBridge(objectName);
          }
       }
    }
@@ -608,7 +622,7 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Pausing " + this);
+         HornetQJMSBridgeLogger.LOGGER.trace("Pausing " + this);
       }
 
       synchronized (lock)
@@ -620,7 +634,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Paused " + this);
+         HornetQJMSBridgeLogger.LOGGER.trace("Paused " + this);
       }
    }
 
@@ -628,7 +642,7 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Resuming " + this);
+         HornetQJMSBridgeLogger.LOGGER.trace("Resuming " + this);
       }
 
       synchronized (lock)
@@ -640,7 +654,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Resumed " + this);
+         HornetQJMSBridgeLogger.LOGGER.trace("Resumed " + this);
       }
    }
 
@@ -955,7 +969,7 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Enlisting resources in tx");
+         HornetQJMSBridgeLogger.LOGGER.trace("Enlisting resources in tx");
       }
 
       XAResource resSource = ((XASession) sourceSession).getXAResource();
@@ -968,7 +982,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Enlisted resources in tx");
+         HornetQJMSBridgeLogger.LOGGER.trace("Enlisted resources in tx");
       }
    }
 
@@ -976,7 +990,7 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Delisting resources from tx");
+         HornetQJMSBridgeLogger.LOGGER.trace("Delisting resources from tx");
       }
 
       XAResource resSource = ((XASession) sourceSession).getXAResource();
@@ -989,7 +1003,7 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Failed to delist source resource", e);
+            HornetQJMSBridgeLogger.LOGGER.trace("Failed to delist source resource", e);
          }
       }
 
@@ -1003,13 +1017,13 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Failed to delist target resource", e);
+            HornetQJMSBridgeLogger.LOGGER.trace("Failed to delist target resource", e);
          }
       }
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Delisted resources from tx");
+         HornetQJMSBridgeLogger.LOGGER.trace("Delisted resources from tx");
       }
    }
 
@@ -1017,7 +1031,7 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Starting JTA transaction");
+         HornetQJMSBridgeLogger.LOGGER.trace("Starting JTA transaction");
       }
 
       TransactionManager tm = getTm();
@@ -1037,7 +1051,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Started JTA transaction");
+         HornetQJMSBridgeLogger.LOGGER.trace("Started JTA transaction");
       }
 
       return tx;
@@ -1073,7 +1087,8 @@ public final class JMSBridgeImpl implements JMSBridge
    private Connection createConnection(final String username, final String password,
                                        final ConnectionFactoryFactory cff,
                                        final String clientID,
-                                       final boolean isXA) throws Exception
+                                       final boolean isXA,
+                                       boolean isSource) throws Exception
    {
       Connection conn;
 
@@ -1095,7 +1110,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Creating an XA connection");
+               HornetQJMSBridgeLogger.LOGGER.trace("Creating an XA connection");
             }
             conn = ((XAConnectionFactory) cf).createXAConnection();
          }
@@ -1103,7 +1118,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Creating a non XA connection");
+               HornetQJMSBridgeLogger.LOGGER.trace("Creating a non XA connection");
             }
             conn = ((ConnectionFactory) cf).createConnection();
          }
@@ -1114,7 +1129,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Creating an XA connection");
+               HornetQJMSBridgeLogger.LOGGER.trace("Creating an XA connection");
             }
             conn = ((XAConnectionFactory) cf).createXAConnection(username, password);
          }
@@ -1122,7 +1137,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Creating a non XA connection");
+               HornetQJMSBridgeLogger.LOGGER.trace("Creating a non XA connection");
             }
             conn = ((ConnectionFactory) cf).createConnection(username, password);
          }
@@ -1144,12 +1159,12 @@ public final class JMSBridgeImpl implements JMSBridge
          if (ha)
          {
             HornetQConnection hornetQConn = (HornetQConnection) conn;
-            failoverListener = new BridgeFailoverListener();
+            failoverListener = new BridgeFailoverListener(isSource);
             hornetQConn.setFailoverListener(failoverListener);
          }
       }
 
-      conn.setExceptionListener(new BridgeExceptionListener(ha, failoverListener));
+      conn.setExceptionListener(new BridgeExceptionListener(ha, failoverListener, isSource));
 
       return conn;
    }
@@ -1223,7 +1238,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             // We simply use a single local transacted session for consuming and sending
 
-            sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, false);
+            sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, false, true);
             sourceSession = sourceConn.createSession(true, Session.SESSION_TRANSACTED);
          }
          else // bridging across different servers
@@ -1234,20 +1249,20 @@ public final class JMSBridgeImpl implements JMSBridge
                // Create an XASession for consuming from the source
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace("Creating XA source session");
+                  HornetQJMSBridgeLogger.LOGGER.trace("Creating XA source session");
                }
 
-               sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, true);
+               sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, true, true);
                sourceSession = ((XAConnection) sourceConn).createXASession();
             }
             else // QoS = DUPLICATES_OK || AT_MOST_ONCE
             {
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace("Creating non XA source session");
+                  HornetQJMSBridgeLogger.LOGGER.trace("Creating non XA source session");
                }
 
-               sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, false);
+               sourceConn = createConnection(sourceUsername, sourcePassword, sourceCff, clientID, false, true);
                if (qualityOfServiceMode == QualityOfServiceMode.AT_MOST_ONCE && maxBatchSize == 1)
                {
                   sourceSession = sourceConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
@@ -1298,12 +1313,12 @@ public final class JMSBridgeImpl implements JMSBridge
             {
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace("Creating XA dest session");
+                  HornetQJMSBridgeLogger.LOGGER.trace("Creating XA dest session");
                }
 
                // Create an XA session for sending to the destination
 
-               targetConn = createConnection(targetUsername, targetPassword, targetCff, null, true);
+               targetConn = createConnection(targetUsername, targetPassword, targetCff, null, true, false);
 
                targetSession = ((XAConnection) targetConn).createXASession();
             }
@@ -1311,7 +1326,7 @@ public final class JMSBridgeImpl implements JMSBridge
             {
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace("Creating non XA dest session");
+                  HornetQJMSBridgeLogger.LOGGER.trace("Creating non XA dest session");
                }
 
                // Create a standard session for sending to the target
@@ -1320,7 +1335,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
                boolean transacted = maxBatchSize > 1;
 
-               targetConn = createConnection(targetUsername, targetPassword, targetCff, null, false);
+               targetConn = createConnection(targetUsername, targetPassword, targetCff, null, false, false);
 
                targetSession = targetConn.createSession(transacted, transacted ? Session.SESSION_TRANSACTED
                   : Session.AUTO_ACKNOWLEDGE);
@@ -1331,7 +1346,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Starting JTA transaction");
+               HornetQJMSBridgeLogger.LOGGER.trace("Starting JTA transaction");
             }
 
             tx = startTx();
@@ -1350,7 +1365,7 @@ public final class JMSBridgeImpl implements JMSBridge
          // If this fails we should attempt to cleanup or we might end up in some weird state
 
          // Adding a log.warn, so the use may see the cause of the failure and take actions
-         HornetQJMSServerLogger.LOGGER.bridgeConnectError(e);
+         HornetQJMSBridgeLogger.LOGGER.bridgeConnectError(e);
 
          cleanup();
 
@@ -1369,7 +1384,7 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Failed to stop source connection", ignore);
+            HornetQJMSBridgeLogger.LOGGER.trace("Failed to stop source connection", ignore);
          }
       }
 
@@ -1383,7 +1398,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Failed to delist resources", ignore);
+               HornetQJMSBridgeLogger.LOGGER.trace("Failed to delist resources", ignore);
             }
          }
          try
@@ -1395,7 +1410,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Failed to rollback", ignore);
+               HornetQJMSBridgeLogger.LOGGER.trace("Failed to rollback", ignore);
             }
          }
       }
@@ -1409,7 +1424,7 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Failed to close source connection", ignore);
+            HornetQJMSBridgeLogger.LOGGER.trace("Failed to close source connection", ignore);
          }
       }
       try
@@ -1423,7 +1438,7 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Failed to close target connection", ignore);
+            HornetQJMSBridgeLogger.LOGGER.trace("Failed to close target connection", ignore);
          }
       }
    }
@@ -1447,7 +1462,7 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Setting up connections");
+         HornetQJMSBridgeLogger.LOGGER.trace("Setting up connections");
       }
 
       int count = 0;
@@ -1468,7 +1483,7 @@ public final class JMSBridgeImpl implements JMSBridge
             break;
          }
 
-         HornetQJMSServerLogger.LOGGER.failedToSetUpBridge(failureRetryInterval);
+         HornetQJMSBridgeLogger.LOGGER.failedToSetUpBridge(failureRetryInterval);
 
          pause(failureRetryInterval);
       }
@@ -1481,7 +1496,7 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Sending batch of " + messages.size() + " messages");
+         HornetQJMSBridgeLogger.LOGGER.trace("Sending batch of " + messages.size() + " messages");
       }
 
       if (paused)
@@ -1489,7 +1504,7 @@ public final class JMSBridgeImpl implements JMSBridge
          // Don't send now
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Paused, so not sending now");
+            HornetQJMSBridgeLogger.LOGGER.trace("Paused, so not sending now");
          }
 
          return;
@@ -1520,14 +1535,14 @@ public final class JMSBridgeImpl implements JMSBridge
 
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Client acking source session");
+               HornetQJMSBridgeLogger.LOGGER.trace("Client acking source session");
             }
 
             messages.getLast().acknowledge();
 
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Client acked source session");
+               HornetQJMSBridgeLogger.LOGGER.trace("Client acked source session");
             }
          }
 
@@ -1542,7 +1557,7 @@ public final class JMSBridgeImpl implements JMSBridge
             }
             catch (TransactionRolledbackException e)
             {
-               HornetQJMSServerLogger.LOGGER.warn(e.getMessage() + ", retrying TX", e);
+               HornetQJMSBridgeLogger.LOGGER.warn(e.getMessage() + ", retrying TX", e);
                exHappened = true;
             }
          }
@@ -1554,14 +1569,14 @@ public final class JMSBridgeImpl implements JMSBridge
 
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Committing target session");
+               HornetQJMSBridgeLogger.LOGGER.trace("Committing target session");
             }
 
             targetSession.commit();
 
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Committed target session");
+               HornetQJMSBridgeLogger.LOGGER.trace("Committed target session");
             }
          }
 
@@ -1574,30 +1589,36 @@ public final class JMSBridgeImpl implements JMSBridge
 
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Client acking source session");
+               HornetQJMSBridgeLogger.LOGGER.trace("Client acking source session");
             }
 
             messages.getLast().acknowledge();
 
             if (JMSBridgeImpl.trace)
             {
-               HornetQJMSServerLogger.LOGGER.trace("Client acked source session");
+               HornetQJMSBridgeLogger.LOGGER.trace("Client acked source session");
             }
          }
       }
       catch (Exception e)
       {
-         HornetQJMSServerLogger.LOGGER.bridgeAckError(e);
+         if (!stopping)
+         {
+            HornetQJMSBridgeLogger.LOGGER.bridgeAckError(e);
+         }
 
          // We don't call failure otherwise failover would be broken with HornetQ
          // We let the ExceptionListener to deal with failures
 
-         try
-         {
-            sourceSession.recover();
-         }
-         catch (Throwable ignored)
+         if (connectedSource)
          {
+            try
+            {
+               sourceSession.recover();
+            }
+            catch (Throwable ignored)
+            {
+            }
          }
 
       }
@@ -1620,14 +1641,14 @@ public final class JMSBridgeImpl implements JMSBridge
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Committing JTA transaction");
+            HornetQJMSBridgeLogger.LOGGER.trace("Committing JTA transaction");
          }
 
          tx.commit();
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Committed JTA transaction");
+            HornetQJMSBridgeLogger.LOGGER.trace("Committed JTA transaction");
          }
       }
       catch (Exception e)
@@ -1641,7 +1662,7 @@ public final class JMSBridgeImpl implements JMSBridge
          {
          }
 
-         HornetQJMSServerLogger.LOGGER.bridgeAckError(e);
+         HornetQJMSBridgeLogger.LOGGER.bridgeAckError(e);
 
          //we don't do handle failure here because the tx
          //may be rolledback due to failover. All failure handling
@@ -1662,7 +1683,7 @@ public final class JMSBridgeImpl implements JMSBridge
          }
          catch (Exception e)
          {
-            HornetQJMSServerLogger.LOGGER.bridgeAckError(e);
+            HornetQJMSBridgeLogger.LOGGER.bridgeAckError(e);
 
             handleFailureOnSend();
          }
@@ -1677,20 +1698,20 @@ public final class JMSBridgeImpl implements JMSBridge
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Committing source session");
+            HornetQJMSBridgeLogger.LOGGER.trace("Committing source session");
          }
 
          sourceSession.commit();
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Committed source session");
+            HornetQJMSBridgeLogger.LOGGER.trace("Committed source session");
          }
 
       }
       catch (Exception e)
       {
-         HornetQJMSServerLogger.LOGGER.bridgeAckError(e);
+         HornetQJMSBridgeLogger.LOGGER.bridgeAckError(e);
 
          try
          {
@@ -1732,7 +1753,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Sending message " + msg);
+            HornetQJMSBridgeLogger.LOGGER.trace("Sending message " + msg);
          }
 
          // Make sure the correct time to live gets propagated
@@ -1753,7 +1774,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Sent message " + msg);
+            HornetQJMSBridgeLogger.LOGGER.trace("Sent message " + msg);
          }
       }
    }
@@ -1789,7 +1810,7 @@ public final class JMSBridgeImpl implements JMSBridge
       // distributed request/response
       if (JMSBridgeImpl.trace)
       {
-         HornetQJMSServerLogger.LOGGER.trace("Adding old message id in Message header");
+         HornetQJMSBridgeLogger.LOGGER.trace("Adding old message id in Message header");
       }
 
       JMSBridgeImpl.copyProperties(msg);
@@ -1893,6 +1914,10 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          while (started)
          {
+            if (stopping)
+            {
+               return;
+            }
             synchronized (lock)
             {
                if (paused || failed)
@@ -1903,6 +1928,10 @@ public final class JMSBridgeImpl implements JMSBridge
                   }
                   catch (InterruptedException e)
                   {
+                     if (stopping)
+                     {
+                        return;
+                     }
                      throw new HornetQInterruptedException(e);
                   }
                   continue;
@@ -1924,7 +1953,7 @@ public final class JMSBridgeImpl implements JMSBridge
                {
                   if (JMSBridgeImpl.trace)
                   {
-                     HornetQJMSServerLogger.LOGGER.trace(this + " exception while receiving a message", jmse);
+                     HornetQJMSBridgeLogger.LOGGER.trace(this + " exception while receiving a message", jmse);
                   }
                }
 
@@ -1938,7 +1967,11 @@ public final class JMSBridgeImpl implements JMSBridge
                   {
                      if (JMSBridgeImpl.trace)
                      {
-                        HornetQJMSServerLogger.LOGGER.trace(this + " thread was interrupted");
+                        HornetQJMSBridgeLogger.LOGGER.trace(this + " thread was interrupted");
+                     }
+                     if (stopping)
+                     {
+                        return;
                      }
                      throw new HornetQInterruptedException(e);
                   }
@@ -1947,7 +1980,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace(this + " received message " + msg);
+                  HornetQJMSBridgeLogger.LOGGER.trace(this + " received message " + msg);
                }
 
                messages.add(msg);
@@ -1956,21 +1989,21 @@ public final class JMSBridgeImpl implements JMSBridge
 
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace(this + " rescheduled batchExpiryTime to " + batchExpiryTime);
+                  HornetQJMSBridgeLogger.LOGGER.trace(this + " rescheduled batchExpiryTime to " + batchExpiryTime);
                }
 
                if (maxBatchSize != -1 && messages.size() >= maxBatchSize)
                {
                   if (JMSBridgeImpl.trace)
                   {
-                     HornetQJMSServerLogger.LOGGER.trace(this + " maxBatchSize has been reached so sending batch");
+                     HornetQJMSBridgeLogger.LOGGER.trace(this + " maxBatchSize has been reached so sending batch");
                   }
 
                   sendBatch();
 
                   if (JMSBridgeImpl.trace)
                   {
-                     HornetQJMSServerLogger.LOGGER.trace(this + " sent batch");
+                     HornetQJMSBridgeLogger.LOGGER.trace(this + " sent batch");
                   }
                }
             }
@@ -1992,14 +2025,15 @@ public final class JMSBridgeImpl implements JMSBridge
          }
          catch (JMSException e)
          {
-            HornetQJMSServerLogger.LOGGER.jmsBridgeSrcConnectError(e);
+            HornetQJMSBridgeLogger.LOGGER.jmsBridgeSrcConnectError(e);
          }
       }
 
       protected void succeeded()
       {
-         HornetQJMSServerLogger.LOGGER.bridgeReconnected();
-
+         HornetQJMSBridgeLogger.LOGGER.bridgeReconnected();
+         connectedSource = true;
+         connectedTarget = true;
          synchronized (lock)
          {
             failed = false;
@@ -2011,7 +2045,7 @@ public final class JMSBridgeImpl implements JMSBridge
       protected void failed()
       {
          // We haven't managed to recreate connections or maxRetries = 0
-         HornetQJMSServerLogger.LOGGER.errorConnectingBridge();
+         HornetQJMSBridgeLogger.LOGGER.errorConnectingBridge();
 
          try
          {
@@ -2026,7 +2060,7 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace("Failure handler running");
+            HornetQJMSBridgeLogger.LOGGER.trace("Failure handler running");
          }
 
          // Clear the messages
@@ -2038,7 +2072,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
          if (maxRetries > 0 || maxRetries == -1)
          {
-            HornetQJMSServerLogger.LOGGER.bridgeRetry(failureRetryInterval);
+            HornetQJMSBridgeLogger.LOGGER.bridgeRetry(failureRetryInterval);
 
             pause(failureRetryInterval);
 
@@ -2063,17 +2097,20 @@ public final class JMSBridgeImpl implements JMSBridge
       protected void failed()
       {
          // Don't call super
-         HornetQJMSServerLogger.LOGGER.bridgeNotStarted();
+         HornetQJMSBridgeLogger.LOGGER.bridgeNotStarted();
       }
 
       @Override
       protected void succeeded()
       {
          // Don't call super - a bit ugly in this case but better than taking the lock twice.
-         HornetQJMSServerLogger.LOGGER.bridgeConnected();
+         HornetQJMSBridgeLogger.LOGGER.bridgeConnected();
 
          synchronized (lock)
          {
+
+            connectedSource = true;
+            connectedTarget = true;
             failed = false;
             started = true;
 
@@ -2086,7 +2123,7 @@ public final class JMSBridgeImpl implements JMSBridge
             }
             catch (JMSException e)
             {
-               HornetQJMSServerLogger.LOGGER.jmsBridgeSrcConnectError(e);
+               HornetQJMSBridgeLogger.LOGGER.jmsBridgeSrcConnectError(e);
             }
          }
       }
@@ -2098,7 +2135,7 @@ public final class JMSBridgeImpl implements JMSBridge
       {
          if (JMSBridgeImpl.trace)
          {
-            HornetQJMSServerLogger.LOGGER.trace(this + " running");
+            HornetQJMSBridgeLogger.LOGGER.trace(this + " running");
          }
 
          synchronized (lock)
@@ -2111,7 +2148,7 @@ public final class JMSBridgeImpl implements JMSBridge
                {
                   if (JMSBridgeImpl.trace)
                   {
-                     HornetQJMSServerLogger.LOGGER.trace(this + " waited enough");
+                     HornetQJMSBridgeLogger.LOGGER.trace(this + " waited enough");
                   }
 
                   synchronized (lock)
@@ -2120,14 +2157,14 @@ public final class JMSBridgeImpl implements JMSBridge
                      {
                         if (JMSBridgeImpl.trace)
                         {
-                           HornetQJMSServerLogger.LOGGER.trace(this + " got some messages so sending batch");
+                           HornetQJMSBridgeLogger.LOGGER.trace(this + " got some messages so sending batch");
                         }
 
                         sendBatch();
 
                         if (JMSBridgeImpl.trace)
                         {
-                           HornetQJMSServerLogger.LOGGER.trace(this + " sent batch");
+                           HornetQJMSBridgeLogger.LOGGER.trace(this + " sent batch");
                         }
                      }
                   }
@@ -2140,21 +2177,25 @@ public final class JMSBridgeImpl implements JMSBridge
                   {
                      if (JMSBridgeImpl.trace)
                      {
-                        HornetQJMSServerLogger.LOGGER.trace(this + " waiting for " + toWait);
+                        HornetQJMSBridgeLogger.LOGGER.trace(this + " waiting for " + toWait);
                      }
 
                      lock.wait(toWait);
 
                      if (JMSBridgeImpl.trace)
                      {
-                        HornetQJMSServerLogger.LOGGER.trace(this + " woke up");
+                        HornetQJMSBridgeLogger.LOGGER.trace(this + " woke up");
                      }
                   }
                   catch (InterruptedException e)
                   {
                      if (JMSBridgeImpl.trace)
                      {
-                        HornetQJMSServerLogger.LOGGER.trace(this + " thread was interrupted");
+                        HornetQJMSBridgeLogger.LOGGER.trace(this + " thread was interrupted");
+                     }
+                     if (stopping)
+                     {
+                        return;
                      }
                      throw new HornetQInterruptedException(e);
                   }
@@ -2169,25 +2210,43 @@ public final class JMSBridgeImpl implements JMSBridge
    {
       boolean ha;
       BridgeFailoverListener failoverListener;
+      private final boolean isSource;
 
-      public BridgeExceptionListener(boolean ha, BridgeFailoverListener failoverListener)
+      public BridgeExceptionListener(boolean ha, BridgeFailoverListener failoverListener, boolean isSource)
       {
          this.ha = ha;
          this.failoverListener = failoverListener;
+         this.isSource = isSource;
       }
 
       public void onException(final JMSException e)
       {
-         HornetQJMSServerLogger.LOGGER.bridgeFailure(e);
+         if (stopping)
+         {
+            return;
+         }
+         HornetQJMSBridgeLogger.LOGGER.bridgeFailure(e);
+         if (isSource)
+         {
+            connectedSource = false;
+         }
+         else
+         {
+            connectedTarget = false;
+         }
 
          synchronized (lock)
          {
+            if (stopping)
+            {
+               return;
+            }
             if (failed)
             {
                // The failure has already been detected and is being handled
                if (JMSBridgeImpl.trace)
                {
-                  HornetQJMSServerLogger.LOGGER.trace("Failure recovery already in progress");
+                  HornetQJMSBridgeLogger.LOGGER.trace("Failure recovery already in progress");
                }
             }
             else
@@ -2221,7 +2280,7 @@ public final class JMSBridgeImpl implements JMSBridge
             }
             catch (Throwable e)
             {
-               HornetQJMSServerLogger.LOGGER.debug("unable to load  recovery registry " + locatorClasse, e);
+               HornetQJMSBridgeLogger.LOGGER.debug("unable to load  recovery registry " + locatorClasse, e);
             }
             if (registry != null)
             {
@@ -2231,7 +2290,7 @@ public final class JMSBridgeImpl implements JMSBridge
 
          if (registry != null)
          {
-            HornetQJMSServerLogger.LOGGER.debug("Recovery Registry located = " + registry);
+            HornetQJMSBridgeLogger.LOGGER.debug("Recovery Registry located = " + registry);
          }
       }
    }
@@ -2274,14 +2333,31 @@ public final class JMSBridgeImpl implements JMSBridge
 
    private class BridgeFailoverListener implements FailoverEventListener
    {
+      private final boolean isSource;
       volatile FailoverEventType lastEvent;
 
+      public BridgeFailoverListener(boolean isSource)
+      {
+         this.isSource = isSource;
+      }
+
       @Override
       public void failoverEvent(FailoverEventType eventType)
       {
          synchronized (this)
          {
             lastEvent = eventType;
+            if (eventType == FailoverEventType.FAILURE_DETECTED)
+            {
+               if (isSource)
+               {
+                  connectedSource = false;
+               }
+               else
+               {
+                  connectedTarget = false;
+               }
+            }
             this.notify();
          }
       }
@@ -2324,12 +2400,23 @@ public final class JMSBridgeImpl implements JMSBridge
          if (timedOut)
          {
             //timeout, presumably failover failed.
-            HornetQJMSServerLogger.LOGGER.debug("Timed out waiting for failover completion " + this);
+            HornetQJMSBridgeLogger.LOGGER.debug("Timed out waiting for failover completion " + this);
             return false;
          }
 
+         /*
+         * make sure we reset the connected flags
+         * */
          if (result == FailoverEventType.FAILOVER_COMPLETED)
          {
+            if (isSource)
+            {
+               connectedSource = true;
+            }
+            else
+            {
+               connectedTarget = true;
+            }
             return true;
          }
          //failover failed, need retry.

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSQueueControlImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSQueueControlImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSQueueControlImpl.java
index 6d646c9..9c597e2 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSQueueControlImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSQueueControlImpl.java
@@ -362,6 +362,11 @@ public class JMSQueueControlImpl extends StandardMBean implements JMSQueueContro
       return coreQueueControl.getFilter();
    }
 
+   public void flushExecutor()
+   {
+      coreQueueControl.flushExecutor();
+   }
+
    @Override
    public MBeanInfo getMBeanInfo()
    {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSServerControlImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSServerControlImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSServerControlImpl.java
index db3e812..f575b1d 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSServerControlImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSServerControlImpl.java
@@ -21,6 +21,7 @@ import javax.management.NotificationBroadcasterSupport;
 import javax.management.NotificationEmitter;
 import javax.management.NotificationFilter;
 import javax.management.NotificationListener;
+
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -28,7 +29,6 @@ import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicLong;
 
-import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.api.core.management.Parameter;
 import org.hornetq.api.jms.JMSFactoryType;
 import org.hornetq.api.jms.management.ConnectionFactoryControl;
@@ -46,7 +46,9 @@ import org.hornetq.jms.server.HornetQJMSServerLogger;
 import org.hornetq.jms.server.JMSServerManager;
 import org.hornetq.jms.server.config.ConnectionFactoryConfiguration;
 import org.hornetq.jms.server.config.impl.ConnectionFactoryConfigurationImpl;
+import org.hornetq.jms.server.management.JMSNotificationType;
 import org.hornetq.spi.core.protocol.RemotingConnection;
+import org.hornetq.utils.TypedProperties;
 import org.hornetq.utils.json.JSONArray;
 import org.hornetq.utils.json.JSONObject;
 
@@ -54,7 +56,8 @@ import org.hornetq.utils.json.JSONObject;
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  */
-public class JMSServerControlImpl extends AbstractControl implements JMSServerControl, NotificationEmitter
+public class JMSServerControlImpl extends AbstractControl implements JMSServerControl, NotificationEmitter,
+                                                                     org.hornetq.core.server.management.NotificationListener
 {
 
    // Constants -----------------------------------------------------
@@ -129,7 +132,7 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
    public static MBeanNotificationInfo[] getNotificationInfos()
    {
-      NotificationType[] values = NotificationType.values();
+      JMSNotificationType[] values = JMSNotificationType.values();
       String[] names = new String[values.length];
       for (int i = 0; i < values.length; i++)
       {
@@ -147,6 +150,7 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
       super(JMSServerControl.class, server.getHornetQServer().getStorageManager());
       this.server = server;
       broadcaster = new NotificationBroadcasterSupport();
+      server.getHornetQServer().getManagementService().addNotificationListener(this);
    }
 
    // Public --------------------------------------------------------
@@ -196,8 +200,6 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
                                            connectorList,
                                            JMSServerControlImpl.convert(bindings));
          }
-
-         sendNotification(NotificationType.CONNECTION_FACTORY_CREATED, name);
       }
       finally
       {
@@ -322,7 +324,39 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
       try
       {
-         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl(name, ha, bindings);
+         ConnectionFactoryConfiguration configuration = new ConnectionFactoryConfigurationImpl()
+            .setName(name)
+            .setHA(ha)
+            .setBindings(bindings)
+            .setFactoryType(JMSFactoryType.valueOf(cfType))
+            .setClientID(clientID)
+            .setClientFailureCheckPeriod(clientFailureCheckPeriod)
+            .setConnectionTTL(connectionTTL)
+            .setCallTimeout(callTimeout)
+            .setCallFailoverTimeout(callFailoverTimeout)
+            .setMinLargeMessageSize(minLargeMessageSize)
+            .setCompressLargeMessages(compressLargeMessages)
+            .setConsumerWindowSize(consumerWindowSize)
+            .setConsumerMaxRate(consumerMaxRate)
+            .setConfirmationWindowSize(confirmationWindowSize)
+            .setProducerWindowSize(producerWindowSize)
+            .setProducerMaxRate(producerMaxRate)
+            .setBlockOnAcknowledge(blockOnAcknowledge)
+            .setBlockOnDurableSend(blockOnDurableSend)
+            .setBlockOnNonDurableSend(blockOnNonDurableSend)
+            .setAutoGroup(autoGroup)
+            .setPreAcknowledge(preAcknowledge)
+            .setTransactionBatchSize(transactionBatchSize)
+            .setDupsOKBatchSize(dupsOKBatchSize)
+            .setUseGlobalPools(useGlobalPools)
+            .setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize)
+            .setThreadPoolMaxSize(threadPoolMaxSize)
+            .setRetryInterval(retryInterval)
+            .setRetryIntervalMultiplier(retryIntervalMultiplier)
+            .setMaxRetryInterval(maxRetryInterval)
+            .setReconnectAttempts(reconnectAttempts)
+            .setFailoverOnInitialConnection(failoverOnInitialConnection)
+            .setGroupID(groupId);
 
          if (useDiscovery)
          {
@@ -338,46 +372,12 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
             configuration.setConnectorNames(connectorNamesList);
          }
 
-         configuration.setFactoryType(JMSFactoryType.valueOf(cfType));
-         configuration.setClientID(clientID);
-         configuration.setClientFailureCheckPeriod(clientFailureCheckPeriod);
-         configuration.setConnectionTTL(connectionTTL);
-         configuration.setCallTimeout(callTimeout);
-         configuration.setCallFailoverTimeout(callFailoverTimeout);
-         configuration.setMinLargeMessageSize(minLargeMessageSize);
-         configuration.setCompressLargeMessages(compressLargeMessages);
-         configuration.setConsumerWindowSize(consumerWindowSize);
-         configuration.setConsumerMaxRate(consumerMaxRate);
-         configuration.setConfirmationWindowSize(confirmationWindowSize);
-         configuration.setProducerWindowSize(producerWindowSize);
-         configuration.setProducerMaxRate(producerMaxRate);
-         configuration.setBlockOnAcknowledge(blockOnAcknowledge);
-         configuration.setBlockOnDurableSend(blockOnDurableSend);
-         configuration.setBlockOnNonDurableSend(blockOnNonDurableSend);
-         configuration.setAutoGroup(autoGroup);
-         configuration.setPreAcknowledge(preAcknowledge);
-
-         if (loadBalancingPolicyClassName == null || loadBalancingPolicyClassName.trim().equals(""))
+         if (loadBalancingPolicyClassName != null && !loadBalancingPolicyClassName.trim().equals(""))
          {
-            loadBalancingPolicyClassName = HornetQClient.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
+            configuration.setLoadBalancingPolicyClassName(loadBalancingPolicyClassName);
          }
 
-         configuration.setLoadBalancingPolicyClassName(loadBalancingPolicyClassName);
-         configuration.setTransactionBatchSize(transactionBatchSize);
-         configuration.setDupsOKBatchSize(dupsOKBatchSize);
-         configuration.setUseGlobalPools(useGlobalPools);
-         configuration.setScheduledThreadPoolMaxSize(scheduledThreadPoolMaxSize);
-         configuration.setThreadPoolMaxSize(threadPoolMaxSize);
-         configuration.setRetryInterval(retryInterval);
-         configuration.setRetryIntervalMultiplier(retryIntervalMultiplier);
-         configuration.setMaxRetryInterval(maxRetryInterval);
-         configuration.setReconnectAttempts(reconnectAttempts);
-         configuration.setFailoverOnInitialConnection(failoverOnInitialConnection);
-         configuration.setGroupID(groupId);
-
          server.createConnectionFactory(true, configuration, bindings);
-
-         sendNotification(NotificationType.CONNECTION_FACTORY_CREATED, name);
       }
       finally
       {
@@ -427,12 +427,8 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
       try
       {
-         boolean created = server.createQueue(true, name, selector, durable, JMSServerControlImpl.toArray(jndiBindings));
-         if (created)
-         {
-            sendNotification(NotificationType.QUEUE_CREATED, name);
-         }
-         return created;
+         return server.createQueue(true, name, selector, durable,
+               JMSServerControlImpl.toArray(jndiBindings));
       }
       finally
       {
@@ -453,12 +449,7 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
       try
       {
-         boolean destroyed = server.destroyQueue(name, removeConsumers);
-         if (destroyed)
-         {
-            sendNotification(NotificationType.QUEUE_DESTROYED, name);
-         }
-         return destroyed;
+         return server.destroyQueue(name, removeConsumers);
       }
       finally
       {
@@ -479,12 +470,7 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
       try
       {
-         boolean created = server.createTopic(true, topicName, JMSServerControlImpl.toArray(jndiBindings));
-         if (created)
-         {
-            sendNotification(NotificationType.TOPIC_CREATED, topicName);
-         }
-         return created;
+         return server.createTopic(true, topicName, JMSServerControlImpl.toArray(jndiBindings));
       }
       finally
       {
@@ -506,12 +492,7 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
       try
       {
-         boolean destroyed = server.destroyTopic(name, removeConsumers);
-         if (destroyed)
-         {
-            sendNotification(NotificationType.TOPIC_DESTROYED, name);
-         }
-         return destroyed;
+         return server.destroyTopic(name, removeConsumers);
       }
       finally
       {
@@ -527,11 +508,7 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
       try
       {
-         boolean destroyed = server.destroyConnectionFactory(name);
-         if (destroyed)
-         {
-            sendNotification(NotificationType.CONNECTION_FACTORY_DESTROYED, name);
-         }
+         server.destroyConnectionFactory(name);
       }
       finally
       {
@@ -696,6 +673,38 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
       }
    }
 
+   public boolean closeConsumerConnectionsForAddress(final String address) throws Exception
+   {
+      checkStarted();
+
+      clearIO();
+
+      try
+      {
+         return server.closeConsumerConnectionsForAddress(address);
+      }
+      finally
+      {
+         blockOnIO();
+      }
+   }
+
+   public boolean closeConnectionsForUser(final String userName) throws Exception
+   {
+      checkStarted();
+
+      clearIO();
+
+      try
+      {
+         return server.closeConnectionsForUser(userName);
+      }
+      finally
+      {
+         blockOnIO();
+      }
+   }
+
    public String[] listConnectionIDs() throws Exception
    {
       checkStarted();
@@ -889,12 +898,6 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
    // Private -------------------------------------------------------
 
-   private void sendNotification(final NotificationType type, final String message)
-   {
-      Notification notif = new Notification(type.toString(), this, notifSeq.incrementAndGet(), message);
-      broadcaster.sendNotification(notif);
-   }
-
    private void checkStarted()
    {
       if (!server.isStarted())
@@ -905,16 +908,6 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
    // Inner classes -------------------------------------------------
 
-   public static enum NotificationType
-   {
-      QUEUE_CREATED,
-      QUEUE_DESTROYED,
-      TOPIC_CREATED,
-      TOPIC_DESTROYED,
-      CONNECTION_FACTORY_CREATED,
-      CONNECTION_FACTORY_DESTROYED;
-   }
-
    public String[] listTargetDestinations(String sessionID) throws Exception
    {
       String[] addresses = server.getHornetQServer().getHornetQServerControl().listTargetAddresses(sessionID);
@@ -1041,4 +1034,16 @@ public class JMSServerControlImpl extends AbstractControl implements JMSServerCo
 
       return obj;
    }
+
+   @Override
+   public void onNotification(org.hornetq.core.server.management.Notification notification)
+   {
+      if (!(notification.getType() instanceof JMSNotificationType)) return;
+      JMSNotificationType type = (JMSNotificationType) notification.getType();
+      TypedProperties prop = notification.getProperties();
+
+      this.broadcaster.sendNotification(new Notification(type.toString(), this,
+            notifSeq.incrementAndGet(), prop.getSimpleStringProperty(JMSNotificationType.MESSAGE).toString()));
+   }
+
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSTopicControlImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSTopicControlImpl.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSTopicControlImpl.java
index bdeceeb..f38ba8a 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSTopicControlImpl.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/management/impl/JMSTopicControlImpl.java
@@ -315,13 +315,21 @@ public class JMSTopicControlImpl extends StandardMBean implements TopicControl
             String clientID = null;
             String subName = null;
 
-            if (queue.isDurable())
+            if (queue.isDurable() && !queue.getName().startsWith(ResourceNames.JMS_TOPIC))
             {
                Pair<String, String> pair = HornetQDestination.decomposeQueueNameForDurableSubscription(queue.getName()
                                                                                                             .toString());
                clientID = pair.getA();
                subName = pair.getB();
             }
+            else if (queue.getName().startsWith(ResourceNames.JMS_TOPIC))
+            {
+               // in the case of heirarchical topics the queue name will not follow the <part>.<part> pattern of normal
+               // durable subscribers so skip decomposing the name for the client ID and subscription name and just
+               // hard-code it
+               clientID = "HornetQ";
+               subName = "HornetQ";
+            }
 
             String filter = queue.getFilter() != null ? queue.getFilter() : null;
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/HornetQJMSServerLogger.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/HornetQJMSServerLogger.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/HornetQJMSServerLogger.java
index e5c79f3..49536e2 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/HornetQJMSServerLogger.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/HornetQJMSServerLogger.java
@@ -12,8 +12,6 @@
  */
 package org.hornetq.jms.server;
 
-import javax.management.ObjectName;
-
 import org.hornetq.api.core.client.ClientSessionFactory;
 import org.hornetq.jms.server.recovery.XARecoveryConfig;
 import org.jboss.logging.BasicLogger;
@@ -26,7 +24,7 @@ import org.w3c.dom.Node;
 
 /**
  * @author <a href="mailto:andy.taylor@jboss.org">Andy Taylor</a>
- *         3/15/12
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  *
  * Logger Code 12
  *
@@ -50,19 +48,6 @@ public interface HornetQJMSServerLogger extends BasicLogger
    HornetQJMSServerLogger LOGGER = Logger.getMessageLogger(HornetQJMSServerLogger.class, HornetQJMSServerLogger.class.getPackage().getName());
 
    @LogMessage(level = Logger.Level.INFO)
-   @Message(id = 121000, value = "Failed to set up JMS bridge connections. Most probably the source or target servers are unavailable." +
-         " Will retry after a pause of {0} ms", format = Message.Format.MESSAGE_FORMAT)
-   void failedToSetUpBridge(long failureRetryInterval);
-
-   @LogMessage(level = Logger.Level.INFO)
-   @Message(id = 121001, value = "JMS Bridge Succeeded in reconnecting to servers" , format = Message.Format.MESSAGE_FORMAT)
-   void bridgeReconnected();
-
-   @LogMessage(level = Logger.Level.INFO)
-   @Message(id = 121002, value = "Succeeded in connecting to servers" , format = Message.Format.MESSAGE_FORMAT)
-   void bridgeConnected();
-
-   @LogMessage(level = Logger.Level.INFO)
    @Message(id = 121003, value = "JMS Server Manager Running cached command for {0}" , format = Message.Format.MESSAGE_FORMAT)
    void serverRunningCachedCommand(Runnable run);
 
@@ -77,34 +62,6 @@ public interface HornetQJMSServerLogger extends BasicLogger
    void invalidHostForConnector(String name, String newHost);
 
    @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122000, value = "Attempt to start JMS Bridge, but is already started" , format = Message.Format.MESSAGE_FORMAT)
-   void errorBridgeAlreadyStarted();
-
-   @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122001, value = "Failed to start JMS Bridge" , format = Message.Format.MESSAGE_FORMAT)
-   void errorStartingBridge();
-
-   @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122002, value = "Failed to unregisted JMS Bridge {0}" , format = Message.Format.MESSAGE_FORMAT)
-   void errorUnregisteringBridge(ObjectName objectName);
-
-   @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122003, value = "JMS Bridge unable to set up connections, bridge will be stopped" , format = Message.Format.MESSAGE_FORMAT)
-   void errorConnectingBridge();
-
-   @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122004, value = "JMS Bridge Will retry after a pause of {0} ms" , format = Message.Format.MESSAGE_FORMAT)
-   void bridgeRetry(long failureRetryInterval);
-
-   @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122005, value = "JMS Bridge unable to set up connections, bridge will not be started" , format = Message.Format.MESSAGE_FORMAT)
-   void bridgeNotStarted();
-
-   @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122006, value = "Detected failure on bridge connection" , format = Message.Format.MESSAGE_FORMAT)
-   void bridgeFailure(@Cause Exception e);
-
-   @LogMessage(level = Logger.Level.WARN)
    @Message(id = 122007, value = "Queue {0} does not exist on the topic {1}. It was deleted manually probably." , format = Message.Format.MESSAGE_FORMAT)
    void noQueueOnTopic(String queueName, String name);
 
@@ -113,14 +70,6 @@ public interface HornetQJMSServerLogger extends BasicLogger
    void recoveryConnectFailed(String s);
 
    @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122009, value = "JMS Bridge failed to send + acknowledge batch, closing JMS objects"  , format = Message.Format.MESSAGE_FORMAT)
-   void bridgeAckError(@Cause Exception e);
-
-   @LogMessage(level = Logger.Level.WARN)
-   @Message(id = 122010, value = "Failed to connect JMS Bridge", format = Message.Format.MESSAGE_FORMAT)
-   void bridgeConnectError(@Cause Exception e);
-
-   @LogMessage(level = Logger.Level.WARN)
    @Message(id = 122011, value = "error unbinding {0} from JNDI" , format = Message.Format.MESSAGE_FORMAT)
    void jndiUnbindError(@Cause Exception e, String key);
 
@@ -161,10 +110,6 @@ public interface HornetQJMSServerLogger extends BasicLogger
    void jmsConfigMissingKey(Node e);
 
    @LogMessage(level = Logger.Level.ERROR)
-   @Message(id = 124001, value = "Failed to start source connection" , format = Message.Format.MESSAGE_FORMAT)
-   void jmsBridgeSrcConnectError(@Cause Exception e);
-
-   @LogMessage(level = Logger.Level.ERROR)
    @Message(id = 124002, value = "Failed to start JMS deployer" , format = Message.Format.MESSAGE_FORMAT)
    void jmsDeployerStartError(@Cause Exception e);
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-jms-server/src/main/java/org/hornetq/jms/server/JMSServerManager.java
----------------------------------------------------------------------
diff --git a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/JMSServerManager.java b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/JMSServerManager.java
index 35ef0a9..f593077 100644
--- a/hornetq-jms-server/src/main/java/org/hornetq/jms/server/JMSServerManager.java
+++ b/hornetq-jms-server/src/main/java/org/hornetq/jms/server/JMSServerManager.java
@@ -284,6 +284,10 @@ public interface JMSServerManager extends HornetQComponent
 
    boolean closeConnectionsForAddress(String ipAddress) throws Exception;
 
+   boolean closeConsumerConnectionsForAddress(String address) throws Exception;
+
+   boolean closeConnectionsForUser(String address) throws Exception;
+
    String[] listConnectionIDs() throws Exception;
 
    String[] listSessions(String connectionID) throws Exception;


[41/51] [partial] activemq-6 git commit: ACTIVEMQ6-2 Update to HQ master

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManager.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManager.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManager.java
index d5bfc7e..b2bad9a 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManager.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManager.java
@@ -18,6 +18,8 @@ import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Lock;
 
+import io.netty.channel.ChannelPipeline;
+import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQException;
 import org.hornetq.api.core.HornetQExceptionType;
 import org.hornetq.api.core.HornetQInterruptedException;
@@ -25,6 +27,8 @@ import org.hornetq.api.core.Interceptor;
 import org.hornetq.api.core.Pair;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.api.core.TransportConfiguration;
+import org.hornetq.api.core.client.ClientSessionFactory;
+import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
@@ -44,11 +48,12 @@ import org.hornetq.core.protocol.core.impl.wireformat.DisconnectMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.DisconnectMessage_V2;
 import org.hornetq.core.protocol.core.impl.wireformat.Ping;
 import org.hornetq.core.protocol.core.impl.wireformat.SubscribeClusterTopologyUpdatesMessageV2;
+import org.hornetq.core.remoting.impl.netty.HornetQFrameDecoder2;
 import org.hornetq.core.version.Version;
 import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.spi.core.remoting.ClientProtocolManager;
 import org.hornetq.spi.core.remoting.Connection;
-import org.hornetq.spi.core.remoting.ProtocolResponseHandler;
+import org.hornetq.spi.core.remoting.TopologyResponseHandler;
 import org.hornetq.spi.core.remoting.SessionContext;
 import org.hornetq.utils.VersionLoader;
 
@@ -70,7 +75,7 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
 {
    private final int versionID = VersionLoader.getVersion().getIncrementingVersion();
 
-   private final ClientSessionFactoryInternal factoryInternal;
+   private ClientSessionFactoryInternal factoryInternal;
 
    /**
     * Guards assignments to {@link #inCreateSession} and {@link #inCreateSessionLatch}
@@ -87,12 +92,9 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
     */
    private CountDownLatch inCreateSessionLatch;
 
-
-   protected PacketDecoder packetDecoder = ClientPacketDecoder.INSTANCE;
-
    protected volatile RemotingConnectionImpl connection;
 
-   protected ProtocolResponseHandler callbackHandler;
+   protected TopologyResponseHandler topologyResponseHandler;
 
    /**
     * Flag that signals that the communication is closing. Causes many processes to exit.
@@ -102,15 +104,29 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
    private final CountDownLatch waitLatch = new CountDownLatch(1);
 
 
-   public HornetQClientProtocolManager(ClientSessionFactoryInternal factory)
+   public HornetQClientProtocolManager()
    {
-      this.factoryInternal = factory;
    }
 
+   public String getName()
+   {
+      return HornetQClient.DEFAULT_CORE_PROTOCOL;
+   }
+
+   public void setSessionFactory(ClientSessionFactory factory)
+   {
+      this.factoryInternal = (ClientSessionFactoryInternal)factory;
+   }
 
-   public void replacePacketDecoder(PacketDecoder decoder)
+   public ClientSessionFactory getSessionFactory()
    {
-      this.packetDecoder = decoder;
+      return this.factoryInternal;
+   }
+
+   @Override
+   public void addChannelHandlers(ChannelPipeline pipeline)
+   {
+      pipeline.addLast("hornetq-decoder", new HornetQFrameDecoder2());
    }
 
    public boolean waitOnLatch(long milliseconds) throws InterruptedException
@@ -193,7 +209,6 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
          if (inCreateSessionLatch != null)
             inCreateSessionLatch.countDown();
       }
-      forceReturnChannel1();
 
 
       Channel channel1 = getChannel1();
@@ -212,16 +227,6 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
    }
 
 
-   public void setConnection(RemotingConnection connection)
-   {
-      this.connection = (RemotingConnectionImpl) connection;
-   }
-
-   @Override
-   public void shakeHands()
-   {
-   }
-
    @Override
    public void ping(long connectionTTL)
    {
@@ -234,14 +239,6 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
       connection.flush();
    }
 
-   public void setResponseHandler(ProtocolResponseHandler handler)
-   {
-      this.callbackHandler = handler;
-
-      getChannel0().setHandler(new Channel0Handler(connection));
-   }
-
-
    @Override
    public void sendSubscribeTopology(final boolean isServer)
    {
@@ -395,7 +392,7 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
 
    }
 
-   public boolean cleanupBeforeFailover()
+   public boolean cleanupBeforeFailover(HornetQException cause)
    {
 
       boolean needToInterrupt;
@@ -423,7 +420,7 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
 
       if (needToInterrupt)
       {
-         forceReturnChannel1();
+         forceReturnChannel1(cause);
 
          // Now we need to make sure that the thread has actually exited and returned it's
          // connections
@@ -460,15 +457,32 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
 
    public RemotingConnection connect(Connection transportConnection, long callTimeout, long callFailoverTimeout,
                                      List<Interceptor> incomingInterceptors, List<Interceptor> outgoingInterceptors,
-                                     ProtocolResponseHandler protocolResponseHandler)
+                                     TopologyResponseHandler topologyResponseHandler)
    {
-      RemotingConnectionImpl remotingConnection = new RemotingConnectionImpl(packetDecoder, transportConnection,
+      this.connection = new RemotingConnectionImpl(getPacketDecoder(), transportConnection,
                                                                              callTimeout, callFailoverTimeout,
                                                                              incomingInterceptors, outgoingInterceptors);
-      setConnection(remotingConnection);
-      this.setResponseHandler(protocolResponseHandler);
 
-      return remotingConnection;
+      this.topologyResponseHandler = topologyResponseHandler;
+
+      getChannel0().setHandler(new Channel0Handler(connection));
+
+
+      sendHandshake(transportConnection);
+
+      return connection;
+   }
+
+   private void sendHandshake(Connection transportConnection)
+   {
+      if (transportConnection.isUsingProtocolHandling())
+      {
+         // no need to send handshake on inVM as inVM is not using the NettyProtocolHandling
+         String handshake = "HORNETQ";
+         HornetQBuffer hqbuffer = connection.createBuffer(handshake.length());
+         hqbuffer.writeBytes(handshake.getBytes());
+         transportConnection.write(hqbuffer);
+      }
    }
 
 
@@ -498,8 +512,18 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
                scaleDownTargetNodeID = msg_v2.getScaleDownNodeID() == null ? null : msg_v2.getScaleDownNodeID().toString();
             }
 
-            if (callbackHandler != null)
-               callbackHandler.nodeDisconnected(conn, nodeID == null ? null : nodeID.toString(), scaleDownTargetNodeID);
+            if (topologyResponseHandler != null)
+               topologyResponseHandler.nodeDisconnected(conn, nodeID == null ? null : nodeID.toString(), scaleDownTargetNodeID);
+         }
+         else if (type == PacketImpl.CLUSTER_TOPOLOGY)
+         {
+            ClusterTopologyChangeMessage topMessage = (ClusterTopologyChangeMessage) packet;
+            notifyTopologyChange(topMessage);
+         }
+         else if (type == PacketImpl.CLUSTER_TOPOLOGY_V2)
+         {
+            ClusterTopologyChangeMessage_V2 topMessage = (ClusterTopologyChangeMessage_V2) packet;
+            notifyTopologyChange(topMessage);
          }
          else if (type == PacketImpl.CLUSTER_TOPOLOGY || type == PacketImpl.CLUSTER_TOPOLOGY_V2 || type == PacketImpl.CLUSTER_TOPOLOGY_V3)
          {
@@ -546,8 +570,10 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
                HornetQClientLogger.LOGGER.debug("Notifying " + topMessage.getNodeID() + " going down");
             }
 
-            if (callbackHandler != null)
-               callbackHandler.notifyNodeDown(eventUID, topMessage.getNodeID());
+            if (topologyResponseHandler != null)
+            {
+               topologyResponseHandler.notifyNodeDown(eventUID, topMessage.getNodeID());
+            }
          }
          else
          {
@@ -559,13 +585,20 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
                                             null);
             }
 
-            if (callbackHandler != null)
-               callbackHandler.notifyNodeUp(eventUID, topMessage.getNodeID(), backupGroupName, scaleDownGroupName, transportConfig, topMessage.isLast());
+            if (topologyResponseHandler != null)
+            {
+               topologyResponseHandler.notifyNodeUp(eventUID, topMessage.getNodeID(), backupGroupName, scaleDownGroupName, transportConfig, topMessage.isLast());
+            }
          }
       }
    }
 
-   private void forceReturnChannel1()
+   protected PacketDecoder getPacketDecoder()
+   {
+      return ClientPacketDecoder.INSTANCE;
+   }
+
+   private void forceReturnChannel1(HornetQException cause)
    {
       if (connection != null)
       {
@@ -573,7 +606,7 @@ public class HornetQClientProtocolManager implements ClientProtocolManager
 
          if (channel1 != null)
          {
-            channel1.returnBlocking();
+            channel1.returnBlocking(cause);
          }
       }
    }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManagerFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManagerFactory.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManagerFactory.java
index d6b7f08..0a066f2 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManagerFactory.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQClientProtocolManagerFactory.java
@@ -13,7 +13,6 @@
 
 package org.hornetq.core.protocol.core.impl;
 
-import org.hornetq.core.client.impl.ClientSessionFactoryInternal;
 import org.hornetq.spi.core.remoting.ClientProtocolManager;
 import org.hornetq.spi.core.remoting.ClientProtocolManagerFactory;
 
@@ -23,8 +22,21 @@ import org.hornetq.spi.core.remoting.ClientProtocolManagerFactory;
 
 public class HornetQClientProtocolManagerFactory implements ClientProtocolManagerFactory
 {
-   public ClientProtocolManager newProtocolManager(ClientSessionFactoryInternal factoryInternal)
+   private static final long serialVersionUID = 1;
+
+   private static final HornetQClientProtocolManagerFactory INSTANCE = new HornetQClientProtocolManagerFactory();
+
+   private HornetQClientProtocolManagerFactory()
+   {
+   }
+
+   public static final HornetQClientProtocolManagerFactory getInstance()
+   {
+      return INSTANCE;
+   }
+
+   public ClientProtocolManager newProtocolManager()
    {
-      return new HornetQClientProtocolManager(factoryInternal);
+      return new HornetQClientProtocolManager();
    }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQConsumerContext.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQConsumerContext.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQConsumerContext.java
new file mode 100644
index 0000000..b63f372
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQConsumerContext.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.protocol.core.impl;
+
+import org.hornetq.spi.core.remoting.ConsumerContext;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class HornetQConsumerContext extends ConsumerContext
+{
+   private long id;
+
+   public HornetQConsumerContext(long id)
+   {
+      this.id = id;
+   }
+
+   public long getId()
+   {
+      return id;
+   }
+
+   @Override
+   public boolean equals(Object o)
+   {
+      if (this == o) return true;
+      if (o == null || getClass() != o.getClass()) return false;
+
+      HornetQConsumerContext that = (HornetQConsumerContext) o;
+
+      if (id != that.id) return false;
+
+      return true;
+   }
+
+   @Override
+   public int hashCode()
+   {
+      return (int) (id ^ (id >>> 32));
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQSessionContext.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQSessionContext.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQSessionContext.java
index 96a8181..311e937 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQSessionContext.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/HornetQSessionContext.java
@@ -38,6 +38,7 @@ import org.hornetq.core.client.impl.ClientConsumerImpl;
 import org.hornetq.core.client.impl.ClientConsumerInternal;
 import org.hornetq.core.client.impl.ClientLargeMessageInternal;
 import org.hornetq.core.client.impl.ClientMessageInternal;
+import org.hornetq.core.client.impl.ClientProducerCreditsImpl;
 import org.hornetq.core.client.impl.ClientSessionImpl;
 import org.hornetq.core.message.impl.MessageInternal;
 import org.hornetq.core.protocol.core.Channel;
@@ -111,12 +112,14 @@ public class HornetQSessionContext extends SessionContext
    private final Channel sessionChannel;
    private final int serverVersion;
    private int confirmationWindow;
+   private final String name;
 
 
    public HornetQSessionContext(String name, RemotingConnection remotingConnection, Channel sessionChannel, int serverVersion, int confirmationWindow)
    {
-      super(name, remotingConnection);
+      super(remotingConnection);
 
+      this.name = name;
       this.sessionChannel = sessionChannel;
       this.serverVersion = serverVersion;
       this.confirmationWindow = confirmationWindow;
@@ -169,9 +172,9 @@ public class HornetQSessionContext extends SessionContext
    // Failover utility methods
 
    @Override
-   public void returnBlocking()
+   public void returnBlocking(HornetQException cause)
    {
-      sessionChannel.returnBlocking();
+      sessionChannel.returnBlocking(cause);
    }
 
    @Override
@@ -196,6 +199,12 @@ public class HornetQSessionContext extends SessionContext
       sessionChannel.returnBlocking();
    }
 
+   @Override
+   public void linkFlowControl(SimpleString address, ClientProducerCreditsImpl clientProducerCredits)
+   {
+      // nothing to be done here... Flow control here is done on the core side
+   }
+
 
    public void setSendAcknowledgementHandler(final SendAcknowledgementHandler handler)
    {
@@ -232,6 +241,8 @@ public class HornetQSessionContext extends SessionContext
    {
       long consumerID = idGenerator.generateID();
 
+      HornetQConsumerContext consumerContext = new HornetQConsumerContext(consumerID);
+
       SessionCreateConsumerMessage request = new SessionCreateConsumerMessage(consumerID,
                                                                               queueName,
                                                                               filterString,
@@ -245,7 +256,7 @@ public class HornetQSessionContext extends SessionContext
       // The value we send is just a hint
 
       return new ClientConsumerImpl(session,
-                                    consumerID,
+                                    consumerContext,
                                     queueName,
                                     filterString,
                                     browseOnly,
@@ -279,17 +290,17 @@ public class HornetQSessionContext extends SessionContext
    @Override
    public void closeConsumer(final ClientConsumer consumer) throws HornetQException
    {
-      sessionChannel.sendBlocking(new SessionConsumerCloseMessage((long) consumer.getId()), PacketImpl.NULL_RESPONSE);
+      sessionChannel.sendBlocking(new SessionConsumerCloseMessage(getConsumerID(consumer)), PacketImpl.NULL_RESPONSE);
    }
 
    public void sendConsumerCredits(final ClientConsumer consumer, final int credits)
    {
-      sessionChannel.send(new SessionConsumerFlowCreditMessage((long) consumer.getId(), credits));
+      sessionChannel.send(new SessionConsumerFlowCreditMessage(getConsumerID(consumer), credits));
    }
 
    public void forceDelivery(final ClientConsumer consumer, final long sequence) throws HornetQException
    {
-      SessionForceConsumerDelivery request = new SessionForceConsumerDelivery((long) consumer.getId(), sequence);
+      SessionForceConsumerDelivery request = new SessionForceConsumerDelivery(getConsumerID(consumer), sequence);
       sessionChannel.send(request);
    }
 
@@ -390,7 +401,7 @@ public class HornetQSessionContext extends SessionContext
       return msgI.getEncodeSize();
    }
 
-   public void sendFullMessage(MessageInternal msgI, boolean sendBlocking, SendAcknowledgementHandler handler) throws HornetQException
+   public void sendFullMessage(MessageInternal msgI, boolean sendBlocking, SendAcknowledgementHandler handler, SimpleString defaultAddress) throws HornetQException
    {
       SessionSendMessage packet = new SessionSendMessage(msgI, sendBlocking, handler);
 
@@ -440,11 +451,11 @@ public class HornetQSessionContext extends SessionContext
       PacketImpl messagePacket;
       if (individual)
       {
-         messagePacket = new SessionIndividualAcknowledgeMessage((long) consumer.getId(), message.getMessageID(), block);
+         messagePacket = new SessionIndividualAcknowledgeMessage(getConsumerID(consumer), message.getMessageID(), block);
       }
       else
       {
-         messagePacket = new SessionAcknowledgeMessage((long) consumer.getId(), message.getMessageID(), block);
+         messagePacket = new SessionAcknowledgeMessage(getConsumerID(consumer), message.getMessageID(), block);
       }
 
       if (block)
@@ -459,7 +470,7 @@ public class HornetQSessionContext extends SessionContext
 
    public void expireMessage(final ClientConsumer consumer, Message message) throws HornetQException
    {
-      SessionExpireMessage messagePacket = new SessionExpireMessage((long) consumer.getId(), message.getMessageID());
+      SessionExpireMessage messagePacket = new SessionExpireMessage(getConsumerID(consumer), message.getMessageID());
 
       sessionChannel.send(messagePacket);
    }
@@ -682,7 +693,7 @@ public class HornetQSessionContext extends SessionContext
          sendPacketWithoutLock(sessionChannel, createQueueRequest);
       }
 
-      SessionCreateConsumerMessage createConsumerRequest = new SessionCreateConsumerMessage(consumerInternal.getID(),
+      SessionCreateConsumerMessage createConsumerRequest = new SessionCreateConsumerMessage(getConsumerID(consumerInternal),
                                                                                             consumerInternal.getQueueName(),
                                                                                             consumerInternal.getFilterString(),
                                                                                             consumerInternal.isBrowseOnly(),
@@ -694,7 +705,7 @@ public class HornetQSessionContext extends SessionContext
 
       if (clientWindowSize != 0)
       {
-         SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage((long) consumerInternal.getId(),
+         SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal),
                                                                                         clientWindowSize);
 
          sendPacketWithoutLock(sessionChannel, packet);
@@ -702,7 +713,7 @@ public class HornetQSessionContext extends SessionContext
       else
       {
          // https://jira.jboss.org/browse/HORNETQ-522
-         SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage((long) consumerInternal.getId(),
+         SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal),
                                                                                         1);
          sendPacketWithoutLock(sessionChannel, packet);
       }
@@ -748,7 +759,8 @@ public class HornetQSessionContext extends SessionContext
    private void handleConsumerDisconnected(DisconnectConsumerMessage packet) throws HornetQException
    {
       DisconnectConsumerMessage message = packet;
-      session.handleConsumerDisconnect(message.getConsumerId());
+
+      session.handleConsumerDisconnect(new HornetQConsumerContext(message.getConsumerId()));
    }
 
    private void handleReceivedMessagePacket(SessionReceiveMessage messagePacket) throws Exception
@@ -759,7 +771,7 @@ public class HornetQSessionContext extends SessionContext
 
       msgi.setFlowControlSize(messagePacket.getPacketSize());
 
-      handleReceiveMessage(messagePacket.getConsumerID(), msgi);
+      handleReceiveMessage(new HornetQConsumerContext(messagePacket.getConsumerID()), msgi);
    }
 
    private void handleReceiveLargeMessage(SessionReceiveLargeMessage serverPacket) throws Exception
@@ -770,13 +782,13 @@ public class HornetQSessionContext extends SessionContext
 
       clientLargeMessage.setDeliveryCount(serverPacket.getDeliveryCount());
 
-      handleReceiveLargeMessage(serverPacket.getConsumerID(), clientLargeMessage, serverPacket.getLargeMessageSize());
+      handleReceiveLargeMessage(new HornetQConsumerContext(serverPacket.getConsumerID()), clientLargeMessage, serverPacket.getLargeMessageSize());
    }
 
 
    private void handleReceiveContinuation(SessionReceiveContinuationMessage continuationPacket) throws Exception
    {
-      handleReceiveContinuation(continuationPacket.getConsumerID(), continuationPacket.getBody(), continuationPacket.getPacketSize(),
+      handleReceiveContinuation(new HornetQConsumerContext(continuationPacket.getConsumerID()), continuationPacket.getBody(), continuationPacket.getPacketSize(),
                                 continuationPacket.isContinues());
    }
 
@@ -863,6 +875,11 @@ public class HornetQSessionContext extends SessionContext
       }
    }
 
+   private long getConsumerID(ClientConsumer consumer)
+   {
+      return ((HornetQConsumerContext)consumer.getConsumerContext()).getId();
+   }
+
    private ClassLoader lookupTCCL()
    {
       return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/RemotingConnectionImpl.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/RemotingConnectionImpl.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/RemotingConnectionImpl.java
index 0f161df..3afd32e 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/RemotingConnectionImpl.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/RemotingConnectionImpl.java
@@ -12,31 +12,26 @@
  */
 package org.hornetq.core.protocol.core.impl;
 
-import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.Executor;
 
 import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQException;
-import org.hornetq.api.core.HornetQInterruptedException;
 import org.hornetq.api.core.Interceptor;
 import org.hornetq.api.core.SimpleString;
 import org.hornetq.core.client.HornetQClientLogger;
-import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.protocol.core.Channel;
 import org.hornetq.core.protocol.core.CoreRemotingConnection;
 import org.hornetq.core.protocol.core.Packet;
 import org.hornetq.core.protocol.core.impl.ChannelImpl.CHANNEL_ID;
 import org.hornetq.core.protocol.core.impl.wireformat.DisconnectMessage;
 import org.hornetq.core.protocol.core.impl.wireformat.DisconnectMessage_V2;
-import org.hornetq.core.remoting.CloseListener;
-import org.hornetq.core.remoting.FailureListener;
 import org.hornetq.core.security.HornetQPrincipal;
+import org.hornetq.spi.core.protocol.AbstractRemotingConnection;
 import org.hornetq.spi.core.remoting.Connection;
 import org.hornetq.utils.SimpleIDGenerator;
 
@@ -44,7 +39,7 @@ import org.hornetq.utils.SimpleIDGenerator;
  * @author <a href="tim.fox@jboss.com">Tim Fox</a>
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
  */
-public class RemotingConnectionImpl implements CoreRemotingConnection
+public class RemotingConnectionImpl extends AbstractRemotingConnection implements CoreRemotingConnection
 {
    // Constants
    // ------------------------------------------------------------------------------------
@@ -58,14 +53,8 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
    // -----------------------------------------------------------------------------------
    private final PacketDecoder packetDecoder;
 
-   private final Connection transportConnection;
-
    private final Map<Long, Channel> channels = new ConcurrentHashMap<Long, Channel>();
 
-   private final List<FailureListener> failureListeners = new CopyOnWriteArrayList<FailureListener>();
-
-   private final List<CloseListener> closeListeners = new CopyOnWriteArrayList<CloseListener>();
-
    private final long blockingCallTimeout;
 
    private final long blockingCallFailoverTimeout;
@@ -88,16 +77,10 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
 
    private final Object failLock = new Object();
 
-   private volatile boolean dataReceived;
-
-   private final Executor executor;
-
    private volatile boolean executing;
 
    private final SimpleString nodeID;
 
-   private final long creationTime;
-
    private String clientID;
 
    // Constructors
@@ -141,9 +124,9 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
                                   final SimpleString nodeID)
 
    {
-      this.packetDecoder = packetDecoder;
+      super(transportConnection, executor);
 
-      this.transportConnection = transportConnection;
+      this.packetDecoder = packetDecoder;
 
       this.blockingCallTimeout = blockingCallTimeout;
 
@@ -155,11 +138,9 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
 
       this.client = client;
 
-      this.executor = executor;
-
       this.nodeID = nodeID;
 
-      this.creationTime = System.currentTimeMillis();
+      transportConnection.setProtocolConnection(this);
    }
 
 
@@ -173,27 +154,10 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
          ", nodeID=" +
          nodeID +
          ", transportConnection=" +
-         transportConnection +
+         getTransportConnection() +
          "]";
    }
 
-   public Connection getTransportConnection()
-   {
-      return transportConnection;
-   }
-
-   public List<FailureListener> getFailureListeners()
-   {
-      return new ArrayList<FailureListener>(failureListeners);
-   }
-
-   public void setFailureListeners(final List<FailureListener> listeners)
-   {
-      failureListeners.clear();
-
-      failureListeners.addAll(listeners);
-   }
-
    /**
     * @return the clientVersion
     */
@@ -210,21 +174,6 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
       this.clientVersion = clientVersion;
    }
 
-   public Object getID()
-   {
-      return transportConnection.getID();
-   }
-
-   public String getRemoteAddress()
-   {
-      return transportConnection.getRemoteAddress();
-   }
-
-   public long getCreationTime()
-   {
-      return creationTime;
-   }
-
    public synchronized Channel getChannel(final long channelID, final int confWindowSize)
    {
       Channel channel = channels.get(channelID);
@@ -249,83 +198,6 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
       channels.put(channelID, channel);
    }
 
-   public void addFailureListener(final FailureListener listener)
-   {
-      if (listener == null)
-      {
-         throw HornetQClientMessageBundle.BUNDLE.failListenerCannotBeNull();
-      }
-      failureListeners.add(listener);
-   }
-
-   public boolean removeFailureListener(final FailureListener listener)
-   {
-      if (listener == null)
-      {
-         throw HornetQClientMessageBundle.BUNDLE.failListenerCannotBeNull();
-      }
-
-      return failureListeners.remove(listener);
-   }
-
-   public void addCloseListener(final CloseListener listener)
-   {
-      if (listener == null)
-      {
-         throw HornetQClientMessageBundle.BUNDLE.closeListenerCannotBeNull();
-      }
-
-      closeListeners.add(listener);
-   }
-
-   public boolean removeCloseListener(final CloseListener listener)
-   {
-      if (listener == null)
-      {
-         throw HornetQClientMessageBundle.BUNDLE.closeListenerCannotBeNull();
-      }
-
-      return closeListeners.remove(listener);
-   }
-
-   public List<CloseListener> removeCloseListeners()
-   {
-      List<CloseListener> ret = new ArrayList<CloseListener>(closeListeners);
-
-      closeListeners.clear();
-
-      return ret;
-   }
-
-   public List<FailureListener> removeFailureListeners()
-   {
-      List<FailureListener> ret = new ArrayList<FailureListener>(failureListeners);
-
-      failureListeners.clear();
-
-      return ret;
-   }
-
-   public void setCloseListeners(List<CloseListener> listeners)
-   {
-      closeListeners.clear();
-
-      closeListeners.addAll(listeners);
-   }
-
-   public HornetQBuffer createBuffer(final int size)
-   {
-      return transportConnection.createBuffer(size);
-   }
-
-   /*
-    * This can be called concurrently by more than one thread so needs to be locked
-    */
-   public void fail(final HornetQException me)
-   {
-      fail(me, null);
-   }
-
    public void fail(final HornetQException me, String scaleDownTargetNodeID)
    {
       synchronized (failLock)
@@ -340,6 +212,16 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
 
       HornetQClientLogger.LOGGER.connectionFailureDetected(me.getMessage(), me.getType());
 
+
+      try
+      {
+         transportConnection.forceClose();
+      }
+      catch (Throwable e)
+      {
+         HornetQClientLogger.LOGGER.warn(e.getMessage(), e);
+      }
+
       // Then call the listeners
       callFailureListeners(me, scaleDownTargetNodeID);
 
@@ -349,7 +231,7 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
 
       for (Channel channel : channels.values())
       {
-         channel.returnBlocking();
+         channel.returnBlocking(me);
       }
    }
 
@@ -464,15 +346,6 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
       return blockingCallFailoverTimeout;
    }
 
-   public boolean checkDataReceived()
-   {
-      boolean res = dataReceived;
-
-      dataReceived = false;
-
-      return res;
-   }
-
    //We flush any confirmations on the connection - this prevents idle bridges for example
    //sitting there with many unacked messages
    public void flush()
@@ -488,12 +361,11 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
 
    public HornetQPrincipal getDefaultHornetQPrincipal()
    {
-      return transportConnection.getDefaultHornetQPrincipal();
+      return getTransportConnection().getDefaultHornetQPrincipal();
    }
 
    // Buffer Handler implementation
    // ----------------------------------------------------
-
    public void bufferReceived(final Object connectionID, final HornetQBuffer buffer)
    {
       try
@@ -539,7 +411,7 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
             doBufferReceived(packet);
          }
 
-         dataReceived = true;
+         super.bufferReceived(connectionID, buffer);
       }
       catch (Exception e)
       {
@@ -565,7 +437,7 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
       }
    }
 
-   private void removeAllChannels()
+   protected void removeAllChannels()
    {
       // We get the transfer lock first - this ensures no packets are being processed AND
       // it's guaranteed no more packets will be processed once this method is complete
@@ -575,55 +447,10 @@ public class RemotingConnectionImpl implements CoreRemotingConnection
       }
    }
 
-   private void callFailureListeners(final HornetQException me, String scaleDownTargetNodeID)
-   {
-      final List<FailureListener> listenersClone = new ArrayList<FailureListener>(failureListeners);
-
-      for (final FailureListener listener : listenersClone)
-      {
-         try
-         {
-            listener.connectionFailed(me, false, scaleDownTargetNodeID);
-         }
-         catch (HornetQInterruptedException interrupted)
-         {
-            // this is an expected behaviour.. no warn or error here
-            HornetQClientLogger.LOGGER.debug("thread interrupted", interrupted);
-         }
-         catch (final Throwable t)
-         {
-            // Failure of one listener to execute shouldn't prevent others
-            // from
-            // executing
-            HornetQClientLogger.LOGGER.errorCallingFailureListener(t);
-         }
-      }
-   }
-
-   private void callClosingListeners()
-   {
-      final List<CloseListener> listenersClone = new ArrayList<CloseListener>(closeListeners);
-
-      for (final CloseListener listener : listenersClone)
-      {
-         try
-         {
-            listener.connectionClosed();
-         }
-         catch (final Throwable t)
-         {
-            // Failure of one listener to execute shouldn't prevent others
-            // from
-            // executing
-            HornetQClientLogger.LOGGER.errorCallingFailureListener(t);
-         }
-      }
-   }
-
    private void internalClose()
    {
       // We close the underlying transport connection
-      transportConnection.close();
+      getTransportConnection().close();
 
       for (Channel channel : channels.values())
       {

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/Ping.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/Ping.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/Ping.java
index 50e799b..77811bb 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/Ping.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/Ping.java
@@ -16,9 +16,9 @@ import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.core.protocol.core.impl.PacketImpl;
 
 /**
- * Ping is sent on the client side at {@link ClientSessionFactoryImpl}. At the server's side it is
- * treated at {@link RemotingServiceImpl}
- * @see RemotingConnection#checkDataReceived()
+ * Ping is sent on the client side by {@link org.hornetq.core.client.impl.ClientSessionFactoryImpl}. At the server's
+ * side it is handled by {@link org.hornetq.core.remoting.server.impl.RemotingServiceImpl}
+ * @see org.hornetq.spi.core.protocol.RemotingConnection#checkDataReceived()
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  */
 public final class Ping extends PacketImpl

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/SessionSendMessage.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/SessionSendMessage.java b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/SessionSendMessage.java
index 1a54ed2..fac4698 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/SessionSendMessage.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/protocol/core/impl/wireformat/SessionSendMessage.java
@@ -27,12 +27,12 @@ public class SessionSendMessage extends MessagePacket
    private boolean requiresResponse;
 
    /**
-    * In case, we are using a different handler than the one set on the {@link ClientSession}
+    * In case, we are using a different handler than the one set on the {@link org.hornetq.api.core.client.ClientSession}
     * <p/>
     * This field is only used at the client side.
     *
-    * @see ClientSession#setSendAcknowledgementHandler(SendAcknowledgementHandler)
-    * @see ClientProducer#send(SimpleString, Message, SendAcknowledgementHandler)
+    * @see org.hornetq.api.core.client.ClientSession#setSendAcknowledgementHandler(SendAcknowledgementHandler)
+    * @see org.hornetq.api.core.client.ClientProducer#send(org.hornetq.api.core.SimpleString, org.hornetq.api.core.Message, SendAcknowledgementHandler)
     */
    private final transient SendAcknowledgementHandler handler;
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/TransportConfigurationUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/TransportConfigurationUtil.java b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/TransportConfigurationUtil.java
new file mode 100644
index 0000000..58666e0
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/TransportConfigurationUtil.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.core.remoting.impl;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.hornetq.api.core.TransportConfigurationHelper;
+import org.hornetq.utils.ClassloadingUtil;
+
+/**
+ * Stores static mappings of class names to ConnectorFactory instances to act as a central repo for ConnectorFactory
+ * objects.
+ *
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
+ */
+
+public class TransportConfigurationUtil
+{
+   private static final Map<String, Map<String, Object>> DEFAULTS = new HashMap<>();
+
+   private static final HashMap<String, Object> EMPTY_HELPER = new HashMap<>();
+
+   public static Map<String, Object> getDefaults(String className)
+   {
+      if (className == null)
+      {
+         /* Returns a new clone of the empty helper.  This allows any parent objects to update the map key/values
+            without polluting the EMPTY_HELPER map. */
+         return (Map<String, Object>) EMPTY_HELPER.clone();
+      }
+
+      if (!DEFAULTS.containsKey(className))
+      {
+         Object object = instantiateObject(className);
+         if (object != null && object instanceof TransportConfigurationHelper)
+         {
+
+            DEFAULTS.put(className, ((TransportConfigurationHelper) object).getDefaults());
+         }
+         else
+         {
+            DEFAULTS.put(className, EMPTY_HELPER);
+         }
+      }
+
+      /* We need to return a copy of the default Map.  This means the defaults parent is able to update the map without
+      modifying the original */
+      return cloneDefaults(DEFAULTS.get(className));
+   }
+
+   private static Object instantiateObject(final String className)
+   {
+      return AccessController.doPrivileged(new PrivilegedAction<Object>()
+      {
+         public Object run()
+         {
+            try
+            {
+               return ClassloadingUtil.newInstanceFromClassLoader(className);
+            }
+            catch (IllegalStateException e)
+            {
+               return null;
+            }
+         }
+      });
+   }
+
+   private static Map<String, Object> cloneDefaults(Map<String, Object> defaults)
+   {
+      Map<String, Object> cloned = new HashMap<String, Object>();
+      for (Map.Entry entry : defaults.entrySet())
+      {
+         cloned.put((String) entry.getKey(), entry.getValue());
+      }
+      return cloned;
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/HornetQAMQPFrameDecoder.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/HornetQAMQPFrameDecoder.java b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/HornetQAMQPFrameDecoder.java
new file mode 100644
index 0000000..68fc6e1
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/HornetQAMQPFrameDecoder.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+package org.hornetq.core.remoting.impl.netty;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
+
+/**
+ * A Netty decoder specially optimised to to decode messages on the core protocol only
+ *
+ * @author <a href="tlee@redhat.com">Trustin Lee</a>
+ * @author <a href="nmaurer@redhat.com">Norman Maurer</a>
+ * @version $Revision: 7839 $, $Date: 2009-08-21 02:26:39 +0900 (2009-08-21, 금) $
+ */
+public class HornetQAMQPFrameDecoder extends LengthFieldBasedFrameDecoder
+{
+   public HornetQAMQPFrameDecoder()
+   {
+      // The interface itself is part of the buffer (hence the -4)
+      super(Integer.MAX_VALUE, 0, 4, -4 , 0);
+   }
+
+
+   @Override
+   protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length)
+   {
+      return super.extractFrame(ctx, buffer, index, length);
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnection.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnection.java b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnection.java
index 474c452..a848df2 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnection.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnection.java
@@ -20,6 +20,7 @@ import java.util.concurrent.Semaphore;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelPromise;
 import io.netty.channel.EventLoop;
 import io.netty.handler.ssl.SslHandler;
@@ -30,6 +31,7 @@ import org.hornetq.api.core.TransportConfiguration;
 import org.hornetq.core.buffers.impl.ChannelBufferWrapper;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.security.HornetQPrincipal;
+import org.hornetq.spi.core.protocol.RemotingConnection;
 import org.hornetq.spi.core.remoting.Connection;
 import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener;
 import org.hornetq.spi.core.remoting.ReadyListener;
@@ -66,7 +68,9 @@ public class NettyConnection implements Connection
 
    private final Set<ReadyListener> readyListeners = new ConcurrentHashSet<ReadyListener>();
 
-   // Static --------------------------------------------------------
+   private RemotingConnection protocolConnection;
+
+// Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
 
@@ -89,9 +93,29 @@ public class NettyConnection implements Connection
 
    // Public --------------------------------------------------------
 
+   public Channel getNettyChannel()
+   {
+      return channel;
+   }
    // Connection implementation ----------------------------
 
 
+   public void forceClose()
+   {
+      if (channel != null)
+      {
+         try
+         {
+            channel.close();
+         }
+         catch (Throwable e)
+         {
+            HornetQClientLogger.LOGGER.warn(e.getMessage(), e);
+         }
+      }
+   }
+
+
    /**
     * This is exposed so users would have the option to look at any data through interceptors
     *
@@ -102,6 +126,16 @@ public class NettyConnection implements Connection
       return channel;
    }
 
+   public RemotingConnection getProtocolConnection()
+   {
+      return protocolConnection;
+   }
+
+   public void setProtocolConnection(RemotingConnection protocolConnection)
+   {
+      this.protocolConnection = protocolConnection;
+   }
+
    public void close()
    {
       if (closed)
@@ -178,6 +212,11 @@ public class NettyConnection implements Connection
 
    public void write(HornetQBuffer buffer, final boolean flush, final boolean batched)
    {
+      write(buffer, flush, batched, null);
+   }
+
+   public void write(HornetQBuffer buffer, final boolean flush, final boolean batched, final ChannelFutureListener futureListener)
+   {
 
       try
       {
@@ -223,7 +262,7 @@ public class NettyConnection implements Connection
             // use a normal promise
             final ByteBuf buf = buffer.byteBuf();
             final ChannelPromise promise;
-            if (flush)
+            if (flush || futureListener != null)
             {
                promise = channel.newPromise();
             }
@@ -236,7 +275,14 @@ public class NettyConnection implements Connection
             boolean inEventLoop = eventLoop.inEventLoop();
             if (!inEventLoop)
             {
-               channel.writeAndFlush(buf, promise);
+               if (futureListener != null)
+               {
+                  channel.writeAndFlush(buf, promise).addListener(futureListener);
+               }
+               else
+               {
+                  channel.writeAndFlush(buf, promise);
+               }
             }
             else
             {
@@ -248,7 +294,14 @@ public class NettyConnection implements Connection
                   @Override
                   public void run()
                   {
-                     channel.writeAndFlush(buf, promise);
+                     if (futureListener != null)
+                     {
+                        channel.writeAndFlush(buf, promise).addListener(futureListener);
+                     }
+                     else
+                     {
+                        channel.writeAndFlush(buf, promise);
+                     }
                   }
                };
                // execute the task on the eventloop
@@ -343,6 +396,12 @@ public class NettyConnection implements Connection
       }
    }
 
+   @Override
+   public boolean isUsingProtocolHandling()
+   {
+      return true;
+   }
+
 
    // Public --------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnector.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnector.java b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnector.java
index e053cac..f442c91 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnector.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnector.java
@@ -41,6 +41,8 @@ import java.security.AccessController;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.security.PrivilegedAction;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
@@ -94,16 +96,16 @@ import io.netty.util.ResourceLeakDetector;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GlobalEventExecutor;
 import org.hornetq.api.config.HornetQDefaultConfiguration;
-import org.hornetq.api.core.HornetQBuffer;
 import org.hornetq.api.core.HornetQException;
-import org.hornetq.api.core.client.HornetQClient;
 import org.hornetq.core.client.HornetQClientLogger;
 import org.hornetq.core.client.HornetQClientMessageBundle;
 import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
+import org.hornetq.core.protocol.core.impl.HornetQClientProtocolManager;
 import org.hornetq.core.remoting.impl.ssl.SSLSupport;
 import org.hornetq.core.server.HornetQComponent;
 import org.hornetq.spi.core.remoting.AbstractConnector;
 import org.hornetq.spi.core.remoting.BufferHandler;
+import org.hornetq.spi.core.remoting.ClientProtocolManager;
 import org.hornetq.spi.core.remoting.Connection;
 import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener;
 import org.hornetq.utils.ConfigurationHelper;
@@ -117,6 +119,7 @@ import static org.hornetq.utils.Base64.encodeBytes;
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
  * @author <a href="mailto:tlee@redhat.com">Trustin Lee</a>
  * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class NettyConnector extends AbstractConnector
 {
@@ -142,10 +145,19 @@ public class NettyConnector extends AbstractConnector
 
    private static final AttributeKey<String> REMOTING_KEY = AttributeKey.valueOf(SEC_HORNETQ_REMOTING_KEY);
 
+   // Default Configuration
+   public static final Map<String, Object> DEFAULT_CONFIG;
+
    static
    {
       // Disable resource leak detection for performance reasons by default
       ResourceLeakDetector.setEnabled(false);
+
+      // Set default Configuration
+      Map<String, Object> config = new HashMap<String , Object>();
+      config.put(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST);
+      config.put(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT);
+      DEFAULT_CONFIG = Collections.unmodifiableMap(config);
    }
 
    // Attributes ----------------------------------------------------
@@ -229,12 +241,13 @@ public class NettyConnector extends AbstractConnector
 
    private int connectTimeoutMillis;
 
+   private final ClientProtocolManager protocolManager;
+
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
 
    // Public --------------------------------------------------------
-
    public NettyConnector(final Map<String, Object> configuration,
                          final BufferHandler handler,
                          final ConnectionLifeCycleListener listener,
@@ -242,7 +255,22 @@ public class NettyConnector extends AbstractConnector
                          final Executor threadPool,
                          final ScheduledExecutorService scheduledThreadPool)
    {
+      this(configuration, handler, listener, closeExecutor, threadPool, scheduledThreadPool, new HornetQClientProtocolManager());
+   }
+
+
+   public NettyConnector(final Map<String, Object> configuration,
+                         final BufferHandler handler,
+                         final ConnectionLifeCycleListener listener,
+                         final Executor closeExecutor,
+                         final Executor threadPool,
+                         final ScheduledExecutorService scheduledThreadPool,
+                         final ClientProtocolManager protocolManager)
+   {
       super(configuration);
+
+      this.protocolManager = protocolManager;
+
       if (listener == null)
       {
          throw HornetQClientMessageBundle.BUNDLE.nullListener();
@@ -437,10 +465,7 @@ public class NettyConnector extends AbstractConnector
          group = new NioEventLoopGroup(threadsToUse);
       }
       // if we are a servlet wrap the socketChannelFactory
-      if (useServlet)
-      {
-         // TODO: This will be replaced by allow upgrade HTTP connection from Undertow.;
-      }
+
       bootstrap = new Bootstrap();
       bootstrap.channel(channelClazz);
       bootstrap.group(group);
@@ -611,7 +636,8 @@ public class NettyConnector extends AbstractConnector
                pipeline.addLast(httpClientCodec);
                pipeline.addLast("http-upgrade", new HttpUpgradeHandler(pipeline, httpClientCodec));
             }
-            pipeline.addLast(new HornetQFrameDecoder2());
+
+            protocolManager.addChannelHandlers(pipeline);
 
             pipeline.addLast(new HornetQClientChannelHandler(channelGroup, handler, new Listener()));
          }
@@ -761,8 +787,8 @@ public class NettyConnector extends AbstractConnector
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
 
                final String endpoint = ConfigurationHelper.getStringProperty(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME,
-                       null,
-                       configuration);
+                                                                             null,
+                                                                             configuration);
                if (endpoint != null)
                {
                   request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
@@ -800,7 +826,7 @@ public class NettyConnector extends AbstractConnector
          // No acceptor on a client connection
          Listener connectionListener = new Listener();
          NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false);
-         connectionListener.connectionCreated(null, conn, HornetQClient.DEFAULT_CORE_PROTOCOL);
+         connectionListener.connectionCreated(null, conn, protocolManager.getName());
          return conn;
       }
       else
@@ -876,6 +902,11 @@ public class NettyConnector extends AbstractConnector
                   ctx.close();
                }
             }
+            else if (response.getStatus().code() == HttpResponseStatus.FORBIDDEN.code())
+            {
+               HornetQClientLogger.LOGGER.httpUpgradeNotSupportedByRemoteAcceptor();
+               ctx.close();
+            }
             latch.countDown();
          }
       }
@@ -1062,10 +1093,6 @@ public class NettyConnector extends AbstractConnector
          {
             throw HornetQClientMessageBundle.BUNDLE.connectionExists(connection.getID());
          }
-         String handshake = "HORNETQ";
-         HornetQBuffer buffer = connection.createBuffer(handshake.length());
-         buffer.writeBytes(handshake.getBytes());
-         connection.write(buffer);
       }
 
       public void connectionDestroyed(final Object connectionID)

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnectorFactory.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnectorFactory.java b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnectorFactory.java
index 1b9f9e9..f66b58a 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnectorFactory.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/netty/NettyConnectorFactory.java
@@ -18,6 +18,7 @@ import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
 
 import org.hornetq.spi.core.remoting.BufferHandler;
+import org.hornetq.spi.core.remoting.ClientProtocolManager;
 import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener;
 import org.hornetq.spi.core.remoting.Connector;
 import org.hornetq.spi.core.remoting.ConnectorFactory;
@@ -26,6 +27,7 @@ import org.hornetq.spi.core.remoting.ConnectorFactory;
  * A NettyConnectorFactory
  *
  * @author <a href="mailto:tim.fox@jboss.com">Tim Fox</a>
+ * @author <a href="mailto:mtaylor@redhat.com">Martyn Taylor</a>
  */
 public class NettyConnectorFactory implements ConnectorFactory
 {
@@ -34,7 +36,8 @@ public class NettyConnectorFactory implements ConnectorFactory
                                     final ConnectionLifeCycleListener listener,
                                     final Executor closeExecutor,
                                     final Executor threadPool,
-                                    final ScheduledExecutorService scheduledThreadPool)
+                                    final ScheduledExecutorService scheduledThreadPool,
+                                    final ClientProtocolManager protocolManager)
    {
       return new NettyConnector(configuration, handler, listener, closeExecutor, threadPool, scheduledThreadPool);
    }
@@ -49,4 +52,10 @@ public class NettyConnectorFactory implements ConnectorFactory
    {
       return false;
    }
+
+   @Override
+   public Map<String, Object> getDefaults()
+   {
+      return NettyConnector.DEFAULT_CONFIG;
+   }
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/ssl/SSLSupport.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/ssl/SSLSupport.java b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/ssl/SSLSupport.java
index cbe93f9..97bd565 100644
--- a/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/ssl/SSLSupport.java
+++ b/hornetq-core-client/src/main/java/org/hornetq/core/remoting/impl/ssl/SSLSupport.java
@@ -32,19 +32,15 @@ import org.hornetq.utils.ClassloadingUtil;
 
 /**
  * @author <a href="mailto:jmesnil@redhat.com">Jeff Mesnil</a>
+ * @author Justin Bertram
  *
- *
+ * Please note, this class supports PKCS#11 keystores, but there are no specific tests in the HornetQ test-suite to
+ * validate/verify this works because this requires a functioning PKCS#11 provider which is not available by default
+ * (see java.security.Security#getProviders()).  The main thing to keep in mind is that PKCS#11 keystores will have a
+ * null keystore path.
  */
 public class SSLSupport
 {
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
    // Public --------------------------------------------------------
 
    public static SSLContext createContext(final String keystoreProvider, final String keystorePath, final String keystorePassword,
@@ -81,17 +77,13 @@ public class SSLSupport
       return supportedSuites.delete(supportedSuites.length() - 2, supportedSuites.length()).toString();
    }
 
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
    // Private -------------------------------------------------------
 
    private static TrustManager[] loadTrustManager(final String trustStoreProvider,
                                                   final String trustStorePath,
                                                   final String trustStorePassword) throws Exception
    {
-      if (trustStorePath == null && ("JKS".equals(trustStoreProvider) || trustStoreProvider == null))
+      if (trustStorePath == null && (trustStoreProvider == null || (trustStoreProvider != null && !"PKCS11".equals(trustStoreProvider.toUpperCase()))))
       {
          return null;
       }
@@ -107,14 +99,11 @@ public class SSLSupport
 
    private static KeyStore loadKeystore(final String keystoreProvider, final String keystorePath, final String keystorePassword) throws Exception
    {
-      assert keystorePath != null || "JKS".equals(keystoreProvider) == false;
-      assert keystorePassword != null;
-
       KeyStore ks = KeyStore.getInstance(keystoreProvider);
       InputStream in = null;
       try
       {
-         if ("JKS".equals(keystoreProvider))
+         if (keystorePath != null)
          {
             URL keystoreURL = SSLSupport.validateStoreURL(keystorePath);
             in = keystoreURL.openStream();
@@ -139,7 +128,7 @@ public class SSLSupport
 
    private static KeyManager[] loadKeyManagers(final String keyStoreProvider, final String keystorePath, final String keystorePassword) throws Exception
    {
-      if (keystorePath == null && ("JKS".equals(keyStoreProvider) || keyStoreProvider == null))
+      if (keystorePath == null && (keyStoreProvider == null || (keyStoreProvider != null && !"PKCS11".equals(keyStoreProvider.toUpperCase()))))
       {
          return null;
       }
@@ -196,7 +185,4 @@ public class SSLSupport
          }
       });
    }
-
-
-   // Inner classes -------------------------------------------------
 }

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/reader/BytesMessageUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/reader/BytesMessageUtil.java b/hornetq-core-client/src/main/java/org/hornetq/reader/BytesMessageUtil.java
new file mode 100644
index 0000000..24ea35c
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/reader/BytesMessageUtil.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.reader;
+
+import org.hornetq.api.core.Message;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class BytesMessageUtil extends MessageUtil
+{
+
+   public static boolean bytesReadBoolean(Message message)
+   {
+      return getBodyBuffer(message).readBoolean();
+   }
+
+   public static byte bytesReadByte(Message message)
+   {
+      return getBodyBuffer(message).readByte();
+   }
+
+   public static int bytesReadUnsignedByte(Message message)
+   {
+      return getBodyBuffer(message).readUnsignedByte();
+   }
+
+   public static short bytesReadShort(Message message)
+   {
+      return getBodyBuffer(message).readShort();
+   }
+
+   public static int bytesReadUnsignedShort(Message message)
+   {
+      return getBodyBuffer(message).readUnsignedShort();
+   }
+
+   public static char bytesReadChar(Message message)
+   {
+      return (char)getBodyBuffer(message).readShort();
+   }
+
+   public static int bytesReadInt(Message message)
+   {
+      return getBodyBuffer(message).readInt();
+   }
+
+   public static long bytesReadLong(Message message)
+   {
+      return getBodyBuffer(message).readLong();
+   }
+
+   public static float bytesReadFloat(Message message)
+   {
+      return Float.intBitsToFloat(getBodyBuffer(message).readInt());
+   }
+
+   public static double bytesReadDouble(Message message)
+   {
+      return Double.longBitsToDouble(getBodyBuffer(message).readLong());
+   }
+
+   public static String bytesReadUTF(Message message)
+   {
+      return getBodyBuffer(message).readUTF();
+   }
+
+
+
+   public static int bytesReadBytes(Message message, final byte[] value)
+   {
+      return bytesReadBytes(message, value, value.length);
+   }
+
+   public static int bytesReadBytes(Message message, final byte[] value, final int length)
+   {
+      if (!getBodyBuffer(message).readable())
+      {
+         return -1;
+      }
+
+      int read = Math.min(length, getBodyBuffer(message).readableBytes());
+
+      if (read != 0)
+      {
+         getBodyBuffer(message).readBytes(value, 0, read);
+      }
+
+      return read;
+
+   }
+
+
+   public static void bytesWriteBoolean(Message message, boolean value)
+   {
+      getBodyBuffer(message).writeBoolean(value);
+   }
+
+
+
+   public static void bytesWriteByte(Message message, byte value)
+   {
+      getBodyBuffer(message).writeByte(value);
+   }
+
+
+
+   public static void bytesWriteShort(Message message, short value)
+   {
+      getBodyBuffer(message).writeShort(value);
+   }
+
+
+   public static void bytesWriteChar(Message message, char value)
+   {
+      getBodyBuffer(message).writeShort((short)value);
+   }
+
+   public static void bytesWriteInt(Message message, int value)
+   {
+      getBodyBuffer(message).writeInt(value);
+   }
+
+   public static void bytesWriteLong(Message message, long value)
+   {
+      getBodyBuffer(message).writeLong(value);
+   }
+
+   public static void bytesWriteFloat(Message message, float value)
+   {
+      getBodyBuffer(message).writeInt(Float.floatToIntBits(value));
+   }
+
+   public static void bytesWriteDouble(Message message, double value)
+   {
+      getBodyBuffer(message).writeLong(Double.doubleToLongBits(value));
+   }
+
+   public static void bytesWriteUTF(Message message, String value)
+   {
+      getBodyBuffer(message).writeUTF(value);
+   }
+
+   public static void bytesWriteBytes(Message message, byte[] value)
+   {
+      getBodyBuffer(message).writeBytes(value);
+   }
+
+   public static void bytesWriteBytes(Message message, final byte[] value, final int offset, final int length)
+   {
+      getBodyBuffer(message).writeBytes(value, offset, length);
+   }
+
+
+   /**
+    * Returns true if it could send the Object to any known format
+    * @param message
+    * @param value
+    * @return
+    */
+   public static boolean bytesWriteObject(Message message, Object value)
+   {
+      if (value == null)
+      {
+         throw new NullPointerException("Attempt to write a null value");
+      }
+      if (value instanceof String)
+      {
+         bytesWriteUTF(message, (String) value);
+      }
+      else if (value instanceof Boolean)
+      {
+         bytesWriteBoolean(message, (Boolean) value);
+      }
+      else if (value instanceof Character)
+      {
+         bytesWriteChar(message, (Character) value);
+      }
+      else if (value instanceof Byte)
+      {
+         bytesWriteByte(message, (Byte) value);
+      }
+      else if (value instanceof Short)
+      {
+         bytesWriteShort(message, (Short) value);
+      }
+      else if (value instanceof Integer)
+      {
+         bytesWriteInt(message, (Integer) value);
+      }
+      else if (value instanceof Long)
+      {
+         bytesWriteLong(message, (Long) value);
+      }
+      else if (value instanceof Float)
+      {
+         bytesWriteFloat(message, (Float) value);
+      }
+      else if (value instanceof Double)
+      {
+         bytesWriteDouble(message, (Double) value);
+      }
+      else if (value instanceof byte[])
+      {
+         bytesWriteBytes(message, (byte[]) value);
+      }
+      else
+      {
+         return false;
+      }
+
+
+      return true;
+   }
+
+   public static void bytesMessageReset(Message message)
+   {
+      getBodyBuffer(message).resetReaderIndex();
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/reader/MapMessageUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/reader/MapMessageUtil.java b/hornetq-core-client/src/main/java/org/hornetq/reader/MapMessageUtil.java
new file mode 100644
index 0000000..d55fb30
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/reader/MapMessageUtil.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.reader;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.Message;
+import org.hornetq.utils.TypedProperties;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class MapMessageUtil extends MessageUtil
+{
+
+   /**
+    * Utility method to set the map on a message body
+    */
+   public static void writeBodyMap(Message message, TypedProperties properties)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      buff.resetWriterIndex();
+      properties.encode(buff);
+   }
+
+   /**
+    * Utility method to set the map on a message body
+    */
+   public static TypedProperties readBodyMap(Message message)
+   {
+      TypedProperties map = new TypedProperties();
+      readBodyMap(message, map);
+      return map;
+   }
+
+   /**
+    * Utility method to set the map on a message body
+    */
+   public static void readBodyMap(Message message, TypedProperties map)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      buff.resetReaderIndex();
+      map.decode(buff);
+   }
+
+
+
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/reader/MessageUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/reader/MessageUtil.java b/hornetq-core-client/src/main/java/org/hornetq/reader/MessageUtil.java
new file mode 100644
index 0000000..a2429db
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/reader/MessageUtil.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.reader;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.HornetQException;
+import org.hornetq.api.core.HornetQPropertyConversionException;
+import org.hornetq.api.core.Message;
+import org.hornetq.api.core.SimpleString;
+
+/**
+ * static methods intended for import static on JMS like messages.
+ *
+ * This provides a helper for core message to act some of the JMS functions used by the JMS wrapper
+ *
+ * @author Clebert Suconic
+ */
+
+public class MessageUtil
+{
+   public static final SimpleString CORRELATIONID_HEADER_NAME = new SimpleString("JMSCorrelationID");
+
+   public static final SimpleString REPLYTO_HEADER_NAME = new SimpleString("JMSReplyTo");
+
+   public static final SimpleString TYPE_HEADER_NAME = new SimpleString("JMSType");
+
+   public static final SimpleString JMS = new SimpleString("JMS");
+
+   public static final SimpleString JMSX = new SimpleString("JMSX");
+
+   public static final SimpleString JMS_ = new SimpleString("JMS_");
+
+   public static final String JMSXDELIVERYCOUNT = "JMSXDeliveryCount";
+
+   public static final String JMSXGROUPID = "JMSXGroupID";
+
+   public static final SimpleString CONNECTION_ID_PROPERTY_NAME = new SimpleString("__HQ_CID");
+
+
+
+   public static HornetQBuffer getBodyBuffer(Message message)
+   {
+      return message.getBodyBuffer();
+   }
+
+
+
+   public static byte[] getJMSCorrelationIDAsBytes(Message message)
+   {
+      Object obj = message.getObjectProperty(CORRELATIONID_HEADER_NAME);
+
+      if (obj instanceof byte[])
+      {
+         return (byte[])obj;
+      }
+      else
+      {
+         return null;
+      }
+   }
+
+
+
+   public static void setJMSType(Message message, String type)
+   {
+      message.putStringProperty(TYPE_HEADER_NAME, new SimpleString(type));
+   }
+
+   public static String getJMSType(Message message)
+   {
+      SimpleString ss = message.getSimpleStringProperty(TYPE_HEADER_NAME);
+
+      if (ss != null)
+      {
+         return ss.toString();
+      }
+      else
+      {
+         return null;
+      }
+   }
+
+
+   public static final void setJMSCorrelationIDAsBytes(Message message, final byte[] correlationID) throws HornetQException
+   {
+      if (correlationID == null || correlationID.length == 0)
+      {
+         throw new HornetQException("Please specify a non-zero length byte[]");
+      }
+      message.putBytesProperty(CORRELATIONID_HEADER_NAME, correlationID);
+   }
+
+   public static void setJMSCorrelationID(Message message, final String correlationID)
+   {
+      if (correlationID == null)
+      {
+         message.removeProperty(CORRELATIONID_HEADER_NAME);
+      }
+      else
+      {
+         message.putStringProperty(CORRELATIONID_HEADER_NAME, new SimpleString(correlationID));
+      }
+   }
+
+   public static String getJMSCorrelationID(Message message)
+   {
+      try
+      {
+         return message.getStringProperty(CORRELATIONID_HEADER_NAME);
+      }
+      catch (HornetQPropertyConversionException e)
+      {
+         return null;
+      }
+   }
+
+
+   public static SimpleString getJMSReplyTo(Message message)
+   {
+      return message.getSimpleStringProperty(REPLYTO_HEADER_NAME);
+   }
+
+   public static void setJMSReplyTo(Message message, final SimpleString dest)
+   {
+
+      if (dest == null)
+      {
+         message.removeProperty(REPLYTO_HEADER_NAME);
+      }
+      else
+      {
+
+         message.putStringProperty(REPLYTO_HEADER_NAME, dest);
+      }
+   }
+
+
+
+   public static void clearProperties(Message message)
+   {
+
+      List<SimpleString> toRemove = new ArrayList<SimpleString>();
+
+      for (SimpleString propName : message.getPropertyNames())
+      {
+         if (!propName.startsWith(JMS) || propName.startsWith(JMSX) ||
+            propName.startsWith(JMS_))
+         {
+            toRemove.add(propName);
+         }
+      }
+
+      for (SimpleString propName : toRemove)
+      {
+         message.removeProperty(propName);
+      }
+   }
+
+
+
+   public static Set<String> getPropertyNames(Message message)
+   {
+      HashSet<String> set = new HashSet<String>();
+
+      for (SimpleString propName : message.getPropertyNames())
+      {
+         if ((!propName.startsWith(JMS) || propName.startsWith(JMSX) ||
+            propName.startsWith(JMS_)) && !propName.startsWith(CONNECTION_ID_PROPERTY_NAME))
+         {
+            set.add(propName.toString());
+         }
+      }
+
+      set.add(JMSXDELIVERYCOUNT);
+
+      return set;
+   }
+
+   public static boolean propertyExists(Message message, String name)
+   {
+      return message.containsProperty(new SimpleString(name)) || name.equals(MessageUtil.JMSXDELIVERYCOUNT) ||
+         MessageUtil.JMSXGROUPID.equals(name) &&
+            message.containsProperty(org.hornetq.api.core.Message.HDR_GROUP_ID);
+   }
+}

http://git-wip-us.apache.org/repos/asf/activemq-6/blob/177e6820/hornetq-core-client/src/main/java/org/hornetq/reader/StreamMessageUtil.java
----------------------------------------------------------------------
diff --git a/hornetq-core-client/src/main/java/org/hornetq/reader/StreamMessageUtil.java b/hornetq-core-client/src/main/java/org/hornetq/reader/StreamMessageUtil.java
new file mode 100644
index 0000000..edefc01
--- /dev/null
+++ b/hornetq-core-client/src/main/java/org/hornetq/reader/StreamMessageUtil.java
@@ -0,0 +1,300 @@
+/*
+ * Copyright 2005-2014 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.reader;
+
+import org.hornetq.api.core.HornetQBuffer;
+import org.hornetq.api.core.Message;
+import org.hornetq.api.core.Pair;
+import org.hornetq.utils.DataConstants;
+
+/**
+ * @author Clebert Suconic
+ */
+
+public class StreamMessageUtil extends MessageUtil
+{
+   /**
+    * Method to read boolean values out of the Stream protocol existent on JMS Stream Messages
+    * Throws IllegalStateException if the type was invalid
+    *
+    * @param message
+    * @return
+    */
+   public static boolean streamReadBoolean(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+
+      switch (type)
+      {
+         case DataConstants.BOOLEAN:
+            return buff.readBoolean();
+         case DataConstants.STRING:
+            String s = buff.readNullableString();
+            return Boolean.valueOf(s);
+         default:
+            throw new IllegalStateException("Invalid conversion, type byte was " + type);
+      }
+
+   }
+
+   public static byte streamReadByte(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      int index = buff.readerIndex();
+      try
+      {
+         byte type = buff.readByte();
+         switch (type)
+         {
+            case DataConstants.BYTE:
+               return buff.readByte();
+            case DataConstants.STRING:
+               String s = buff.readNullableString();
+               return Byte.parseByte(s);
+            default:
+               throw new IllegalStateException("Invalid conversion");
+         }
+      }
+      catch (NumberFormatException e)
+      {
+         buff.readerIndex(index);
+         throw e;
+      }
+
+   }
+
+   public static short streamReadShort(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.BYTE:
+            return buff.readByte();
+         case DataConstants.SHORT:
+            return buff.readShort();
+         case DataConstants.STRING:
+            String s = buff.readNullableString();
+            return Short.parseShort(s);
+         default:
+            throw new IllegalStateException("Invalid conversion");
+      }
+   }
+
+   public static char streamReadChar(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.CHAR:
+            return (char)buff.readShort();
+         case DataConstants.STRING:
+            String str = buff.readNullableString();
+            if (str == null)
+            {
+               throw new NullPointerException("Invalid conversion");
+            }
+            else
+            {
+               throw new IllegalStateException("Invalid conversion");
+            }
+         default:
+            throw new IllegalStateException("Invalid conversion");
+      }
+
+   }
+
+   public static int streamReadInteger(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.BYTE:
+            return buff.readByte();
+         case DataConstants.SHORT:
+            return buff.readShort();
+         case DataConstants.INT:
+            return buff.readInt();
+         case DataConstants.STRING:
+            String s = buff.readNullableString();
+            return Integer.parseInt(s);
+         default:
+            throw new IllegalStateException("Invalid conversion");
+      }
+   }
+
+
+   public static long streamReadLong(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.BYTE:
+            return buff.readByte();
+         case DataConstants.SHORT:
+            return buff.readShort();
+         case DataConstants.INT:
+            return buff.readInt();
+         case DataConstants.LONG:
+            return buff.readLong();
+         case DataConstants.STRING:
+            String s = buff.readNullableString();
+            return Long.parseLong(s);
+         default:
+            throw new IllegalStateException("Invalid conversion");
+      }
+   }
+
+   public static float streamReadFloat(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.FLOAT:
+            return Float.intBitsToFloat(buff.readInt());
+         case DataConstants.STRING:
+            String s = buff.readNullableString();
+            return Float.parseFloat(s);
+         default:
+            throw new IllegalStateException("Invalid conversion");
+      }
+   }
+
+
+   public static double streamReadDouble(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.FLOAT:
+            return Float.intBitsToFloat(buff.readInt());
+         case DataConstants.DOUBLE:
+            return Double.longBitsToDouble(buff.readLong());
+         case DataConstants.STRING:
+            String s = buff.readNullableString();
+            return Double.parseDouble(s);
+         default:
+            throw new IllegalStateException("Invalid conversion: " + type);
+      }
+   }
+
+
+   public static String streamReadString(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.BOOLEAN:
+            return String.valueOf(buff.readBoolean());
+         case DataConstants.BYTE:
+            return String.valueOf(buff.readByte());
+         case DataConstants.SHORT:
+            return String.valueOf(buff.readShort());
+         case DataConstants.CHAR:
+            return String.valueOf((char)buff.readShort());
+         case DataConstants.INT:
+            return String.valueOf(buff.readInt());
+         case DataConstants.LONG:
+            return String.valueOf(buff.readLong());
+         case DataConstants.FLOAT:
+            return String.valueOf(Float.intBitsToFloat(buff.readInt()));
+         case DataConstants.DOUBLE:
+            return String.valueOf(Double.longBitsToDouble(buff.readLong()));
+         case DataConstants.STRING:
+            return buff.readNullableString();
+         default:
+            throw new IllegalStateException("Invalid conversion");
+      }
+   }
+
+   /**
+    * Utility for reading bytes out of streaming.
+    * It will return remainingBytes, bytesRead
+    * @param remainingBytes remaining Bytes from previous read. Send it to 0 if it was the first call for the message
+    * @param message
+    * @return a pair of remaining bytes and bytes read
+    */
+   public static Pair<Integer, Integer> streamReadBytes(Message message, int remainingBytes, byte[] value)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+
+      if (remainingBytes == -1)
+      {
+         return new Pair<>(0, -1);
+      }
+      else if (remainingBytes == 0)
+      {
+         byte type = buff.readByte();
+         if (type != DataConstants.BYTES)
+         {
+            throw new IllegalStateException("Invalid conversion");
+         }
+         remainingBytes = buff.readInt();
+      }
+      int read = Math.min(value.length, remainingBytes);
+      buff.readBytes(value, 0, read);
+      remainingBytes -= read;
+      if (remainingBytes == 0)
+      {
+         remainingBytes = -1;
+      }
+      return new Pair<>(remainingBytes, read);
+
+   }
+
+   public static Object streamReadObject(Message message)
+   {
+      HornetQBuffer buff = getBodyBuffer(message);
+
+      byte type = buff.readByte();
+      switch (type)
+      {
+         case DataConstants.BOOLEAN:
+            return buff.readBoolean();
+         case DataConstants.BYTE:
+            return buff.readByte();
+         case DataConstants.SHORT:
+            return buff.readShort();
+         case DataConstants.CHAR:
+            return (char)buff.readShort();
+         case DataConstants.INT:
+            return buff.readInt();
+         case DataConstants.LONG:
+            return buff.readLong();
+         case DataConstants.FLOAT:
+            return Float.intBitsToFloat(buff.readInt());
+         case DataConstants.DOUBLE:
+            return Double.longBitsToDouble(buff.readLong());
+         case DataConstants.STRING:
+            return buff.readNullableString();
+         case DataConstants.BYTES:
+            int bufferLen = buff.readInt();
+            byte[] bytes = new byte[bufferLen];
+            buff.readBytes(bytes);
+            return bytes;
+         default:
+            throw new IllegalStateException("Invalid conversion");
+      }
+
+   }
+
+
+}