@Test
 public void testBasicSend2times() throws Exception {
   SimpleString dla = new SimpleString("DLA");
   SimpleString qName = new SimpleString("q1");
   AddressSettings addressSettings =
       new AddressSettings().setMaxDeliveryAttempts(2).setDeadLetterAddress(dla);
   server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings);
   SimpleString dlq = new SimpleString("DLQ1");
   clientSession.createQueue(dla, dlq, null, false);
   clientSession.createQueue(qName, qName, null, false);
   ClientProducer producer = clientSession.createProducer(qName);
   producer.send(createTextMessage(clientSession, "heyho!"));
   clientSession.start();
   ClientConsumer clientConsumer = clientSession.createConsumer(qName);
   ClientMessage m = clientConsumer.receive(5000);
   m.acknowledge();
   Assert.assertNotNull(m);
   Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!");
   // force a cancel
   clientSession.rollback();
   clientSession.start();
   m = clientConsumer.receive(5000);
   m.acknowledge();
   Assert.assertNotNull(m);
   Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!");
   // force a cancel
   clientSession.rollback();
   m = clientConsumer.receiveImmediate();
   Assert.assertNull(m);
   clientConsumer.close();
   clientConsumer = clientSession.createConsumer(dlq);
   m = clientConsumer.receive(5000);
   Assert.assertNotNull(m);
   Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!");
 }
  @Test
  public void testDeadLetterAddressWithOverridenSublevelAddressSettings() throws Exception {
    int defaultDeliveryAttempt = 3;
    int specificeDeliveryAttempt = defaultDeliveryAttempt + 1;

    SimpleString address = new SimpleString("prefix.address");
    SimpleString queue = RandomUtil.randomSimpleString();
    SimpleString defaultDeadLetterAddress = RandomUtil.randomSimpleString();
    SimpleString defaultDeadLetterQueue = RandomUtil.randomSimpleString();
    SimpleString specificDeadLetterAddress = RandomUtil.randomSimpleString();
    SimpleString specificDeadLetterQueue = RandomUtil.randomSimpleString();

    AddressSettings defaultAddressSettings =
        new AddressSettings()
            .setMaxDeliveryAttempts(defaultDeliveryAttempt)
            .setDeadLetterAddress(defaultDeadLetterAddress);
    server.getAddressSettingsRepository().addMatch("*", defaultAddressSettings);
    AddressSettings specificAddressSettings =
        new AddressSettings()
            .setMaxDeliveryAttempts(specificeDeliveryAttempt)
            .setDeadLetterAddress(specificDeadLetterAddress);
    server.getAddressSettingsRepository().addMatch(address.toString(), specificAddressSettings);

    clientSession.createQueue(address, queue, false);
    clientSession.createQueue(defaultDeadLetterAddress, defaultDeadLetterQueue, false);
    clientSession.createQueue(specificDeadLetterAddress, specificDeadLetterQueue, false);

    ClientProducer producer = clientSession.createProducer(address);
    ClientMessage clientMessage = createTextMessage(clientSession, "heyho!");
    producer.send(clientMessage);

    clientSession.start();
    ClientConsumer clientConsumer = clientSession.createConsumer(queue);
    ClientConsumer defaultDeadLetterConsumer = clientSession.createConsumer(defaultDeadLetterQueue);
    ClientConsumer specificDeadLetterConsumer =
        clientSession.createConsumer(specificDeadLetterQueue);

    for (int i = 0; i < defaultDeliveryAttempt; i++) {
      ClientMessage m = clientConsumer.receive(500);
      Assert.assertNotNull(m);
      Assert.assertEquals(i + 1, m.getDeliveryCount());
      m.acknowledge();
      clientSession.rollback();
    }

    Assert.assertNull(defaultDeadLetterConsumer.receiveImmediate());
    Assert.assertNull(specificDeadLetterConsumer.receiveImmediate());

    // one more redelivery attempt:
    ClientMessage m = clientConsumer.receive(500);
    Assert.assertNotNull(m);
    Assert.assertEquals(specificeDeliveryAttempt, m.getDeliveryCount());
    m.acknowledge();
    clientSession.rollback();

    Assert.assertNull(defaultDeadLetterConsumer.receiveImmediate());
    Assert.assertNotNull(specificDeadLetterConsumer.receive(500));
  }
 @Override
 public void onMessage(ClientMessage message) {
   count++;
   latch.countDown();
   try {
     clientSession.rollback(true);
   } catch (ActiveMQException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
   throw new RuntimeException();
 }
  @Test
  public void testLargeMessageFileLeak() throws Exception {
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();

    // only run this on *nix systems which will have the
    // com.sun.management.UnixOperatingSystemMXBean (needed to check open file count)
    Assume.assumeTrue(os instanceof UnixOperatingSystemMXBean);

    long fdBaseline = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount();
    final int SIZE = 2 * 1024;
    SimpleString dla = new SimpleString("DLA");
    SimpleString qName = new SimpleString("q1");
    SimpleString adName = new SimpleString("ad1");

    AddressSettings addressSettings =
        new AddressSettings().setMaxDeliveryAttempts(1).setDeadLetterAddress(dla);
    server.getAddressSettingsRepository().addMatch(adName.toString(), addressSettings);
    SimpleString dlq = new SimpleString("DLQ1");
    clientSession.createQueue(dla, dlq, null, false);
    clientSession.createQueue(adName, qName, null, false);
    for (int i = 0; i < 10; i++) {
      ClientProducer producer = clientSession.createProducer(adName);
      ClientMessage clientFile = clientSession.createMessage(true);
      clientFile.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(SIZE));
      producer.send(clientFile);
      clientSession.start();
      ClientConsumer clientConsumer = clientSession.createConsumer(qName);
      ClientMessage m = clientConsumer.receive(500);
      m.acknowledge();
      Assert.assertNotNull(m);

      // force a cancel
      clientSession.rollback();
      m = clientConsumer.receiveImmediate();
      Assert.assertNull(m);
      clientConsumer.close();
    }
    assertEquals(
        "File descriptors are leaking",
        0,
        ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount() - fdBaseline);
  }
  @Test
  public void testDeadlLetterAddressWithDefaultAddressSettings() throws Exception {
    int deliveryAttempt = 3;

    SimpleString address = RandomUtil.randomSimpleString();
    SimpleString queue = RandomUtil.randomSimpleString();
    SimpleString deadLetterAddress = RandomUtil.randomSimpleString();
    SimpleString deadLetterQueue = RandomUtil.randomSimpleString();
    AddressSettings addressSettings =
        new AddressSettings()
            .setMaxDeliveryAttempts(deliveryAttempt)
            .setDeadLetterAddress(deadLetterAddress);
    server.getAddressSettingsRepository().setDefault(addressSettings);

    clientSession.createQueue(address, queue, false);
    clientSession.createQueue(deadLetterAddress, deadLetterQueue, false);

    ClientProducer producer = clientSession.createProducer(address);
    ClientMessage clientMessage = createTextMessage(clientSession, "heyho!");
    producer.send(clientMessage);

    clientSession.start();
    ClientConsumer clientConsumer = clientSession.createConsumer(queue);
    for (int i = 0; i < deliveryAttempt; i++) {
      ClientMessage m = clientConsumer.receive(500);
      Assert.assertNotNull(m);
      DeadLetterAddressTest.log.info("i is " + i);
      DeadLetterAddressTest.log.info("delivery cout is " + m.getDeliveryCount());
      Assert.assertEquals(i + 1, m.getDeliveryCount());
      m.acknowledge();
      clientSession.rollback();
    }
    ClientMessage m = clientConsumer.receive(500);
    Assert.assertNull("not expecting a message", m);
    clientConsumer.close();

    clientConsumer = clientSession.createConsumer(deadLetterQueue);
    m = clientConsumer.receive(500);
    Assert.assertNotNull(m);
    Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!");
  }
  private void doTestMultipleGroupingXARollback() throws Exception {
    ServerLocator locator = createInVMNonHALocator();
    locator.setBlockOnAcknowledge(true);
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    ClientSession clientSession = sessionFactory.createSession(true, false, false);
    ClientProducer clientProducer = this.clientSession.createProducer(qName);
    clientSession.start();

    ClientConsumer consumer = clientSession.createConsumer(qName);
    ClientConsumer consumer2 = clientSession.createConsumer(qName);
    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);
    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;
    }
    latch = new CountDownLatch(numMessages);
    dummyMessageHandler.reset(latch);
    dummyMessageHandler2.reset(latch);
    clientSession.rollback(xid);
    clientSession.start(xid, XAResource.TMNOFLAGS);
    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);
    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 = this.clientSession.createConsumer(qName);
    Assert.assertNull(consumer.receiveImmediate());
    clientSession.close();
    locator.close();
  }
  private void doTestMultipleGroupingTXRollback() throws Exception {
    log.info("*** starting test");
    ServerLocator locator = createInVMNonHALocator();
    locator.setBlockOnAcknowledge(true);
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    ClientSession clientSession = sessionFactory.createSession(false, false, false);
    ClientProducer clientProducer = this.clientSession.createProducer(qName);
    ClientConsumer consumer = clientSession.createConsumer(qName);
    ClientConsumer consumer2 = clientSession.createConsumer(qName);
    clientSession.start();

    // need to wait a bit or 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));
    Assert.assertEquals(50, dummyMessageHandler.list.size(), dummyMessageHandler.list.size());
    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;
    }
    latch = new CountDownLatch(numMessages);
    dummyMessageHandler.reset(latch);
    dummyMessageHandler2.reset(latch);
    clientSession.rollback();
    Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    Assert.assertEquals(dummyMessageHandler.list.size(), 50);
    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 = this.clientSession.createConsumer(qName);
    Assert.assertNull(consumer.receiveImmediate());
    clientSession.close();
    locator.close();
  }
  @Test
  public void testHeadersSet() throws Exception {
    final int MAX_DELIVERIES = 16;
    final int NUM_MESSAGES = 5;
    SimpleString dla = new SimpleString("DLA");
    SimpleString qName = new SimpleString("q1");
    AddressSettings addressSettings =
        new AddressSettings().setMaxDeliveryAttempts(MAX_DELIVERIES).setDeadLetterAddress(dla);
    server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings);
    SimpleString dlq = new SimpleString("DLQ1");
    clientSession.createQueue(dla, dlq, null, false);
    clientSession.createQueue(qName, qName, null, false);
    ServerLocator locator = createInVMNonHALocator();
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    ClientSession sendSession = sessionFactory.createSession(false, true, true);
    ClientProducer producer = sendSession.createProducer(qName);
    Map<String, Long> origIds = new HashMap<>();

    for (int i = 0; i < NUM_MESSAGES; i++) {
      ClientMessage tm = createTextMessage(clientSession, "Message:" + i);
      producer.send(tm);
    }

    ClientConsumer clientConsumer = clientSession.createConsumer(qName);
    clientSession.start();

    for (int i = 0; i < MAX_DELIVERIES; i++) {
      for (int j = 0; j < NUM_MESSAGES; j++) {
        ClientMessage tm = clientConsumer.receive(1000);

        Assert.assertNotNull(tm);
        tm.acknowledge();
        if (i == 0) {
          origIds.put("Message:" + j, tm.getMessageID());
        }
        Assert.assertEquals("Message:" + j, tm.getBodyBuffer().readString());
      }
      clientSession.rollback();
    }

    long timeout = System.currentTimeMillis() + 5000;

    // DLA transfer is asynchronous fired on the rollback
    while (System.currentTimeMillis() < timeout
        && getMessageCount(((Queue) server.getPostOffice().getBinding(qName).getBindable())) != 0) {
      Thread.sleep(1);
    }

    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

    ClientConsumer cc3 = clientSession.createConsumer(dlq);

    for (int i = 0; i < NUM_MESSAGES; i++) {
      ClientMessage tm = cc3.receive(1000);

      Assert.assertNotNull(tm);

      String text = tm.getBodyBuffer().readString();
      Assert.assertEquals("Message:" + i, text);

      // Check the headers
      SimpleString origDest = (SimpleString) tm.getObjectProperty(Message.HDR_ORIGINAL_ADDRESS);

      Long origMessageId = (Long) tm.getObjectProperty(Message.HDR_ORIG_MESSAGE_ID);

      Assert.assertEquals(qName, origDest);

      Long origId = origIds.get(text);

      Assert.assertEquals(origId, origMessageId);
    }

    sendSession.close();
  }