Java Code Examples for javax.jms.Session#recover()

The following examples show how to use javax.jms.Session#recover() . 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: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Recover
 *
 * @throws JMSException Failed to close session.
 */
@Override
public void recover() throws JMSException {
   lock();
   try {
      Session session = getSessionInternal();

      if (cri.isTransacted()) {
         throw new IllegalStateException("Session is transacted");
      }

      if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
         ActiveMQRALogger.LOGGER.trace("Recover session " + this);
      }

      session.recover();
   } finally {
      unlock();
   }
}
 
Example 2
Source File: ClientJmsDelegate.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public void rollbackOrRecoverIfNecessary(String sessionName)
{
    try
    {
        final Session session = _testSessions.get(sessionName);
        synchronized(session)
        {
            if (session.getTransacted())
            {
                session.rollback();
            }
            else if (session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
            {
                session.recover();
            }
        }
    }
    catch (final JMSException jmse)
    {
        throw new DistributedTestException("Unable to rollback or recover on session: " +
                        sessionName, jmse);
    }
}
 
Example 3
Source File: AbstractMessageListenerContainer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Perform a rollback, if appropriate.
 * @param session the JMS Session to rollback
 * @throws javax.jms.JMSException in case of a rollback error
 */
protected void rollbackIfNecessary(Session session) throws JMSException {
	if (session.getTransacted()) {
		if (isSessionLocallyTransacted(session)) {
			// Transacted session created by this container -> rollback.
			JmsUtils.rollbackIfNecessary(session);
		}
	}
	else if (isClientAcknowledge(session)) {
		session.recover();
	}
}
 
Example 4
Source File: FailoverProviderTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testSessionRecoverPassthrough() throws Exception {
    JmsConnectionFactory factory = new JmsConnectionFactory(
        "failover:(mock://localhost)");

    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    session.recover();
    connection.close();

    assertEquals(1, mockPeer.getContextStats().getRecoverCalls());
}
 
Example 5
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 6
Source File: JmsRedeliveredTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * @throws JMSException
 */
public void testTopicRecoverMarksMessageRedelivered() throws JMSException {

   connection.setClientID(getName());
   connection.start();

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

   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 7
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 8
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 queue.
 *
 * @throws JMSException
 */
public void testQueueRecoverMarksMessageRedelivered() throws JMSException {
   connection.start();

   Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   Queue queue = session.createQueue("queue-" + getName());
   MessageProducer producer = createProducer(session, queue);
   producer.send(createTextMessage(session));

   // Consume the message...
   MessageConsumer consumer = session.createConsumer(queue);
   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 9
Source File: CachedJMSConnectionFactory.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Recover JMS session
 *
 * @param session    JMS session to issue recover() on
 * @param forcefully True if recover needs to be done without conditions. Otherwise, recover
 *                   will be done based on cache level
 * @throws JMSException Upon error recovering the session
 */
public void recoverSession(Session session, boolean forcefully) throws JMSException {
    if (this.cacheLevel >= JMSConstants.CACHE_SESSION || forcefully) {
        if (logger.isDebugEnabled()) {
            logger.debug("Recovered JMS session");
        }
        session.recover();
    }
}
 
Example 10
Source File: RecoverTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testMessageOrderForClientAcknowledge() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(queue);
        Utils.sendMessages(connection, queue, SENT_COUNT);
        connection.start();

        int messageSeen = 0;
        int expectedIndex = 0;
        while (expectedIndex < SENT_COUNT)
        {
            Message message = receiveAndValidateMessage(consumer, expectedIndex);

            //don't ack the message until we receive it 5 times
            if (messageSeen < 5)
            {
                LOGGER.debug(String.format("Recovering message with index %d", expectedIndex));
                session.recover();
                messageSeen++;
            }
            else
            {
                LOGGER.debug(String.format("Acknowledging message with index %d", expectedIndex));
                messageSeen = 0;
                expectedIndex++;
                message.acknowledge();
            }
        }
    }
    finally
    {
        connection.close();
    }
}
 
Example 11
Source File: RecoverTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoverForClientAcknowledge() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(queue);
        Utils.sendMessages(connection, queue, SENT_COUNT);
        connection.start();

        Message message = receiveAndValidateMessage(consumer, 0);
        message.acknowledge();

        receiveAndValidateMessage(consumer, 1);
        receiveAndValidateMessage(consumer, 2);
        session.recover();

        receiveAndValidateMessage(consumer, 1);
        receiveAndValidateMessage(consumer, 2);
        receiveAndValidateMessage(consumer, 3);
    }
    finally
    {
        connection.close();
    }
}
 
Example 12
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testSessionRecoverDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    session.recover();
    connection.close();
}
 
Example 13
Source File: AbstractMessageListenerContainer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Perform a rollback, if appropriate.
 * @param session the JMS Session to rollback
 * @throws javax.jms.JMSException in case of a rollback error
 */
protected void rollbackIfNecessary(Session session) throws JMSException {
	if (session.getTransacted()) {
		if (isSessionLocallyTransacted(session)) {
			// Transacted session created by this container -> rollback.
			JmsUtils.rollbackIfNecessary(session);
		}
	}
	else if (isClientAcknowledge(session)) {
		session.recover();
	}
}
 
Example 14
Source File: RecoverTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testAcknowledgePerConsumer() throws Exception
{
    Queue queue1 = createQueue("Q1");
    Queue queue2 = createQueue("Q2");

    Connection consumerConnection = getConnection();
    try
    {
        Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer consumer1 = consumerSession.createConsumer(queue1);
        MessageConsumer consumer2 = consumerSession.createConsumer(queue2);

        Connection producerConnection = getConnection();
        try
        {
            Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer1 = producerSession.createProducer(queue1);
            MessageProducer producer2 = producerSession.createProducer(queue2);

            producer1.send(producerSession.createTextMessage("msg1"));
            producer2.send(producerSession.createTextMessage("msg2"));
        }
        finally
        {
            producerConnection.close();
        }
        consumerConnection.start();

        TextMessage message2 = (TextMessage) consumer2.receive(getReceiveTimeout());
        assertNotNull(message2);
        assertEquals("msg2", message2.getText());

        message2.acknowledge();
        consumerSession.recover();

        TextMessage message1 = (TextMessage) consumer1.receive(getReceiveTimeout());
        assertNotNull(message1);
        assertEquals("msg1", message1.getText());
    }
    finally
    {
        consumerConnection.close();
    }
}
 
Example 15
Source File: SortedQueueTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetNextWithAck() throws Exception
{
    final String queueName = getTestName();
    Queue queue = createSortedQueue(queueName, TEST_SORT_KEY);

    final Connection producerConnection = getConnection();
    try
    {
        final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
        final MessageProducer producer = producerSession.createProducer(queue);

        sendAndCommitMessage(producerSession, producer, "2");
        sendAndCommitMessage(producerSession, producer, "3");
        sendAndCommitMessage(producerSession, producer, "1");

        final Connection consumerConnection = getConnectionBuilder().setPrefetch(1).build();
        try
        {
            final Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            final MessageConsumer consumer = consumerSession.createConsumer(queue);
            consumerConnection.start();

            Message received;

            //Receive 3 in sorted order
            received = assertReceiveAndValidateMessage(consumer, "1");
            received.acknowledge();
            received = assertReceiveAndValidateMessage(consumer, "2");
            received.acknowledge();
            received = assertReceiveAndValidateMessage(consumer, "3");
            received.acknowledge();

            //Send 1
            sendAndCommitMessage(producerSession, producer, "4");

            //Receive 1 and recover
            assertReceiveAndValidateMessage(consumer, "4");
            consumerSession.recover();

            //Receive same 1
            received = assertReceiveAndValidateMessage(consumer, "4");
            received.acknowledge();

            //Send 3 out of order
            sendAndCommitMessage(producerSession, producer, "7");
            sendAndCommitMessage(producerSession, producer, "6");
            sendAndCommitMessage(producerSession, producer, "5");

            //Receive 1 of 3 (possibly out of order due to pre-fetch)
            final Message messageBeforeRollback = assertReceiveMessage(consumer);
            consumerSession.recover();

            if (getProtocol().equals(Protocol.AMQP_0_10))
            {
                //Receive 3 in sorted order (not as per JMS recover)
                received = assertReceiveAndValidateMessage(consumer, "5");
                received.acknowledge();
                received = assertReceiveAndValidateMessage(consumer, "6");
                received.acknowledge();
                received = assertReceiveAndValidateMessage(consumer, "7");
                received.acknowledge();
            }
            else
            {
                //First message will be the one rolled-back (as per JMS spec).
                final String messageKeyDeliveredBeforeRollback =
                        messageBeforeRollback.getStringProperty(TEST_SORT_KEY);
                received = assertReceiveAndValidateMessage(consumer, messageKeyDeliveredBeforeRollback);
                received.acknowledge();

                //Remaining two messages will be sorted
                final SortedSet<String> keys = new TreeSet<>(Arrays.asList("5", "6", "7"));
                keys.remove(messageKeyDeliveredBeforeRollback);

                received = assertReceiveAndValidateMessage(consumer, keys.first());
                received.acknowledge();
                received = assertReceiveAndValidateMessage(consumer, keys.last());
                received.acknowledge();
            }
        }
        finally
        {
            consumerConnection.close();
        }
    }
    finally
    {
        producerConnection.close();
    }
}
 
Example 16
Source File: QueueConsumerTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({ "broker-port", "admin-username", "admin-password", "broker-hostname" })
@Test
public void testConsumerWithBasicRecover(String port,
                                        String adminUsername,
                                        String adminPassword,
                                        String brokerHostname) throws Exception {
    String queueName = "testConsumerWithBasicRecover";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // publish message
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    TextMessage firstMessage = producerSession.createTextMessage("First message for reject test");
    TextMessage secondMessage = producerSession.createTextMessage("Second message for reject test");
    String correlationIdOne = "1";
    String correlationIdTwo = "2";
    firstMessage.setJMSCorrelationID(correlationIdOne);
    secondMessage.setJMSCorrelationID(correlationIdTwo);
    producer.send(firstMessage);
    producer.send(secondMessage);
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    Message message = consumer.receive(5000);
    Assert.assertNotNull(message, "Message was not received");

    subscriberSession.recover();

    // Message order can change after recovering
    for (int i = 0; i < 2; i++) {
        message = consumer.receive(5000);
        Assert.assertNotNull(message, "Requeued message was not received");

        if (correlationIdOne.equals(message.getJMSCorrelationID())) {
            Assert.assertTrue(message.getJMSRedelivered(), "Redelivered flag was set in second message" + message);
        } else {
            Assert.assertFalse(message.getJMSRedelivered(), "Redelivered flag was set in first message");
        }

        message.acknowledge();
    }

    connection.close();
}
 
Example 17
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testRedel5() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();
      conn.start();

      Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      MessageProducer prod = sess.createProducer(queue1);
      TextMessage tm1 = sess.createTextMessage("hello1");
      TextMessage tm2 = sess.createTextMessage("hello2");
      TextMessage tm3 = sess.createTextMessage("hello3");
      prod.send(tm1);
      prod.send(tm2);
      prod.send(tm3);

      MessageConsumer cons1 = sess.createConsumer(queue1);

      TextMessage rm1 = (TextMessage) cons1.receive(1500);
      ProxyAssertSupport.assertNotNull(rm1);
      ProxyAssertSupport.assertEquals("hello1", rm1.getText());

      // redeliver
      sess.recover();

      TextMessage rm2 = (TextMessage) cons1.receive(1500);
      ProxyAssertSupport.assertNotNull(rm2);
      ProxyAssertSupport.assertEquals("hello1", rm2.getText());

      TextMessage rm3 = (TextMessage) cons1.receive(1500);
      ProxyAssertSupport.assertNotNull(rm3);
      ProxyAssertSupport.assertEquals("hello2", rm3.getText());

      TextMessage rm4 = (TextMessage) cons1.receive(1500);
      ProxyAssertSupport.assertNotNull(rm4);
      ProxyAssertSupport.assertEquals("hello3", rm4.getText());

      rm4.acknowledge();
   } finally {
      if (conn != null) {
         conn.close();
      }

      // This last step is important - there shouldn't be any more messages to receive
      checkEmpty(queue1);

      removeAllMessages(queue1.getQueueName(), true);
   }
}
 
Example 18
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testRedel6() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();
      conn.start();

      Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      MessageProducer prod = sess.createProducer(queue1);
      TextMessage tm1 = sess.createTextMessage("hello1");
      TextMessage tm2 = sess.createTextMessage("hello2");
      TextMessage tm3 = sess.createTextMessage("hello3");
      prod.send(tm1);
      prod.send(tm2);
      prod.send(tm3);

      MessageConsumer cons1 = sess.createConsumer(queue1);

      TextMessage rm1 = (TextMessage) cons1.receive(1500);
      ProxyAssertSupport.assertNotNull(rm1);
      ProxyAssertSupport.assertEquals("hello1", rm1.getText());

      cons1.close();

      log.debug("sess.recover()");

      // redeliver
      sess.recover();

      MessageConsumer cons2 = sess.createConsumer(queue1);

      log.debug("receiving ...");

      TextMessage rm2 = (TextMessage) cons2.receive(1500);
      ProxyAssertSupport.assertNotNull(rm2);
      ProxyAssertSupport.assertEquals("hello1", rm2.getText());

      TextMessage rm3 = (TextMessage) cons2.receive(1500);
      ProxyAssertSupport.assertNotNull(rm3);
      ProxyAssertSupport.assertEquals("hello2", rm3.getText());

      TextMessage rm4 = (TextMessage) cons2.receive(1500);
      ProxyAssertSupport.assertNotNull(rm4);
      ProxyAssertSupport.assertEquals("hello3", rm4.getText());

      rm4.acknowledge();
   } finally {
      if (conn != null) {
         conn.close();
      }

      // This last step is important - there shouldn't be any more messages to receive
      checkEmpty(queue1);

      removeAllMessages(queue1.getQueueName(), true);
   }
}
 
Example 19
Source File: DeadLetterChannelTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({ "broker-hostname", "broker-port", "admin-username", "admin-password" })
@Test
public void testDlcWithBasicRecover(String brokerHostname,
                                    String port,
                                    String adminUsername,
                                    String adminPassword) throws Exception {
    String queueName = "testDlcWithBasicRecover";
    String dlcQueueName = "amq.dlq";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withQueue(queueName)
            .withQueue(dlcQueueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // publish message
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    producer.send(producerSession.createTextMessage("Message for DLC test"));
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    for (int iteration = 0; iteration < 6; iteration++) {
        Message message = consumer.receive(5000);
        Assert.assertNotNull(message, "Message was not received");
        subscriberSession.recover();
    }

    Connection dlcConsumerConnection = connectionFactory.createConnection();
    dlcConsumerConnection.start();
    Session dlcConsumerSession = dlcConsumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer dlcConsumer = dlcConsumerSession.createConsumer((Destination) initialContextForQueue.lookup(
            dlcQueueName));

    Message dlcMessage = dlcConsumer.receive(5000);
    Assert.assertNotNull(dlcMessage, "Dead lettered message was not received" + dlcMessage);
    String originQueue = dlcMessage.getStringProperty("x-origin-queue");
    Assert.assertEquals(originQueue, queueName, "Origin queue name did not match" + dlcMessage);
    String originExchange = dlcMessage.getStringProperty("x-origin-exchange");
    Assert.assertEquals(originExchange, "amq.direct", "Origin exchange name did not match" + dlcMessage);
    String originRoutingKey = dlcMessage.getStringProperty("x-origin-routing-key");
    Assert.assertEquals(originRoutingKey, queueName, "Origin routing key did not match" + dlcMessage);

    dlcConsumerConnection.close();
    connection.close();
}
 
Example 20
Source File: SessionIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doAcknowledgePreviouslyRecoveredClientAckMessagesTestImpl(boolean closeConsumer, boolean closeSession, boolean consumeAllRecovered) throws JMSException, Exception, IOException {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer, false, "?jms.clientID=myClientId", null, null, false);
        connection.start();

        int msgCount = 7;
        int deliverBeforeRecoverCount = 4;
        int acknowledgeAfterRecoverCount = consumeAllRecovered ? 5 : 2;

        testPeer.expectBegin();

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

        String topicName = "myTopic";
        Topic topic = session.createTopic(topicName);

        final CountDownLatch incoming = new CountDownLatch(msgCount);
        ((JmsConnection) connection).addConnectionListener(new JmsDefaultConnectionListener() {

            @Override
            public void onInboundMessage(JmsInboundMessageDispatch envelope) {
                incoming.countDown();
            }
        });

        testPeer.expectReceiverAttach();

        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType("content"), msgCount, false, false,
                equalTo(UnsignedInteger.valueOf(JmsDefaultPrefetchPolicy.DEFAULT_QUEUE_PREFETCH)), 1, false, true);

        MessageConsumer consumer = session.createConsumer(topic);

        TextMessage receivedTextMessage = null;
        for (int i = 1; i <= deliverBeforeRecoverCount; i++) {
            assertNotNull("Expected message did not arrive: " + i, receivedTextMessage = (TextMessage) consumer.receive(3000));
            assertEquals("Unexpected delivery number", i,  receivedTextMessage.getIntProperty(TestAmqpPeer.MESSAGE_NUMBER) + 1);
        }

        // Await all incoming messages to arrive at consumer before we recover, ensure deterministic test behaviour.
        assertTrue("Messages did not arrive in a timely fashion", incoming.await(3, TimeUnit.SECONDS));

        session.recover();

        testPeer.waitForAllHandlersToComplete(1000);

        for (int i = 1; i <= acknowledgeAfterRecoverCount; i++) {
            assertNotNull("Expected message did not arrive after recover: " + i, receivedTextMessage = (TextMessage) consumer.receive(3000));
            assertEquals("Unexpected delivery number after recover", i,  receivedTextMessage.getIntProperty(TestAmqpPeer.MESSAGE_NUMBER) + 1);
            testPeer.expectDisposition(true, new AcceptedMatcher(), i, i);
            receivedTextMessage.acknowledge();
        }

        testPeer.waitForAllHandlersToComplete(1000);

        if(!consumeAllRecovered) {
            // Any message delivered+recovered before but not then delivered and acknowledged afterwards, will have
            // disposition sent as consumer/session/connection is closed.
            for (int i = acknowledgeAfterRecoverCount + 1; i <= deliverBeforeRecoverCount; i++) {
                testPeer.expectDisposition(true, new ModifiedMatcher().withDeliveryFailed(equalTo(true)), i, i);
            }
        }

        if(closeConsumer) {
            testPeer.expectDetach(true,  true,  true);

            // Dispositions sent by proton when the link is freed
            for (int i = Math.max(deliverBeforeRecoverCount, acknowledgeAfterRecoverCount) + 1; i <= msgCount; i++) {
                testPeer.expectDisposition(true, new ReleasedMatcher(), i, i);
            }

            consumer.close();
        }

        if(closeSession) {
            testPeer.expectEnd();

            session.close();
        }

        testPeer.expectClose();

        connection.close();
    }
}