@Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    server = internalCreateServer();

    server.createAddressInfo(new AddressInfo(ADDRESS, RoutingType.ANYCAST));
    Queue queue = server.createQueue(ADDRESS, RoutingType.ANYCAST, ADDRESS, null, true, false);
    queue.getPageSubscription().getPagingStore().startPaging();

    for (int i = 0; i < 10; i++) {
      queue.getPageSubscription().getPagingStore().forceAnotherPage();
    }

    final ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(null, null, false, true, true, false, 0);
    ClientProducer prod = session.createProducer(ADDRESS);

    for (int i = 0; i < 500; i++) {
      ClientMessage msg = session.createMessage(true);
      msg.putIntProperty("key", i);
      prod.send(msg);
      if (i > 0 && i % 10 == 0) {
        session.commit();
      }
    }

    session.close();
    locator.close();

    server.stop();

    internalCreateServer();
  }
  @Test
  public void testStopStartMultipleConsumers() throws Exception {
    locator.setConsumerWindowSize(getMessageEncodeSize(QUEUE) * 33);
    ClientSessionFactory sf = createSessionFactory(locator);

    final ClientSession session = sf.createSession(false, true, true);

    session.createQueue(QUEUE, QUEUE, null, false);

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(session, "m" + i);
      message.putIntProperty(new SimpleString("i"), i);
      producer.send(message);
    }

    ClientConsumer consumer = session.createConsumer(QUEUE);
    ClientConsumer consumer2 = session.createConsumer(QUEUE);
    ClientConsumer consumer3 = session.createConsumer(QUEUE);

    session.start();

    ClientMessage cm = consumer.receive(5000);
    Assert.assertNotNull(cm);
    cm.acknowledge();
    cm = consumer2.receive(5000);
    Assert.assertNotNull(cm);
    cm.acknowledge();
    cm = consumer3.receive(5000);
    Assert.assertNotNull(cm);
    cm.acknowledge();

    session.stop();
    cm = consumer.receiveImmediate();
    Assert.assertNull(cm);
    cm = consumer2.receiveImmediate();
    Assert.assertNull(cm);
    cm = consumer3.receiveImmediate();
    Assert.assertNull(cm);

    session.start();
    cm = consumer.receive(5000);
    Assert.assertNotNull(cm);
    cm = consumer2.receive(5000);
    Assert.assertNotNull(cm);
    cm = consumer3.receive(5000);
    Assert.assertNotNull(cm);
    session.close();
  }
  @Test
  public void testStopStartConsumerSyncReceive() throws Exception {
    ClientSessionFactory sf = createSessionFactory(locator);

    final ClientSession session = sf.createSession(false, true, true);

    session.createQueue(QUEUE, QUEUE, null, false);

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(session, "m" + i);
      message.putIntProperty(new SimpleString("i"), i);
      producer.send(message);
    }

    final ClientConsumer consumer = session.createConsumer(QUEUE);

    session.start();

    for (int i = 0; i < numMessages / 2; i++) {
      ClientMessage cm = consumer.receive(5000);
      Assert.assertNotNull(cm);
      cm.acknowledge();
    }
    session.stop();
    long time = System.currentTimeMillis();
    ClientMessage cm = consumer.receive(1000);
    long taken = System.currentTimeMillis() - time;
    Assert.assertTrue(taken >= 1000);
    Assert.assertNull(cm);

    session.start();
    for (int i = 0; i < numMessages / 2; i++) {
      cm = consumer.receive(5000);
      Assert.assertNotNull(cm);
      cm.acknowledge();
    }

    session.close();
  }
  private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue)
      throws Exception {
    ClientSession session = sf.createSession(false, true, true);

    if (createQueue) {
      session.createQueue(ADDRESS, ADDRESS, null, false);
    }

    ClientProducer producer = session.createProducer(ADDRESS);

    final int numMessages = 1000;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message =
          session.createMessage(
              ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1);
      message.putIntProperty(new SimpleString("count"), i);
      message.getBodyBuffer().writeString("aardvarks");
      producer.send(message);
    }

    ClientConsumer consumer = session.createConsumer(ADDRESS);

    session.start();

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message2 = consumer.receive();

      assertEquals("aardvarks", message2.getBodyBuffer().readString());

      assertEquals(i, message2.getObjectProperty(new SimpleString("count")));

      message2.acknowledge();
    }

    ClientMessage message3 = consumer.receiveImmediate();

    assertNull(message3);

    return session;
  }
  @Test
  public void testConsumerBrowserWithSelector() throws Exception {

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = sf.createSession(false, true, true);

    session.createQueue(QUEUE, QUEUE, null, false);

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(session, "m" + i);
      message.putIntProperty(new SimpleString("x"), i);
      producer.send(message);
    }

    ClientConsumer consumer = session.createConsumer(QUEUE, new SimpleString("x >= 50"), true);

    for (int i = 50; i < numMessages; i++) {
      ClientMessage message2 = consumer.receive(1000);

      Assert.assertEquals("m" + i, message2.getBodyBuffer().readString());
    }

    consumer.close();

    consumer = session.createConsumer(QUEUE, null, true);

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message2 = consumer.receive(1000);

      Assert.assertEquals("m" + i, message2.getBodyBuffer().readString());
    }

    consumer.close();

    session.close();
  }
  @Test
  public void testBrowseWithZeroConsumerWindowSize() throws Exception {
    locator.setConsumerWindowSize(0);

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = sf.createSession(false, true, true);

    session.createQueue(QUEUE, QUEUE, null, false);

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    byte[] bytes = new byte[240];

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = session.createMessage(false);

      message.getBodyBuffer().writeBytes(bytes);

      message.putIntProperty("foo", i);

      producer.send(message);
    }

    // Create a normal non browsing consumer
    session.createConsumer(QUEUE);

    session.start();

    ClientConsumer browser = session.createConsumer(QUEUE, true);

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message2 = browser.receive(1000);

      assertEquals(i, message2.getIntProperty("foo").intValue());
    }

    session.close();
  }
  public void sendMessages(final int start, final int end) throws Exception {
    try (ClientSession session = factory.createSession(false, false)) {

      try {
        session.createQueue(QUEUE, QUEUE, true);
      } catch (Exception ignored) {
      }

      ClientProducer prod = session.createProducer(QUEUE);

      for (int i = start; i < end; i++) {
        ClientMessage msg = session.createMessage(true);
        msg.putIntProperty(new SimpleString("key"), i);
        msg.getBodyBuffer().writeUTF("message " + i);
        prod.send(msg);
      }

      session.commit();
      session.close();
      // server.stop(); -- this test was not supposed to stop the server, it should crash
    }
  }
  @Test
  public void testMessageProperties() throws Exception {
    ClientSession session = basicSetUp();

    session.createQueue(QUEUE_NAME, QUEUE_NAME, true);

    ClientProducer producer = session.createProducer(QUEUE_NAME);

    StringBuilder international = new StringBuilder();
    for (char x = 800; x < 1200; x++) {
      international.append(x);
    }

    String special = "\"<>'&";

    for (int i = 0; i < 5; i++) {
      ClientMessage msg = session.createMessage(true);
      msg.getBodyBuffer().writeString("Bob the giant pig " + i);
      msg.putBooleanProperty("myBooleanProperty", Boolean.TRUE);
      msg.putByteProperty("myByteProperty", new Byte("0"));
      msg.putBytesProperty("myBytesProperty", new byte[] {0, 1, 2, 3, 4});
      msg.putDoubleProperty("myDoubleProperty", i * 1.6);
      msg.putFloatProperty("myFloatProperty", i * 2.5F);
      msg.putIntProperty("myIntProperty", i);
      msg.putLongProperty("myLongProperty", Long.MAX_VALUE - i);
      msg.putObjectProperty("myObjectProperty", i);
      msg.putObjectProperty("myNullObjectProperty", null);
      msg.putShortProperty("myShortProperty", new Integer(i).shortValue());
      msg.putStringProperty("myStringProperty", "myStringPropertyValue_" + i);
      msg.putStringProperty("myNullStringProperty", null);
      msg.putStringProperty("myNonAsciiStringProperty", international.toString());
      msg.putStringProperty("mySpecialCharacters", special);
      msg.putStringProperty(
          new SimpleString("mySimpleStringProperty"),
          new SimpleString("mySimpleStringPropertyValue_" + i));
      msg.putStringProperty(new SimpleString("myNullSimpleStringProperty"), null);
      producer.send(msg);
    }

    session.close();
    locator.close();
    server.stop();

    ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();
    XmlDataExporter xmlDataExporter = new XmlDataExporter();
    xmlDataExporter.process(
        xmlOutputStream,
        server.getConfiguration().getBindingsDirectory(),
        server.getConfiguration().getJournalDirectory(),
        server.getConfiguration().getPagingDirectory(),
        server.getConfiguration().getLargeMessagesDirectory());
    System.out.print(new String(xmlOutputStream.toByteArray()));

    clearDataRecreateServerDirs();
    server.start();
    locator = createInVMNonHALocator();
    factory = createSessionFactory(locator);
    session = factory.createSession(false, true, true);

    ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(xmlOutputStream.toByteArray());
    XmlDataImporter xmlDataImporter = new XmlDataImporter();
    xmlDataImporter.process(xmlInputStream, session);
    ClientConsumer consumer = session.createConsumer(QUEUE_NAME);
    session.start();

    for (int i = 0; i < 5; i++) {
      ClientMessage msg = consumer.receive(CONSUMER_TIMEOUT);
      byte[] body = new byte[msg.getBodySize()];
      msg.getBodyBuffer().readBytes(body);
      assertTrue(new String(body).contains("Bob the giant pig " + i));
      assertEquals(msg.getBooleanProperty("myBooleanProperty"), Boolean.TRUE);
      assertEquals(msg.getByteProperty("myByteProperty"), new Byte("0"));
      byte[] bytes = msg.getBytesProperty("myBytesProperty");
      for (int j = 0; j < 5; j++) {
        assertEquals(j, bytes[j]);
      }
      assertEquals(i * 1.6, msg.getDoubleProperty("myDoubleProperty"), 0.000001);
      assertEquals(i * 2.5F, msg.getFloatProperty("myFloatProperty"), 0.000001);
      assertEquals(i, msg.getIntProperty("myIntProperty").intValue());
      assertEquals(Long.MAX_VALUE - i, msg.getLongProperty("myLongProperty").longValue());
      assertEquals(i, msg.getObjectProperty("myObjectProperty"));
      assertEquals(null, msg.getObjectProperty("myNullObjectProperty"));
      assertEquals(
          new Integer(i).shortValue(), msg.getShortProperty("myShortProperty").shortValue());
      assertEquals("myStringPropertyValue_" + i, msg.getStringProperty("myStringProperty"));
      assertEquals(null, msg.getStringProperty("myNullStringProperty"));
      assertEquals(international.toString(), msg.getStringProperty("myNonAsciiStringProperty"));
      assertEquals(special, msg.getStringProperty("mySpecialCharacters"));
      assertEquals(
          new SimpleString("mySimpleStringPropertyValue_" + i),
          msg.getSimpleStringProperty(new SimpleString("mySimpleStringProperty")));
      assertEquals(
          null, msg.getSimpleStringProperty(new SimpleString("myNullSimpleStringProperty")));
    }
  }
  private void doTestTransactional(final TestRunner runner) throws Throwable {
    // For duplication detection
    int executionId = 0;

    while (!runner.isFailed()) {
      ClientSession session = null;

      executionId++;

      log.info("#test doTestTransactional starting now. Execution " + executionId);

      try {

        boolean retry = false;

        final int numMessages = 1000;

        session = sf.createSession(false, false);

        listener = new CountDownSessionFailureListener(session);
        session.addFailureListener(listener);

        do {
          try {
            ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);

            for (int i = 0; i < numMessages; i++) {
              ClientMessage message = session.createMessage(true);

              message.getBodyBuffer().writeString("message" + i);

              message.putIntProperty("counter", i);

              message.putStringProperty(
                  Message.HDR_DUPLICATE_DETECTION_ID,
                  new SimpleString("id:" + i + ",exec:" + executionId));

              addPayload(message);

              if (log.isDebugEnabled()) {
                log.debug("Sending message " + message);
              }

              producer.send(message);
            }

            log.debug("Sending commit");
            session.commit();

            retry = false;
          } catch (ActiveMQDuplicateIdException die) {
            logAndSystemOut("#test duplicate id rejected on sending");
            break;
          } catch (ActiveMQTransactionRolledBackException trbe) {
            log.info("#test transaction rollback retrying on sending");
            // OK
            retry = true;
          } catch (ActiveMQUnBlockedException ube) {
            log.info("#test transaction rollback retrying on sending");
            // OK
            retry = true;
          } catch (ActiveMQTransactionOutcomeUnknownException toue) {
            log.info("#test transaction rollback retrying on sending");
            // OK
            retry = true;
          } catch (ActiveMQException e) {
            log.info("#test Exception " + e, e);
            throw e;
          }
        } while (retry);

        logAndSystemOut("#test Finished sending, starting consumption now");

        boolean blocked = false;

        retry = false;

        ClientConsumer consumer = null;
        do {
          ArrayList<Integer> msgs = new ArrayList<>();
          try {
            if (consumer == null) {
              consumer = session.createConsumer(FailoverTestBase.ADDRESS);
              session.start();
            }

            for (int i = 0; i < numMessages; i++) {
              if (log.isDebugEnabled()) {
                log.debug("Consumer receiving message " + i);
              }
              ClientMessage message = consumer.receive(10000);
              if (message == null) {
                break;
              }

              if (log.isDebugEnabled()) {
                log.debug("Received message " + message);
              }

              int count = message.getIntProperty("counter");

              if (count != i) {
                log.warn("count was received out of order, " + count + "!=" + i);
              }

              msgs.add(count);

              message.acknowledge();
            }

            log.info("#test commit");
            try {
              session.commit();
            } catch (ActiveMQTransactionRolledBackException trbe) {
              // we know the tx has been rolled back so we just consume again
              retry = true;
              continue;
            } catch (ActiveMQException e) {
              // This could eventually happen
              // We will get rid of this when we implement 2 phase commit on failover
              log.warn("exception during commit, it will be ignored for now" + e.getMessage(), e);
            }

            try {
              if (blocked) {
                assertTrue(
                    "msgs.size is expected to be 0 or "
                        + numMessages
                        + " but it was "
                        + msgs.size(),
                    msgs.size() == 0 || msgs.size() == numMessages);
              } else {
                assertTrue(
                    "msgs.size is expected to be " + numMessages + " but it was " + msgs.size(),
                    msgs.size() == numMessages);
              }
            } catch (Throwable e) {
              log.info(threadDump("Thread dump, messagesReceived = " + msgs.size()));
              logAndSystemOut(e.getMessage() + " messages received");
              for (Integer msg : msgs) {
                logAndSystemOut(msg.toString());
              }
              throw e;
            }

            int i = 0;
            for (Integer msg : msgs) {
              assertEquals(i++, (int) msg);
            }

            retry = false;
            blocked = false;
          } catch (ActiveMQTransactionRolledBackException trbe) {
            logAndSystemOut("Transaction rolled back with " + msgs.size(), trbe);
            // TODO: https://jira.jboss.org/jira/browse/HORNETQ-369
            // ATM RolledBack exception is being called with the transaction is committed.
            // the test will fail if you remove this next line
            blocked = true;
            retry = true;
          } catch (ActiveMQTransactionOutcomeUnknownException tou) {
            logAndSystemOut("Transaction rolled back with " + msgs.size(), tou);
            // TODO: https://jira.jboss.org/jira/browse/HORNETQ-369
            // ATM RolledBack exception is being called with the transaction is committed.
            // the test will fail if you remove this next line
            blocked = true;
            retry = true;
          } catch (ActiveMQUnBlockedException ube) {
            logAndSystemOut("Unblocked with " + msgs.size(), ube);
            // TODO: https://jira.jboss.org/jira/browse/HORNETQ-369
            // This part of the test is never being called.
            blocked = true;
            retry = true;
          } catch (ActiveMQException e) {
            logAndSystemOut(e.getMessage(), e);
            throw e;
          }
        } while (retry);
      } finally {
        if (session != null) {
          session.close();
        }
      }

      listener = null;
    }
  }
  private void doTestNonTransactional(final TestRunner runner) throws Exception {
    while (!runner.isFailed()) {
      AsynchronousFailoverTest.log.info("looping");

      ClientSession session = sf.createSession(true, true, 0);

      listener = new CountDownSessionFailureListener(session);

      session.addFailureListener(listener);

      ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);

      final int numMessages = 1000;

      for (int i = 0; i < numMessages; i++) {
        boolean retry = false;
        do {
          try {
            ClientMessage message = session.createMessage(true);

            message.getBodyBuffer().writeString("message" + i);

            message.putIntProperty("counter", i);

            addPayload(message);

            producer.send(message);

            retry = false;
          } catch (ActiveMQUnBlockedException ube) {
            AsynchronousFailoverTest.log.info("exception when sending message with counter " + i);

            ube.printStackTrace();

            retry = true;

          } catch (ActiveMQException e) {
            fail("Invalid Exception type:" + e.getType());
          }
        } while (retry);
      }

      // create the consumer with retry if failover occurs during createConsumer call
      ClientConsumer consumer = null;
      boolean retry = false;
      do {
        try {
          consumer = session.createConsumer(FailoverTestBase.ADDRESS);

          retry = false;
        } catch (ActiveMQUnBlockedException ube) {
          AsynchronousFailoverTest.log.info("exception when creating consumer");

          retry = true;

        } catch (ActiveMQException e) {
          fail("Invalid Exception type:" + e.getType());
        }
      } while (retry);

      session.start();

      List<Integer> counts = new ArrayList<>(1000);
      int lastCount = -1;
      boolean counterGap = false;
      while (true) {
        ClientMessage message = consumer.receive(500);

        if (message == null) {
          break;
        }

        // messages must remain ordered but there could be a "jump" if messages
        // are missing or duplicated
        int count = message.getIntProperty("counter");
        counts.add(count);
        if (count != lastCount + 1) {
          if (counterGap) {
            Assert.fail("got another counter gap at " + count + ": " + counts);
          } else {
            if (lastCount != -1) {
              AsynchronousFailoverTest.log.info("got first counter gap at " + count);
              counterGap = true;
            }
          }
        }

        lastCount = count;

        message.acknowledge();
      }

      session.close();

      this.listener = null;
    }
  }
  protected void sendCrashReceive() throws Exception {
    ServerLocator[] locators = new ServerLocator[liveServers.size()];
    try {
      for (int i = 0; i < locators.length; i++) {
        locators[i] = getServerLocator(i);
      }

      ClientSessionFactory[] factories = new ClientSessionFactory[liveServers.size()];
      for (int i = 0; i < factories.length; i++) {
        factories[i] = createSessionFactory(locators[i]);
      }

      ClientSession[] sessions = new ClientSession[liveServers.size()];
      for (int i = 0; i < factories.length; i++) {
        sessions[i] = createSession(factories[i], true, true);
        sessions[i].createQueue(ADDRESS, ADDRESS, null, true);
      }

      // make sure bindings are ready before sending messages
      for (int i = 0; i < liveServers.size(); i++) {
        this.waitForBindings(liveServers.get(i).getServer(), ADDRESS.toString(), true, 1, 0, 2000);
        this.waitForBindings(liveServers.get(i).getServer(), ADDRESS.toString(), false, 1, 0, 2000);
      }

      ClientProducer producer = sessions[0].createProducer(ADDRESS);

      for (int i = 0; i < liveServers.size() * 100; i++) {
        ClientMessage message = sessions[0].createMessage(true);

        setBody(i, message);

        message.putIntProperty("counter", i);

        producer.send(message);
      }

      producer.close();

      for (TestableServer liveServer : liveServers) {
        waitForDistribution(ADDRESS, liveServer.getServer(), 100);
      }

      for (TestableServer liveServer : liveServers) {
        liveServer.crash();
      }
      ClientConsumer[] consumers = new ClientConsumer[liveServers.size()];
      for (int i = 0; i < factories.length; i++) {
        consumers[i] = sessions[i].createConsumer(ADDRESS);
        sessions[i].start();
      }

      for (int i = 0; i < 100; i++) {
        for (ClientConsumer consumer : consumers) {
          ClientMessage message = consumer.receive(1000);
          assertNotNull("expecting durable msg " + i, message);
          message.acknowledge();
        }
      }
    } finally {
      for (ServerLocator locator : locators) {
        if (locator != null) {
          try {
            locator.close();
          } catch (Exception e) {
            // ignore
          }
        }
      }
    }
  }
  @Test
  public void testSetUnsetResetMessageHandler() throws Exception {
    final ClientSession session = sf.createSession(false, true, true);

    session.createQueue(QUEUE, QUEUE, null, false);

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(session, "m" + i);
      message.putIntProperty(new SimpleString("i"), i);
      producer.send(message);
    }

    final ClientConsumer consumer = session.createConsumer(QUEUE);

    session.start();

    CountDownLatch latch = new CountDownLatch(50);

    // Message should be in consumer

    class MyHandler implements MessageHandler {

      int messageReceived = 0;

      boolean failed;

      boolean started = true;

      private final CountDownLatch latch;

      MyHandler(final CountDownLatch latch) {
        this.latch = latch;
      }

      @Override
      public void onMessage(final ClientMessage message) {

        try {
          if (!started) {
            failed = true;
          }
          messageReceived++;
          latch.countDown();

          if (latch.getCount() == 0) {

            message.acknowledge();
            started = false;
            consumer.setMessageHandler(null);
          }

        } catch (Exception e) {
        }
      }
    }

    MyHandler handler = new MyHandler(latch);

    consumer.setMessageHandler(handler);

    waitForLatch(latch);

    Thread.sleep(100);

    Assert.assertFalse(handler.failed);

    // Make sure no exceptions were thrown from onMessage
    Assert.assertNull(consumer.getLastException());
    consumer.setMessageHandler(null);
    ClientMessage cm = consumer.receiveImmediate();
    Assert.assertNotNull(cm);
    latch = new CountDownLatch(49);
    handler = new MyHandler(latch);
    consumer.setMessageHandler(handler);
    session.start();
    Assert.assertTrue(
        "message received " + handler.messageReceived, latch.await(5, TimeUnit.SECONDS));

    Thread.sleep(100);

    Assert.assertFalse(handler.failed);
    Assert.assertNull(consumer.getLastException());
    session.close();
  }
  @Test
  public void testStopStartConsumerAsyncSync() throws Exception {
    ClientSessionFactory sf = createSessionFactory(locator);

    final ClientSession session = sf.createSession(false, true, true);

    session.createQueue(QUEUE, QUEUE, null, false);

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(session, "m" + i);
      message.putIntProperty(new SimpleString("i"), i);
      producer.send(message);
    }

    final ClientConsumer consumer = session.createConsumer(QUEUE);

    session.start();

    final CountDownLatch latch = new CountDownLatch(10);

    // Message should be in consumer

    class MyHandler implements MessageHandler {

      boolean failed;

      boolean started = true;

      @Override
      public void onMessage(final ClientMessage message) {

        try {
          if (!started) {
            failed = true;
          }

          latch.countDown();

          if (latch.getCount() == 0) {

            message.acknowledge();
            started = false;
            consumer.setMessageHandler(null);
          }

        } catch (Exception e) {
        }
      }
    }

    MyHandler handler = new MyHandler();

    consumer.setMessageHandler(handler);

    waitForLatch(latch);

    try {
      session.stop();
    } catch (Exception e) {
      SessionStopStartTest.log.warn(e.getMessage(), e);
      throw e;
    }

    Assert.assertFalse(handler.failed);

    // Make sure no exceptions were thrown from onMessage
    Assert.assertNull(consumer.getLastException());
    consumer.setMessageHandler(null);
    session.start();
    for (int i = 0; i < 90; i++) {
      ClientMessage msg = consumer.receive(1000);
      if (msg == null) {
        System.out.println("ClientConsumerTest.testStopConsumer");
      }
      Assert.assertNotNull("message " + i, msg);
      msg.acknowledge();
    }

    Assert.assertNull(consumer.receiveImmediate());

    session.close();
  }
  @Test
  public void testDeployWithFilter() throws Exception {
    final String testAddress = "testAddress";

    final String queueName1 = "queue1";

    final String filter = "cheese='camembert'";

    CoreQueueConfiguration queue1 =
        new CoreQueueConfiguration()
            .setAddress(testAddress)
            .setName(queueName1)
            .setFilterString(filter)
            .setDurable(false);

    configuration.addQueueConfiguration(queue1);

    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration, false));

    server.start();

    ServerLocator locator = createInVMNonHALocator();

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = addClientSession(sf.createSession(false, true, true));

    ClientProducer producer = session.createProducer(new SimpleString(testAddress));

    final SimpleString propKey = new SimpleString("testkey");

    final int numMessages = 1;

    PredefinedQueueTest.log.info("sending messages");

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = session.createMessage(true);

      message.putStringProperty(new SimpleString("cheese"), new SimpleString("camembert"));

      message.putIntProperty(propKey, i);

      producer.send(message);
    }

    session.start();

    ClientConsumer consumer1 = session.createConsumer(queueName1);

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = consumer1.receive(200);
      Assert.assertNotNull(message);
      Assert.assertEquals(i, message.getObjectProperty(propKey));
      message.acknowledge();
    }

    Assert.assertNull(consumer1.receiveImmediate());

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = session.createMessage(true);

      message.putStringProperty(new SimpleString("cheese"), new SimpleString("roquefort"));

      message.putIntProperty(propKey, i);

      producer.send(message);
    }

    Assert.assertNull(consumer1.receiveImmediate());
  }
  @Test
  public void testDurableNonDurable() throws Exception {
    final String testAddress = "testAddress";

    final String queueName1 = "queue1";

    final String queueName2 = "queue2";

    CoreQueueConfiguration queue1 =
        new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1).setDurable(false);

    CoreQueueConfiguration queue2 =
        new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2);

    List<CoreQueueConfiguration> queueConfs = new ArrayList<CoreQueueConfiguration>();

    queueConfs.add(queue1);
    queueConfs.add(queue2);

    configuration.addQueueConfiguration(queue1).addQueueConfiguration(queue2);

    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration));

    server.start();

    ServerLocator locator = createInVMNonHALocator();

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = addClientSession(sf.createSession(false, true, true));

    ClientProducer producer = session.createProducer(new SimpleString(testAddress));

    final SimpleString propKey = new SimpleString("testkey");

    final int numMessages = 1;

    PredefinedQueueTest.log.info("sending messages");

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = session.createMessage(true);

      message.putIntProperty(propKey, i);

      producer.send(message);
    }

    session.close();

    PredefinedQueueTest.log.info("stopping");

    sf.close();

    server.stop();

    server.start();

    sf = createSessionFactory(locator);

    session = addClientSession(sf.createSession(false, true, true));

    session.start();

    ClientConsumer consumer1 = session.createConsumer(queueName1);

    ClientConsumer consumer2 = session.createConsumer(queueName2);

    ClientMessage message = consumer1.receiveImmediate();

    Assert.assertNull(message);

    for (int i = 0; i < numMessages; i++) {
      message = consumer2.receive(200);
      Assert.assertNotNull(message);
      Assert.assertEquals(i, message.getObjectProperty(propKey));
      message.acknowledge();
    }

    Assert.assertNull(consumer1.receiveImmediate());
    Assert.assertNull(consumer2.receiveImmediate());
  }
  @Test
  public void testDeployPreexistingQueues() throws Exception {
    final String testAddress = "testAddress";

    final String queueName1 = "queue1";

    final String queueName2 = "queue2";

    final String queueName3 = "queue3";

    ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(configuration));

    server.start();

    ServerLocator locator = createInVMNonHALocator();

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = addClientSession(sf.createSession(false, true, true));

    session.createQueue(testAddress, queueName1, null, true);

    session.createQueue(testAddress, queueName2, null, true);

    session.createQueue(testAddress, queueName3, null, true);

    session.close();

    sf.close();

    server.stop();

    CoreQueueConfiguration queue1 =
        new CoreQueueConfiguration().setAddress(testAddress).setName(queueName1);

    CoreQueueConfiguration queue2 =
        new CoreQueueConfiguration().setAddress(testAddress).setName(queueName2);

    CoreQueueConfiguration queue3 =
        new CoreQueueConfiguration().setAddress(testAddress).setName(queueName3);

    configuration
        .addQueueConfiguration(queue1)
        .addQueueConfiguration(queue2)
        .addQueueConfiguration(queue3);

    server.start();

    sf = createSessionFactory(locator);

    session = addClientSession(sf.createSession(false, true, true));

    session.start();

    ClientProducer producer = session.createProducer(new SimpleString(testAddress));

    ClientConsumer consumer1 = session.createConsumer(queueName1);

    ClientConsumer consumer2 = session.createConsumer(queueName2);

    ClientConsumer consumer3 = session.createConsumer(queueName3);

    final int numMessages = 10;

    final SimpleString propKey = new SimpleString("testkey");

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = session.createMessage(false);

      message.putIntProperty(propKey, i);

      producer.send(message);
    }

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = consumer1.receive(200);
      Assert.assertNotNull(message);
      Assert.assertEquals(i, message.getObjectProperty(propKey));
      message.acknowledge();

      message = consumer2.receive(200);
      Assert.assertNotNull(message);
      Assert.assertEquals(i, message.getObjectProperty(propKey));
      message.acknowledge();

      message = consumer3.receive(200);
      Assert.assertNotNull(message);
      Assert.assertEquals(i, message.getObjectProperty(propKey));
      message.acknowledge();
    }

    Assert.assertNull(consumer1.receiveImmediate());
    Assert.assertNull(consumer2.receiveImmediate());
    Assert.assertNull(consumer3.receiveImmediate());
  }