@Test
  public void testReceiveImmediate() throws Exception {

    // forces perfect round robin
    locator.setConsumerWindowSize(1);
    ClientSessionFactory cf = createSessionFactory(locator);
    ClientSession sendSession = cf.createSession(false, true, true);
    ClientProducer cp = sendSession.createProducer(addressA);
    ClientSession session = cf.createSession(false, true, true);
    session.createQueue(addressA, queueA, false);
    ClientConsumer cc = session.createConsumer(queueA);
    ClientConsumer cc2 = session.createConsumer(queueA);
    session.start();
    cp.send(sendSession.createMessage(false));
    cp.send(sendSession.createMessage(false));
    cp.send(sendSession.createMessage(false));
    sendSession.commit();

    Assert.assertNotNull(cc2.receive(5000));
    Assert.assertNotNull(cc.receive(5000));
    if (cc.receiveImmediate() == null) {
      Assert.assertNotNull(cc2.receiveImmediate());
    }
    session.close();
    sendSession.close();
  }
  @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();
  }
  public synchronized void handleLargeMessage(
      final ClientLargeMessageInternal clientLargeMessage, long largeMessageSize) throws Exception {
    if (closing) {
      // This is ok - we just ignore the message
      return;
    }

    // Flow control for the first packet, we will have others
    File largeMessageCache = null;

    if (session.isCacheLargeMessageClient()) {
      largeMessageCache =
          File.createTempFile(
              "tmp-large-message-" + clientLargeMessage.getMessageID() + "-", ".tmp");
      largeMessageCache.deleteOnExit();
    }

    ClientSessionFactory sf = session.getSessionFactory();
    ServerLocator locator = sf.getServerLocator();
    long callTimeout = locator.getCallTimeout();

    currentLargeMessageController =
        new LargeMessageControllerImpl(this, largeMessageSize, callTimeout, largeMessageCache);

    if (clientLargeMessage.isCompressed()) {
      clientLargeMessage.setLargeMessageController(
          new CompressedLargeMessageControllerImpl(currentLargeMessageController));
    } else {
      clientLargeMessage.setLargeMessageController(currentLargeMessageController);
    }

    handleRegularMessage(clientLargeMessage);
  }
  @Test
  public void testConsumerMultipleBrowser() 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);
      producer.send(message);
    }

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

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message2 = consumer.receive(1000);
      Assert.assertEquals("m" + i, message2.getBodyBuffer().readString());
      message2 = consumer2.receive(1000);
      Assert.assertEquals("m" + i, message2.getBodyBuffer().readString());
      message2 = consumer3.receive(1000);
      Assert.assertEquals("m" + i, message2.getBodyBuffer().readString());
    }

    session.close();
  }
  @Test
  public void testCounter() throws Exception {
    ClientSessionFactory sf = createSessionFactory(sl);
    ClientSession session = sf.createSession();

    try {
      Queue queue =
          server.createQueue(new SimpleString("A1"), new SimpleString("A1"), null, true, false);

      PageSubscriptionCounter counter = locateCounter(queue);

      StorageManager storage = server.getStorageManager();

      Transaction tx = new TransactionImpl(server.getStorageManager());

      counter.increment(tx, 1);

      assertEquals(0, counter.getValue());

      tx.commit();

      storage.waitOnOperations();

      assertEquals(1, counter.getValue());
    } finally {
      sf.close();
      session.close();
    }
  }
  /**
   * This method deals with messages arrived as regular message but its contents are compressed.
   * Such messages come from message senders who are configured to compress large messages, and if
   * some of the messages are compressed below the min-large-message-size limit, they are sent as
   * regular messages. <br>
   * However when decompressing the message, we are not sure how large the message could be.. for
   * that reason we fake a large message controller that will deal with the message as it was a
   * large message <br>
   * Say that you sent a 1G message full of spaces. That could be just bellow 100K compressed but
   * you wouldn't have enough memory to decompress it
   */
  private void handleCompressedMessage(final ClientMessageInternal clMessage) throws Exception {
    ClientLargeMessageImpl largeMessage = new ClientLargeMessageImpl();
    largeMessage.retrieveExistingData(clMessage);

    File largeMessageCache = null;

    if (session.isCacheLargeMessageClient()) {
      largeMessageCache =
          File.createTempFile("tmp-large-message-" + largeMessage.getMessageID() + "-", ".tmp");
      largeMessageCache.deleteOnExit();
    }

    ClientSessionFactory sf = session.getSessionFactory();
    ServerLocator locator = sf.getServerLocator();
    long callTimeout = locator.getCallTimeout();

    currentLargeMessageController =
        new LargeMessageControllerImpl(
            this, largeMessage.getLargeMessageSize(), callTimeout, largeMessageCache);
    currentLargeMessageController.setLocal(true);

    // sets the packet
    ActiveMQBuffer qbuff = clMessage.getBodyBuffer();
    int bytesToRead = qbuff.writerIndex() - qbuff.readerIndex();
    final byte[] body = qbuff.readBytes(bytesToRead).toByteBuffer().array();

    largeMessage.setLargeMessageController(
        new CompressedLargeMessageControllerImpl(currentLargeMessageController));
    currentLargeMessageController.addPacket(body, body.length, false);

    handleRegularMessage(largeMessage);
  }
  @Test
  public void testConsumerBrowserWithStringSelector() 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);
      if (i % 2 == 0) {
        message.putStringProperty(new SimpleString("color"), new SimpleString("RED"));
      }
      producer.send(message);
    }

    ClientConsumer consumer =
        session.createConsumer(QUEUE, new SimpleString("color = 'RED'"), true);

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

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

    session.close();
  }
  @Test
  public void testConsumerBrowserMessageAckDoesNothing() 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);
      producer.send(message);
    }

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

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

      message2.acknowledge();

      Assert.assertEquals("m" + i, message2.getBodyBuffer().readString());
    }
    // 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, getMessageCount(((Queue) server.getPostOffice().getBinding(QUEUE).getBindable())));

    session.close();
  }
  @Test
  public void testBody2() throws Exception {
    final String QUEUE_NAME = "A1";
    ActiveMQServer server = createServer(true);
    server.start();
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory factory = locator.createSessionFactory();
    ClientSession session = factory.createSession(false, true, true);

    session.createQueue(QUEUE_NAME, QUEUE_NAME, true);

    ClientProducer producer = session.createProducer(QUEUE_NAME);

    ClientMessage msg = session.createMessage(true);
    byte[] bodyTst = new byte[10];
    for (int i = 0; i < 10; i++) {
      bodyTst[i] = (byte) (i + 1);
    }
    msg.getBodyBuffer().writeBytes(bodyTst);
    assertEquals(bodyTst.length, msg.getBodySize());
    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 = locator.createSessionFactory();
    session = factory.createSession(false, false, true);
    ClientSession managementSession = factory.createSession(false, true, true);

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

    msg = consumer.receive(CONSUMER_TIMEOUT);
    assertNotNull(msg);
    assertEquals(msg.getBodySize(), bodyTst.length);
    byte[] bodyRead = new byte[bodyTst.length];
    msg.getBodyBuffer().readBytes(bodyRead);
    assertEqualsByteArrays(bodyTst, bodyRead);

    session.close();
    locator.close();
    server.stop();
  }
  @Test
  public void testCleanupCounterNonPersistent() throws Exception {
    ClientSessionFactory sf = createSessionFactory(sl);
    ClientSession session = sf.createSession();

    try {
      Queue queue =
          server.createQueue(new SimpleString("A1"), new SimpleString("A1"), null, true, false);

      PageSubscriptionCounter counter = locateCounter(queue);

      ((PageSubscriptionCounterImpl) counter).setPersistent(false);

      StorageManager storage = server.getStorageManager();

      Transaction tx = new TransactionImpl(server.getStorageManager());

      for (int i = 0; i < 2100; i++) {

        counter.increment(tx, 1);

        if (i % 200 == 0) {
          tx.commit();

          storage.waitOnOperations();

          assertEquals(i + 1, counter.getValue());

          tx = new TransactionImpl(server.getStorageManager());
        }
      }

      tx.commit();

      storage.waitOnOperations();

      assertEquals(2100, counter.getValue());

      server.stop();

      server = newActiveMQServer();

      server.start();

      queue = server.locateQueue(new SimpleString("A1"));

      assertNotNull(queue);

      counter = locateCounter(queue);

      assertEquals(0, counter.getValue());

    } finally {
      sf.close();
      session.close();
    }
  }
 @Override
 @Before
 public void setUp() throws Exception {
   super.setUp();
   server = addServer(ActiveMQServers.newActiveMQServer(createDefaultInVMConfig(), true));
   server.start();
   // then we create a client as normal
   locator = createInVMNonHALocator();
   locator.setMinLargeMessageSize(1024);
   ClientSessionFactory sessionFactory = createSessionFactory(locator);
   clientSession = addClientSession(sessionFactory.createSession(false, true, false));
 }
 private int getMessageEncodeSize(final SimpleString address) throws Exception {
   ServerLocator locator = createInVMNonHALocator();
   ClientSessionFactory cf = createSessionFactory(locator);
   ClientSession session = cf.createSession(false, true, true);
   ClientMessage message = session.createMessage(false);
   // we need to set the destination so we can calculate the encodesize correctly
   message.setAddress(address);
   int encodeSize = message.getEncodeSize();
   session.close();
   cf.close();
   return encodeSize;
 }
  private void doTestMultipleGroupingTXCommit() throws Exception {
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    ClientSession clientSession = sessionFactory.createSession(false, false, false);
    ClientProducer clientProducer = this.clientSession.createProducer(qName);
    clientSession.start();

    ClientConsumer consumer = clientSession.createConsumer(qName);
    ClientConsumer consumer2 = clientSession.createConsumer(qName);

    // Wait a bit otherwise consumers might be busy
    Thread.sleep(200);

    SimpleString groupId = new SimpleString("grp1");
    SimpleString groupId2 = new SimpleString("grp2");
    int numMessages = 100;
    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(clientSession, "m" + i);
      if (i % 2 == 0 || i == 0) {
        message.putStringProperty(Message.HDR_GROUP_ID, groupId);
      } else {
        message.putStringProperty(Message.HDR_GROUP_ID, groupId2);
      }
      clientProducer.send(message);
    }

    CountDownLatch latch = new CountDownLatch(numMessages);
    DummyMessageHandler dummyMessageHandler = new DummyMessageHandler(latch, true);
    consumer.setMessageHandler(dummyMessageHandler);
    DummyMessageHandler dummyMessageHandler2 = new DummyMessageHandler(latch, true);
    consumer2.setMessageHandler(dummyMessageHandler2);
    Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    clientSession.commit();
    Assert.assertEquals(dummyMessageHandler.list.size(), 50);
    int i = 0;
    for (ClientMessage message : dummyMessageHandler.list) {
      Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i);
      i += 2;
    }
    Assert.assertEquals(dummyMessageHandler2.list.size(), 50);
    i = 1;
    for (ClientMessage message : dummyMessageHandler2.list) {
      Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i);
      i += 2;
    }
    consumer.close();
    consumer2.close();
    consumer = this.clientSession.createConsumer(qName);
    Assert.assertNull(consumer.receiveImmediate());
    clientSession.close();
    locator.close();
  }
  @Test
  public void testLinkedListOrder() throws Exception {
    ServerLocator locator = createInVMNonHALocator();

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = sf.createSession();

    session.start();

    ClientProducer producer = session.createProducer("foo");

    ClientConsumer redConsumer = session.createConsumer("foo", "color='red'");

    ClientConsumer anyConsumer = session.createConsumer("foo");

    sendMessage(session, producer, "any", "msg1");

    sendMessage(session, producer, "any", "msg2");

    sendMessage(session, producer, "any", "msg3");

    sendMessage(session, producer, "red", "msgRed4");

    sendMessage(session, producer, "red", "msgRed5");

    readConsumer("anyConsumer", anyConsumer);

    readConsumer("anyConsumer", anyConsumer);

    log.info("### closing consumer ###");

    anyConsumer.close();

    readConsumer("redConsumer", redConsumer);

    readConsumer("redConsumer", redConsumer);

    log.info("### recreating consumer ###");

    anyConsumer = session.createConsumer("foo");

    session.start();

    readConsumer("anyConsumer", anyConsumer);

    session.close();

    sf.close();

    locator.close();
  }
  private void dotestMultipleGroupingXACommit() throws Exception {
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    ClientSession clientSession = sessionFactory.createSession(true, false, false);
    ClientProducer clientProducer = this.clientSession.createProducer(qName);
    ClientConsumer consumer = clientSession.createConsumer(qName);
    ClientConsumer consumer2 = clientSession.createConsumer(qName);
    clientSession.start();

    Xid xid = new XidImpl("bq".getBytes(), 4, "gtid".getBytes());
    clientSession.start(xid, XAResource.TMNOFLAGS);

    SimpleString groupId = new SimpleString("grp1");
    SimpleString groupId2 = new SimpleString("grp2");
    int numMessages = 100;
    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(clientSession, "m" + i);
      if (i % 2 == 0 || i == 0) {
        message.putStringProperty(Message.HDR_GROUP_ID, groupId);
      } else {
        message.putStringProperty(Message.HDR_GROUP_ID, groupId2);
      }
      clientProducer.send(message);
    }
    CountDownLatch latch = new CountDownLatch(numMessages);
    DummyMessageHandler dummyMessageHandler = new DummyMessageHandler(latch, true);
    consumer.setMessageHandler(dummyMessageHandler);
    DummyMessageHandler dummyMessageHandler2 = new DummyMessageHandler(latch, true);
    consumer2.setMessageHandler(dummyMessageHandler2);
    Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    clientSession.end(xid, XAResource.TMSUCCESS);
    clientSession.prepare(xid);
    clientSession.commit(xid, false);
    Assert.assertEquals(dummyMessageHandler.list.size(), 50);
    int i = 0;
    for (ClientMessage message : dummyMessageHandler.list) {
      Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i);
      i += 2;
    }
    Assert.assertEquals(dummyMessageHandler2.list.size(), 50);
    i = 1;
    for (ClientMessage message : dummyMessageHandler2.list) {
      Assert.assertEquals(message.getBodyBuffer().readString(), "m" + i);
      i += 2;
    }
    consumer.close();
    consumer2.close();
    consumer = this.clientSession.createConsumer(qName);
    Assert.assertNull(consumer.receiveImmediate());
    clientSession.close();
    locator.close();
  }
  @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 testBody() throws Exception {
    final String QUEUE_NAME = "A1";
    ActiveMQServer server = createServer(true);
    server.start();
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory factory = locator.createSessionFactory();
    ClientSession session = factory.createSession(false, true, true);

    session.createQueue(QUEUE_NAME, QUEUE_NAME, true);

    ClientProducer producer = session.createProducer(QUEUE_NAME);

    ClientMessage msg = session.createMessage(Message.TEXT_TYPE, true);
    msg.getBodyBuffer().writeString("bob123");
    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 = locator.createSessionFactory();
    session = factory.createSession(false, false, true);
    ClientSession managementSession = factory.createSession(false, true, true);

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

    msg = consumer.receive(CONSUMER_TIMEOUT);
    assertNotNull(msg);
    assertEquals("bob123", msg.getBodyBuffer().readString());

    session.close();
    locator.close();
    server.stop();
  }
  @Test
  public void testReceiveTimesoutCorrectly() throws Exception {

    ClientSessionFactory cf = createSessionFactory(locator);
    ClientSession session = cf.createSession(false, true, true);
    session.createQueue(addressA, queueA, false);
    ClientConsumer cc = session.createConsumer(queueA);
    session.start();
    long time = System.currentTimeMillis();
    cc.receive(1000);
    Assert.assertTrue(System.currentTimeMillis() - time >= 1000);
    session.close();
  }
 @Test
 public void testBasicReceive() throws Exception {
   ClientSessionFactory cf = createSessionFactory(locator);
   ClientSession sendSession = cf.createSession(false, true, true);
   ClientProducer cp = sendSession.createProducer(addressA);
   ClientSession session = cf.createSession(false, true, true);
   session.createQueue(addressA, queueA, false);
   ClientConsumer cc = session.createConsumer(queueA);
   session.start();
   cp.send(sendSession.createMessage(false));
   Assert.assertNotNull(cc.receive());
   session.close();
   sendSession.close();
 }
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    Configuration config = createDefaultInVMConfig().setJMXManagementEnabled(true);
    server = createServer(false, config);
    server.setMBeanServer(mbeanServer);
    server.start();

    ServerLocator locator = createInVMNonHALocator().setBlockOnNonDurableSend(true);
    ClientSessionFactory sf = createSessionFactory(locator);
    session = sf.createSession(false, true, false);
    session.start();
  }
  private void setupServer(final JournalType journalType) throws Exception {
    Configuration config =
        createDefaultNettyConfig()
            .setJournalType(journalType)
            .setJournalFileSize(ActiveMQDefaultConfiguration.getDefaultJournalFileSize())
            .setJournalMinFiles(ActiveMQDefaultConfiguration.getDefaultJournalMinFiles())
            .setJournalCompactMinFiles(2)
            .setJournalCompactPercentage(50);

    server = createServer(true, config);

    server.start();

    ServerLocator locator =
        createNettyNonHALocator()
            .setBlockOnDurableSend(false)
            .setBlockOnNonDurableSend(false)
            .setBlockOnAcknowledge(false);

    sf = createSessionFactory(locator);

    ClientSession sess = sf.createSession();

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

    sess.close();
    locator.close();
    locator = createInVMNonHALocator();
    sf = createSessionFactory(locator);
  }
  @Test
  public void testRestartJournal() throws Throwable {
    runExternalProcess(getTestDir(), 0, JournalCrashTest.FIRST_RUN);
    runExternalProcess(getTestDir(), JournalCrashTest.FIRST_RUN, JournalCrashTest.SECOND_RUN);
    runExternalProcess(getTestDir(), JournalCrashTest.SECOND_RUN, JournalCrashTest.THIRD_RUN);
    runExternalProcess(getTestDir(), JournalCrashTest.THIRD_RUN, JournalCrashTest.FOURTH_RUN);

    printJournal();

    startServer();

    try (ClientSession session = factory.createSession(true, true)) {

      ClientConsumer consumer = session.createConsumer(QUEUE);
      session.start();

      for (int i = 0; i < JournalCrashTest.FOURTH_RUN; i++) {
        ClientMessage msg = consumer.receive(5000);

        Assert.assertNotNull("Msg at " + i, msg);

        msg.acknowledge();

        Assert.assertEquals(i, msg.getObjectProperty(new SimpleString("key")));
      }
      session.close();
    }
  }
  @Test
  public void testJmsDestination() throws Exception {
    ClientSession session = basicSetUp();

    jmsServer.createQueue(
        true, "myQueue", null, true, "myQueueJndiBinding1", "myQueueJndiBinding2");
    jmsServer.createTopic(true, "myTopic", "myTopicJndiBinding1", "myTopicJndiBinding2");

    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);

    assertNotNull(namingContext.lookup("myQueueJndiBinding1"));
    assertNotNull(namingContext.lookup("myQueueJndiBinding2"));
    assertNotNull(namingContext.lookup("myTopicJndiBinding1"));
    assertNotNull(namingContext.lookup("myTopicJndiBinding2"));

    jmsServer.createConnectionFactory(
        "test-cf", false, JMSFactoryType.CF, Arrays.asList("in-vm1"), "test-cf");

    ConnectionFactory cf = (ConnectionFactory) namingContext.lookup("test-cf");
    Connection connection = cf.createConnection();
    Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer =
        jmsSession.createProducer((Destination) namingContext.lookup("myQueueJndiBinding1"));
    producer.send(jmsSession.createTextMessage());
    MessageConsumer consumer =
        jmsSession.createConsumer((Destination) namingContext.lookup("myQueueJndiBinding2"));
    connection.start();
    assertNotNull(consumer.receive(3000));

    consumer = jmsSession.createConsumer((Destination) namingContext.lookup("myTopicJndiBinding1"));
    producer = jmsSession.createProducer((Destination) namingContext.lookup("myTopicJndiBinding2"));
    producer.send(jmsSession.createTextMessage());
    assertNotNull(consumer.receive(3000));

    connection.close();
  }
  @Test
  public void testSECURITY_PERMISSION_VIOLATION() throws Exception {
    SimpleString queue = RandomUtil.randomSimpleString();
    SimpleString address = RandomUtil.randomSimpleString();

    // guest can not create queue
    Role role =
        new Role(
            "roleCanNotCreateQueue", true, true, false, true, false, true, true, true, true, true);
    Set<Role> roles = new HashSet<>();
    roles.add(role);
    server.getSecurityRepository().addMatch(address.toString(), roles);
    ActiveMQJAASSecurityManager securityManager =
        (ActiveMQJAASSecurityManager) server.getSecurityManager();
    securityManager.getConfiguration().addRole("guest", "roleCanNotCreateQueue");

    SecurityNotificationTest.flush(notifConsumer);

    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession guestSession = sf.createSession("guest", "guest", false, true, true, false, 1);

    try {
      guestSession.createQueue(address, queue, true);
      Assert.fail(
          "session creation must fail and a notification of security violation must be sent");
    } catch (Exception e) {
    }

    ClientMessage[] notifications = SecurityNotificationTest.consumeMessages(1, notifConsumer);
    Assert.assertEquals(
        SECURITY_PERMISSION_VIOLATION.toString(),
        notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString());
    Assert.assertEquals(
        "guest", notifications[0].getObjectProperty(ManagementHelper.HDR_USER).toString());
    Assert.assertEquals(
        address.toString(),
        notifications[0].getObjectProperty(ManagementHelper.HDR_ADDRESS).toString());
    Assert.assertEquals(
        CheckType.CREATE_DURABLE_QUEUE.toString(),
        notifications[0].getObjectProperty(ManagementHelper.HDR_CHECK_TYPE).toString());

    guestSession.close();
  }
  @Test
  public void testLoad() throws Throwable {
    ActiveMQServer server2 = createServer(true, false);

    server2.getConfiguration().setJournalFileSize(10 * 1024 * 1024);
    server2.getConfiguration().setJournalMinFiles(10);
    server2.getConfiguration().setJournalCompactMinFiles(3);
    server2.getConfiguration().setJournalCompactPercentage(50);

    for (int i = 0; i < 10; i++) {
      server2.start();

      ServerLocator locator =
          createInVMNonHALocator().setMinLargeMessageSize(1024 * 1024).setBlockOnDurableSend(false);

      ClientSessionFactory sf = createSessionFactory(locator);

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

      try {
        session.createQueue("slow-queue", "slow-queue");
      } catch (Exception ignored) {
      }

      session.start();
      ClientConsumer consumer = session.createConsumer("slow-queue");

      while (true) {
        System.out.println("Received message from previous");
        ClientMessage msg = consumer.receiveImmediate();
        if (msg == null) {
          break;
        }
        msg.acknowledge();
      }

      session.close();

      produceMessages(sf, 30000);

      server2.stop();
    }
  }
  @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();
  }
  @Test
  public void testReceiveOnClosedException() throws Exception {

    ClientSessionFactory cf = createSessionFactory(locator);
    ClientSession session = cf.createSession(false, true, true);
    session.createQueue(addressA, queueA, false);
    ClientConsumer cc = session.createConsumer(queueA);
    session.start();
    session.close();
    try {
      cc.receive();
      Assert.fail("should throw exception");
    } catch (ActiveMQObjectClosedException oce) {
      // ok
    } catch (ActiveMQException e) {
      Assert.fail("Invalid Exception type:" + e.getType());
    }
    session.close();
  }
  @Test
  public void testSECURITY_AUTHENTICATION_VIOLATION() throws Exception {
    String unknownUser = RandomUtil.randomString();

    SecurityNotificationTest.flush(notifConsumer);

    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sf = createSessionFactory(locator);

    try {
      sf.createSession(unknownUser, RandomUtil.randomString(), false, true, true, false, 1);
      Assert.fail("authentication must fail and a notification of security violation must be sent");
    } catch (Exception e) {
    }

    ClientMessage[] notifications = SecurityNotificationTest.consumeMessages(1, notifConsumer);
    Assert.assertEquals(
        SECURITY_AUTHENTICATION_VIOLATION.toString(),
        notifications[0].getObjectProperty(ManagementHelper.HDR_NOTIFICATION_TYPE).toString());
  }
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    server = createServer(false);

    server.start();
    ServerLocator locator = createInVMNonHALocator();

    ClientSessionFactory sf = createSessionFactory(locator);

    session = sf.createSession();

    session.start();
    session.createQueue("foo", RoutingType.ANYCAST, "foo");

    producer = session.createProducer("foo");
    consumer = session.createConsumer("foo", "animal='giraffe'");
  }
  @Test
  public void testSetMessageHandlerWithMessagesPending() throws Exception {
    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);
      producer.send(message);
    }

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

    session.start();

    Thread.sleep(100);

    // Message should be in consumer

    class MyHandler implements MessageHandler {

      @Override
      public void onMessage(final ClientMessage message) {
        try {
          Thread.sleep(10);

          message.acknowledge();
        } catch (Exception e) {
        }
      }
    }

    consumer.setMessageHandler(new MyHandler());

    // Let a few messages get processed
    Thread.sleep(100);

    // Now set null

    consumer.setMessageHandler(null);

    // Give a bit of time for some queued executors to run

    Thread.sleep(500);

    // Make sure no exceptions were thrown from onMessage
    Assert.assertNull(consumer.getLastException());

    session.close();
  }