Java Code Examples for javax.jms.Message#acknowledge()

The following examples show how to use javax.jms.Message#acknowledge() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JMSIndividualAckTest.java    From activemq-artemis with Apache License 2.0 7 votes vote down vote up
/**
 * Tests if unacknowledged messages are being re-delivered when the consumer connects again.
 *
 * @throws JMSException
 */
public void testUnAckedMessageAreNotConsumedOnSessionClose() throws JMSException {
   connection.start();
   Session session = connection.createSession(false, ActiveMQSession.INDIVIDUAL_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, ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);

   // Attempt to Consume the message...
   consumer = session.createConsumer(queue);
   msg = consumer.receive(2000);
   assertNotNull(msg);
   msg.acknowledge();

   session.close();
}
 
Example 2
Source File: JmsEventTransportImpl.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        if (!(message instanceof TextMessage)) {
            handleInvalidMessageType(message);
            return;
        }

        Event e = eventUnMarshaller.unmarshallEvent(Arrays.asList(PingEvent.class, eventClass), eventClass, message);
        if (e instanceof PingEvent) {
            // if pingMonitor not setup then just swallow..
            if (pingMonitor != null) {
                pingMonitor.pingReceived((PingEvent) e);
            }
        }
        else {
            observer.onResult(new ExecutionResult(e));
        }
        message.acknowledge();
    } catch (Throwable t) { //NOSONAR
        handleThrowable(message, t);
    }
}
 
Example 3
Source File: JmsCheckpointMark.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Acknowledge all outstanding message. Since we believe that messages will be delivered in
 * timestamp order, and acknowledged messages will not be retried, the newest message in this
 * batch is a good bound for future messages.
 */
@Override
public void finalizeCheckpoint() {
  lock.writeLock().lock();
  try {
    for (Message message : messages) {
      try {
        message.acknowledge();
        Instant currentMessageTimestamp = new Instant(message.getJMSTimestamp());
        if (currentMessageTimestamp.isAfter(oldestMessageTimestamp)) {
          oldestMessageTimestamp = currentMessageTimestamp;
        }
      } catch (Exception e) {
        LOG.error("Exception while finalizing message: ", e);
      }
    }
    messages.clear();
  } finally {
    lock.writeLock().unlock();
  }
}
 
Example 4
Source File: JmsClientAckTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 5
Source File: JmsClientAckTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if acknowledged messages are being consumed.
 *
 * @throws JMSException
 */
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();
}
 
Example 6
Source File: JournalPendingMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeliveringStats() throws Exception {
   AtomicLong publishedMessageSize = new AtomicLong();

   Connection connection = cf.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
   producer.send(session.createTextMessage("test"));

   verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
   verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
   verifyDeliveringStats(defaultQueueName, 0, 0);

   MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName));
   Message msg = consumer.receive();
   verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get());
   msg.acknowledge();

   verifyPendingStats(defaultQueueName, 0, 0);
   verifyPendingDurableStats(defaultQueueName, 0, 0);
   verifyDeliveringStats(defaultQueueName, 0, 0);

   connection.close();
}
 
Example 7
Source File: AmqpAcknowledgementsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testAcknowledgeFailsAfterSessionIsClosed() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType(null), 1);

        MessageConsumer messageConsumer = session.createConsumer(queue);

        Message receivedMessage = messageConsumer.receive(6000);
        assertNotNull("Message was not recieved", receivedMessage);

        testPeer.expectDisposition(true, new ModifiedMatcher().withDeliveryFailed(equalTo(true)), 1, 1);
        testPeer.expectEnd();

        session.close();

        try {
            receivedMessage.acknowledge();
            fail("Should not be able to acknowledge the message after session closed");
        } catch (JMSException jmsex) {}

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 8
Source File: CacheSyncMessageListener.java    From j360-dubbo-app-all with Apache License 2.0 5 votes vote down vote up
/**
 * MessageListener回调函数.
 */
@Override
public void onMessage(Message message) {
	try {
		MapMessage mapMessage = (MapMessage) message;
		// 打印消息详情
           byte[] bytes = mapMessage.getBytes("json");
           String json = new String(bytes,"utf-8");
           CacheSyncMessage dto = binder.fromJson(json, CacheSyncMessage.class);
           cacheSyncManager.writeMQCount(dto);
           message.acknowledge();
       } catch (Exception e) {
		log.error("处理消息时发生异常: [{}]", message.toString(), e);
	}
}
 
Example 9
Source File: ConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testSessionCloseDoesNotDeferConsumerClose() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Queue queue = session.createQueue(getTestName());

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType("content"), 1);

        MessageConsumer consumer = session.createConsumer(queue);

        Message receivedMessage = consumer.receive(3000);

        assertNotNull(receivedMessage);
        assertTrue(receivedMessage instanceof TextMessage);

        testPeer.expectDisposition(true, new ModifiedMatcher().withDeliveryFailed(equalTo(true)), 1, 1);
        testPeer.expectEnd();

        session.close();

        // Consumer and Session should be closed, not acknowledge allowed
        try {
            receivedMessage.acknowledge();
            fail("Should not be allowed to call acknowledge after session closed.");
        } catch (IllegalStateException ise) {
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 10
Source File: JmsRedeliveredTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests session recovery and that the redelivered message is marked as
 * such. Session uses client acknowledgement, the destination is a topic and
 * the consumer is a durable suscriber.
 *
 * @throws JMSException
 */
public void testDurableTopicRecoverMarksMessageRedelivered() throws JMSException {
   connection.setClientID(getName());
   connection.start();

   Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   Topic topic = session.createTopic("topic-" + getName());
   MessageConsumer consumer = session.createDurableSubscriber(topic, "sub1");

   MessageProducer producer = createProducer(session, topic);
   producer.send(createTextMessage(session));

   // Consume the message...
   Message msg = consumer.receive(1000);
   assertNotNull(msg);
   assertFalse("Message should not be redelivered.", msg.getJMSRedelivered());
   // Don't ack the message.

   // Reset the session. This should cause the Unacked message to be
   // redelivered.
   session.recover();

   // Attempt to Consume the message...
   msg = consumer.receive(2000);
   assertNotNull(msg);
   assertTrue("Message should be redelivered.", msg.getJMSRedelivered());
   msg.acknowledge();

   session.close();
}
 
Example 11
Source File: AbstractMessageListenerContainer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Perform a commit or message acknowledgement, as appropriate.
 * @param session the JMS Session to commit
 * @param message the Message to acknowledge
 * @throws javax.jms.JMSException in case of commit failure
 */
protected void commitIfNecessary(Session session, Message message) throws JMSException {
	// Commit session or acknowledge message.
	if (session.getTransacted()) {
		// Commit necessary - but avoid commit call within a JTA transaction.
		if (isSessionLocallyTransacted(session)) {
			// Transacted session created by this container -> commit.
			JmsUtils.commitIfNecessary(session);
		}
	}
	else if (message != null && isClientAcknowledge(session)) {
		message.acknowledge();
	}
}
 
Example 12
Source File: JmsClientAckTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 13
Source File: JmsClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private void doCleanupQueue( final Session session, final Destination destination ) throws JMSException {

        try {
            MessageConsumer consumer = session.createConsumer(destination);
            Message message = null;
            do {
                message = consumer.receiveNoWait();
                if (message != null) {
                    message.acknowledge();
                }
            } while (message != null);
        } finally {
            releaseSession(false);
        }
    }
 
Example 14
Source File: JmsClientAckTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=60000)
public void testOnlyUnackedAreRecovered() throws Exception {
    connection = createAmqpConnection();
    connection.start();
    Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = consumerSession.createQueue(name.getMethodName());
    MessageConsumer consumer = consumerSession.createConsumer(queue);
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = producerSession.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    TextMessage sent1 = producerSession.createTextMessage();
    sent1.setText("msg1");
    producer.send(sent1);
    TextMessage sent2 = producerSession.createTextMessage();
    sent2.setText("msg2");
    producer.send(sent2);
    TextMessage sent3 = producerSession.createTextMessage();
    sent3.setText("msg3");
    producer.send(sent3);

    consumer.receive(5000);
    Message rec2 = consumer.receive(5000);
    consumer.receive(5000);
    rec2.acknowledge();

    TextMessage sent4 = producerSession.createTextMessage();
    sent4.setText("msg4");
    producer.send(sent4);

    Message rec4 = consumer.receive(5000);
    assertNotNull(rec4);
    assertTrue(rec4.equals(sent4));
    consumerSession.recover();
    rec4 = consumer.receive(5000);
    assertNotNull(rec4);
    assertTrue(rec4.equals(sent4));
    assertTrue(rec4.getJMSRedelivered());
    rec4.acknowledge();
}
 
Example 15
Source File: QueueAutoDeleteTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testAutoDeleteTopicDefaultDurableSubscriptionQueue() throws Exception {
   ConnectionFactory fact = getCF();
   Connection connection = fact.createConnection();
   connection.start();

   try {

      Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

      String testQueueName = getName();
      String sub = testQueueName + "/mysub";

      Topic topic = session.createTopic(testQueueName);

      assertEquals(testQueueName, topic.getTopicName());


      MessageConsumer consumer = session.createSharedDurableConsumer(topic, sub);

      QueueBinding queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(sub));
      assertFalse(queueBinding.getQueue().isAutoDelete());
      Wait.assertEquals(0, queueBinding.getQueue()::getMessageCount);

      MessageProducer producer = session.createProducer(topic);
      producer.send(session.createTextMessage("hello1"));
      producer.send(session.createTextMessage("hello2"));

      Message message = consumer.receive(5000);
      assertNotNull(message);
      assertEquals("hello1", ((TextMessage)message).getText());
      message.acknowledge();

      consumer.close();

      queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(sub));
      assertNotNull(queueBinding);

      consumer = session.createSharedDurableConsumer(topic, sub);
      message = consumer.receive(5000);
      assertNotNull(message);
      assertEquals("hello2", ((TextMessage)message).getText());
      message.acknowledge();

      consumer.close();

      //Wait longer than scan period.
      Thread.sleep(20);

      queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(sub));
      assertNotNull(queueBinding);


   } finally {
      connection.close();
   }
}
 
Example 16
Source File: AmqpAcknowledgementsIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testAcknowledgeIndividualMessages()  throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(INDIVIDUAL_ACK);
        Queue queue = session.createQueue("myQueue");

        int msgCount = 6;
        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType(null), msgCount, false, false,
                Matchers.greaterThanOrEqualTo(UnsignedInteger.valueOf(msgCount)), 1, false, true);

        MessageConsumer messageConsumer = session.createConsumer(queue);

        List<Message> messages = new ArrayList<>();
        Message lastReceivedMessage = null;
        for (int i = 0; i < msgCount; i++) {
            lastReceivedMessage = messageConsumer.receive(3000);
            assertNotNull("Message " + i + " was not received", lastReceivedMessage);
            messages.add(lastReceivedMessage);

            assertEquals("unexpected message number property", i, lastReceivedMessage.getIntProperty(TestAmqpPeer.MESSAGE_NUMBER));
        }

        List<Integer> ackTypes = new ArrayList<>();
        ackTypes.add(SKIP);
        ackTypes.add(JmsMessageSupport.ACCEPTED);
        ackTypes.add(JmsMessageSupport.REJECTED);
        ackTypes.add(JmsMessageSupport.RELEASED);
        ackTypes.add(JmsMessageSupport.MODIFIED_FAILED);
        ackTypes.add(JmsMessageSupport.MODIFIED_FAILED_UNDELIVERABLE);

        Matcher<?>[] dispositionMatchers = new Matcher<?>[msgCount];
        dispositionMatchers[0] = null;
        dispositionMatchers[JmsMessageSupport.ACCEPTED] = new AcceptedMatcher();
        dispositionMatchers[JmsMessageSupport.REJECTED] = new RejectedMatcher();
        dispositionMatchers[JmsMessageSupport.RELEASED] = new ReleasedMatcher();
        dispositionMatchers[JmsMessageSupport.MODIFIED_FAILED] = new ModifiedMatcher().withDeliveryFailed(equalTo(true));
        dispositionMatchers[JmsMessageSupport.MODIFIED_FAILED_UNDELIVERABLE] = new ModifiedMatcher().withDeliveryFailed(equalTo(true)).withUndeliverableHere(equalTo(true));

        // Acknowledge the messages in a random order with random amqp ack type set (leaving one message without
        // any specific set, to check it accepts), verify the individual dispositions have expected delivery state.
        Random rand = new Random();
        for (int i = 0; i < msgCount; i++) {
            Message msg = messages.remove(rand.nextInt(msgCount - i));

            int deliveryNumber =  msg.getIntProperty(TestAmqpPeer.MESSAGE_NUMBER) + 1;
            int ackType = ackTypes.remove(rand.nextInt(msgCount - i));

            if(ackType != SKIP) {
                msg.setIntProperty(JmsMessageSupport.JMS_AMQP_ACK_TYPE, ackType);

                testPeer.expectDisposition(true, dispositionMatchers[ackType], deliveryNumber, deliveryNumber);
            } else {
                testPeer.expectDisposition(true, new AcceptedMatcher(), deliveryNumber, deliveryNumber);
            }

            msg.acknowledge();

            testPeer.waitForAllHandlersToComplete(3000);
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 17
Source File: MemoryLimitTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 120000)
public void testCursorBatch() throws Exception {

   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?jms.prefetchPolicy.all=10");
   factory.setOptimizeAcknowledge(true);
   Connection conn = factory.createConnection();
   conn.start();
   Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   Queue queue = sess.createQueue("STORE");
   final ProducerThread producer = new ProducerThread(sess, queue) {
      @Override
      protected Message createMessage(int i) throws Exception {
         BytesMessage bytesMessage = sess.createBytesMessage();
         bytesMessage.writeBytes(payload);
         return bytesMessage;
      }
   };
   producer.setMessageCount(2000);
   producer.start();
   producer.join();

   Thread.sleep(1000);

   // assert we didn't break high watermark (70%) usage
   final Destination dest = broker.getDestination((ActiveMQQueue) queue);
   LOG.info("Destination usage: " + dest.getMemoryUsage());
   int percentUsage = dest.getMemoryUsage().getPercentUsage();
   assertTrue("Should be less than 70% of limit but was: " + percentUsage, percentUsage <= 71);
   LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage());
   assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() <= 71);

   // consume one message
   MessageConsumer consumer = sess.createConsumer(queue);
   Message msg = consumer.receive(5000);
   msg.acknowledge();

   // this should free some space and allow us to get new batch of messages in the memory
   // exceeding the limit
   assertTrue("Limit is exceeded", Wait.waitFor(new Wait.Condition() {
      @Override
      public boolean isSatisified() throws Exception {
         LOG.info("Destination usage: " + dest.getMemoryUsage());
         return dest.getMemoryUsage().getPercentUsage() >= 200;
      }
   }));

   LOG.info("Broker usage: " + broker.getSystemUsage().getMemoryUsage());
   assertTrue(broker.getSystemUsage().getMemoryUsage().getPercentUsage() >= 200);

   // let's make sure we can consume all messages
   for (int i = 1; i < 2000; i++) {
      msg = consumer.receive(5000);
      if (msg == null) {
         dumpAllThreads("NoMessage");
      }
      assertNotNull("Didn't receive message " + i, msg);
      msg.acknowledge();
   }
}
 
Example 18
Source File: MessageGroupLateArrivalsTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {

   try {
      startSignal.await();
      log.info(workerName);
      Session sess = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      MessageConsumer consumer = sess.createConsumer(queueName);
      workerStarted.countDown();

      while (true) {
         if (counters[0] == 0 && counters[1] == 0 && counters[2] == 0) {
            doneSignal.countDown();
            log.info(workerName + " done...");
            break;
         }

         Message msg = consumer.receive(500);
         if (msg == null)
            continue;

         msg.acknowledge();

         String group = msg.getStringProperty("JMSXGroupID");
         msg.getBooleanProperty("JMSXGroupFirstForConsumer");

         if ("A".equals(group)) {
            --counters[0];
            update(group);
         } else if ("B".equals(group)) {
            --counters[1];
            update(group);
         } else if ("C".equals(group)) {
            --counters[2];
            update(group);
         } else {
            log.warn(workerName + ", unknown group");
         }
         if (counters[0] != 0 || counters[1] != 0 || counters[2] != 0) {
            msg.acknowledge();
         }
      }
      consumer.close();
      sess.close();
   } catch (Exception e) {
      e.printStackTrace();
   }
}
 
Example 19
Source File: JMSMessageConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 60000)
public void testClientAckMessages() throws Exception {
   final int numMessages = 10;

   Connection connection = createConnection();

   try {
      long time = System.currentTimeMillis();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      javax.jms.Queue queue = session.createQueue(getQueueName());
      MessageProducer producer = session.createProducer(queue);

      byte[] bytes = new byte[2048];
      new Random().nextBytes(bytes);
      for (int i = 0; i < numMessages; i++) {
         TextMessage message = session.createTextMessage();
         message.setText("msg:" + i);
         producer.send(message);
      }
      connection.close();
      Queue queueView = getProxyToQueue(getQueueName());

      Wait.assertEquals(numMessages, queueView::getMessageCount);

      // Now create a new connection and receive and acknowledge
      connection = createConnection();
      session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(queue);

      for (int i = 0; i < numMessages; i++) {
         Message msg = consumer.receive(5000);
         Assert.assertNotNull("" + i, msg);
         Assert.assertTrue("" + msg, msg instanceof TextMessage);
         String text = ((TextMessage) msg).getText();
         // System.out.println("text = " + text);
         Assert.assertEquals(text, "msg:" + i);
         msg.acknowledge();
      }

      consumer.close();
      connection.close();

      Wait.assertEquals(0, queueView::getMessageCount);
   } finally {
      connection.close();
   }
}
 
Example 20
Source File: JmsConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testIndividualACKMessageConsumer() throws Exception {
   Connection conn = cf.createConnection();
   Session session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);
   jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
   MessageProducer producer = session.createProducer(jBossQueue);
   MessageConsumer consumer = session.createConsumer(jBossQueue);
   int noOfMessages = 100;
   for (int i = 0; i < noOfMessages; i++) {
      producer.setPriority(2);
      producer.send(session.createTextMessage("m" + i));
   }

   conn.start();

   final AtomicInteger errors = new AtomicInteger(0);
   final ReusableLatch latch = new ReusableLatch();
   latch.setCount(noOfMessages);

   class MessageAckEven implements MessageListener {

      int count = 0;

      @Override
      public void onMessage(Message msg) {
         try {
            TextMessage txtmsg = (TextMessage) msg;
            if (!txtmsg.getText().equals("m" + count)) {

               errors.incrementAndGet();
            }

            if (count % 2 == 0) {
               msg.acknowledge();
            }

            count++;
         } catch (Exception e) {
            errors.incrementAndGet();
         } finally {
            latch.countDown();
         }
      }

   }

   consumer.setMessageListener(new MessageAckEven());

   Assert.assertTrue(latch.await(5000));

   session.close();

   session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);

   consumer = session.createConsumer(jBossQueue);

   // Consume odd numbers first
   for (int i = 0; i < noOfMessages; i++) {
      if (i % 2 == 0) {
         continue;
      }

      TextMessage m = (TextMessage) consumer.receive(1000);
      Assert.assertNotNull(m);
      m.acknowledge();
      Assert.assertEquals("m" + i, m.getText());
   }

   SimpleString queueName = new SimpleString(JmsConsumerTest.Q_NAME);
   conn.close();

   Queue queue = server.locateQueue(queueName);
   Wait.assertEquals(0, queue::getDeliveringCount);
   Wait.assertEquals(0, queue::getMessageCount);
}