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

The following examples show how to use javax.jms.Session#rollback() . 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: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testTransactionRollbackSucceeds() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(_testName.getMethodName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createMessage());

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    try {
        session.rollback();
    } catch (TransactionRolledBackException ex) {
        fail("Should allow a rollback while offline.");
    }

    connection.close();
}
 
Example 2
Source File: TransactedSessionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Test IllegalStateException is thrown if rollback is called on a non-transacted session
 */
@Test
public void testRollbackIllegalState() throws Exception {
   Connection conn = createConnection();

   Session producerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);

   boolean thrown = false;
   try {
      producerSess.rollback();
   } catch (javax.jms.IllegalStateException e) {
      thrown = true;
   }

   ProxyAssertSupport.assertTrue(thrown);
}
 
Example 3
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 4
Source File: JMSUsecase1Test.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendReceiveTransacted() throws Exception {
   // Send a message to the broker.
   connection.start();
   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   ActiveMQDestination destination = createDestination(session, destinationType);
   MessageProducer producer = session.createProducer(destination);
   producer.setDeliveryMode(this.deliveryMode);
   MessageConsumer consumer = session.createConsumer(destination);
   producer.send(session.createTextMessage("test"));

   // Message should not be delivered until commit.
   assertNull(consumer.receiveNoWait());
   session.commit();

   // Make sure only 1 message was delivered.
   Message message = consumer.receive(1000);
   assertNotNull(message);
   assertFalse(message.getJMSRedelivered());
   assertNull(consumer.receiveNoWait());

   // Message should be redelivered is rollback is used.
   session.rollback();

   // Make sure only 1 message was delivered.
   message = consumer.receive(2000);
   assertNotNull(message);
   assertTrue(message.getJMSRedelivered());
   assertNull(consumer.receiveNoWait());

   // If we commit now, the message should not be redelivered.
   session.commit();
   assertNull(consumer.receiveNoWait());
}
 
Example 5
Source File: SingleConnectionFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
	QueueConnectionFactory cf = mock(QueueConnectionFactory.class);
	QueueConnection con = mock(QueueConnection.class);
	QueueSession txSession = mock(QueueSession.class);
	QueueSession nonTxSession = mock(QueueSession.class);

	given(cf.createQueueConnection()).willReturn(con);
	given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession);
	given(txSession.getTransacted()).willReturn(true);
	given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession);

	CachingConnectionFactory scf = new CachingConnectionFactory(cf);
	scf.setReconnectOnException(false);
	Connection con1 = scf.createQueueConnection();
	Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session1.rollback();
	session1.close();
	session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
	session1.close();
	con1.start();
	QueueConnection con2 = scf.createQueueConnection();
	Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
	session2.close();
	session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session2.getTransacted();
	session2.close();  // should lead to rollback
	con2.start();
	con1.close();
	con2.close();
	scf.destroy();  // should trigger actual close

	verify(txSession).rollback();
	verify(txSession).close();
	verify(nonTxSession).close();
	verify(con).start();
	verify(con).stop();
	verify(con).close();
}
 
Example 6
Source File: JMSHeadersAndPropertiesTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void redelivered() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnectionBuilder().setPrefetch(1).build();
    try
    {
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(queue);
        producer.send(session.createTextMessage("A"));
        producer.send(session.createTextMessage("B"));
        session.commit();

        MessageConsumer consumer = session.createConsumer(queue);
        connection.start();

        Message message = consumer.receive(getReceiveTimeout());
        assertTrue("TextMessage should be received", message instanceof TextMessage);
        assertFalse("Unexpected JMSRedelivered after first receive", message.getJMSRedelivered());
        assertEquals("Unexpected message content", "A", ((TextMessage) message).getText());

        session.rollback();

        message = consumer.receive(getReceiveTimeout());
        assertTrue("TextMessage should be received", message instanceof TextMessage);
        assertTrue("Unexpected JMSRedelivered after second receive", message.getJMSRedelivered());
        assertEquals("Unexpected message content", "A", ((TextMessage) message).getText());

        message = consumer.receive(getReceiveTimeout());
        assertTrue("TextMessage should be received", message instanceof TextMessage);
        assertFalse("Unexpected JMSRedelivered for second message", message.getJMSRedelivered());
        assertEquals("Unexpected message content", "B", ((TextMessage) message).getText());

        session.commit();
    }
    finally
    {
        connection.close();
    }
}
 
Example 7
Source File: TimeToLiveTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassiveTTLWithDurableSubscription() throws Exception
{
    long timeToLiveMillis = getReceiveTimeout() * 2;
    String subscriptionName = getTestName() + "_sub";
    Topic topic = createTopic(getTestName());
    TopicConnection connection = getTopicConnection();
    try
    {
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        TopicSubscriber durableSubscriber = session.createDurableSubscriber(topic, subscriptionName);
        MessageProducer producer = session.createProducer(topic);
        producer.setTimeToLive(timeToLiveMillis);
        producer.send(session.createTextMessage("A"));
        producer.setTimeToLive(0);
        producer.send(session.createTextMessage("B"));
        session.commit();

        connection.start();
        Message message = durableSubscriber.receive(getReceiveTimeout());

        assertTrue("TextMessage should be received", message instanceof TextMessage);
        assertEquals("Unexpected message received", "A", ((TextMessage)message).getText());

        Thread.sleep(timeToLiveMillis);

        session.rollback();
        message = durableSubscriber.receive(getReceiveTimeout());

        assertTrue("TextMessage should be received after waiting for TTL", message instanceof TextMessage);
        assertEquals("Unexpected message received after waiting for TTL", "B", ((TextMessage) message).getText());
    }
    finally
    {
        connection.close();
    }
}
 
Example 8
Source File: TopicRedeliverTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test redelivered flag is set on rollbacked transactions
 *
 * @throws Exception
 */
public void testRedilveredFlagSetOnRollback() throws Exception {
   Destination destination = createDestination(getClass().getName());
   Connection connection = createConnection();
   connection.setClientID(idGen.generateId());
   connection.start();
   Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
   MessageConsumer consumer = null;
   if (topic) {
      consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED");
   } else {
      consumer = consumerSession.createConsumer(destination);
   }
   Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = producerSession.createProducer(destination);
   producer.setDeliveryMode(deliveryMode);

   TextMessage sentMsg = producerSession.createTextMessage();
   sentMsg.setText("msg1");
   producer.send(sentMsg);
   producerSession.commit();

   Message recMsg = consumer.receive(RECEIVE_TIMEOUT);
   assertFalse(recMsg.getJMSRedelivered());
   recMsg = consumer.receive(RECEIVE_TIMEOUT);
   consumerSession.rollback();
   recMsg = consumer.receive(RECEIVE_TIMEOUT);
   assertTrue(recMsg.getJMSRedelivered());
   consumerSession.commit();
   assertTrue(recMsg.equals(sentMsg));
   assertTrue(recMsg.getJMSRedelivered());
   connection.close();
}
 
Example 9
Source File: TransactionsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testJMSErrorCoordinatorClosedOnRollback() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();
        testPeer.expectCoordinatorAttach();

        Binary txnId1 = new Binary(new byte[]{ (byte) 5, (byte) 6, (byte) 7, (byte) 8});
        Binary txnId2 = new Binary(new byte[]{ (byte) 1, (byte) 2, (byte) 3, (byte) 4});

        testPeer.expectDeclare(txnId1);
        testPeer.remotelyCloseLastCoordinatorLinkOnDischarge(txnId1, true, true, txnId2);
        testPeer.expectCoordinatorAttach();
        testPeer.expectDeclare(txnId2);
        testPeer.expectDischarge(txnId2, true);

        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

        try {
            session.rollback();
            fail("Transaction should have rolled back");
        } catch (JMSException ex) {
            LOG.info("Caught expected JMSException");
        }

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

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

        testPeer.expectBegin();
        testPeer.expectCoordinatorAttach();

        Binary txnId = new Binary(new byte[]{ (byte) 5, (byte) 6, (byte) 7, (byte) 8});
        testPeer.expectDeclare(txnId);
        testPeer.remotelyCloseLastCoordinatorLink();

        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

        testPeer.waitForAllHandlersToComplete(2000);

        testPeer.expectCoordinatorAttach();
        testPeer.expectDeclare(txnId);

        testPeer.expectDischarge(txnId, true);

        try {
            session.rollback();
            fail("Rollback should have thrown a JMSException");
        } catch (JMSException ex) {
            LOG.info("Caught expected JMSException");
        }

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 11
Source File: JmsRedeliveredTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests rollback message to be marked as redelivered. Session uses client
 * acknowledgement and the destination is a queue.
 *
 * @throws JMSException
 */
public void testQueueRollbackMarksMessageRedelivered() throws JMSException {
   connection.start();

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

   // Get the message... Should not be redelivered.
   MessageConsumer consumer = session.createConsumer(queue);
   Message msg = consumer.receive(1000);
   assertNotNull(msg);
   assertFalse("Message should not be redelivered.", msg.getJMSRedelivered());

   // Rollback.. should cause redelivery.
   session.rollback();

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

   session.commit();
   session.close();
}
 
Example 12
Source File: SingleConnectionFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
	QueueConnectionFactory cf = mock(QueueConnectionFactory.class);
	QueueConnection con = mock(QueueConnection.class);
	QueueSession txSession = mock(QueueSession.class);
	QueueSession nonTxSession = mock(QueueSession.class);

	given(cf.createQueueConnection()).willReturn(con);
	given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession);
	given(txSession.getTransacted()).willReturn(true);
	given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession);

	CachingConnectionFactory scf = new CachingConnectionFactory(cf);
	scf.setReconnectOnException(false);
	Connection con1 = scf.createQueueConnection();
	Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session1.rollback();
	session1.close();
	session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
	session1.close();
	con1.start();
	QueueConnection con2 = scf.createQueueConnection();
	Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
	session2.close();
	session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session2.getTransacted();
	session2.close();  // should lead to rollback
	con2.start();
	con1.close();
	con2.close();
	scf.destroy();  // should trigger actual close

	verify(txSession).rollback();
	verify(txSession).close();
	verify(nonTxSession).close();
	verify(con).start();
	verify(con).stop();
	verify(con).close();
}
 
Example 13
Source File: JmsRollbackRedeliveryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedeliveryOnSingleSession() throws Exception {

   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
   Connection connection = connectionFactory.createConnection();
   connection.start();

   populateDestination(nbMessages, destinationName, connection);

   // Consume messages and rollback transactions
   {
      AtomicInteger received = new AtomicInteger();
      Map<String, Boolean> rolledback = new ConcurrentHashMap<>();
      Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
      Destination destination = session.createQueue(destinationName);
      while (received.get() < nbMessages) {
         MessageConsumer consumer = session.createConsumer(destination);
         TextMessage msg = (TextMessage) consumer.receive(6000000);
         if (msg != null) {
            if (rolledback.put(msg.getText(), Boolean.TRUE) != null) {
               LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID());
               assertTrue(msg.getJMSRedelivered());
               session.commit();
            } else {
               LOG.info("Rollback message " + msg.getText() + " id: " + msg.getJMSMessageID());
               session.rollback();
            }
         }
         consumer.close();
      }
      session.close();
   }
}
 
Example 14
Source File: SingleConnectionFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException {
	QueueConnectionFactory cf = mock(QueueConnectionFactory.class);
	QueueConnection con = mock(QueueConnection.class);
	QueueSession txSession = mock(QueueSession.class);
	QueueSession nonTxSession = mock(QueueSession.class);

	given(cf.createQueueConnection()).willReturn(con);
	given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession);
	given(txSession.getTransacted()).willReturn(true);
	given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession);

	CachingConnectionFactory scf = new CachingConnectionFactory(cf);
	scf.setReconnectOnException(false);
	Connection con1 = scf.createQueueConnection();
	Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session1.rollback();
	session1.close();
	session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
	session1.close();
	con1.start();
	QueueConnection con2 = scf.createQueueConnection();
	Session session2 = con2.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
	session2.close();
	session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
	session2.getTransacted();
	session2.close();  // should lead to rollback
	con2.start();
	con1.close();
	con2.close();
	scf.destroy();  // should trigger actual close

	verify(txSession).rollback();
	verify(txSession).close();
	verify(nonTxSession).close();
	verify(con).start();
	verify(con).stop();
	verify(con).close();
}
 
Example 15
Source File: JmsRollbackRedeliveryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateRedeliveryCountOnRollbackWithPrefetch0() throws Exception {

   final int numMessages = 1;
   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl + "?jms.prefetchPolicy.queuePrefetch=0");
   Connection connection = connectionFactory.createConnection();
   connection.start();

   populateDestination(numMessages, destinationName, connection);

   {
      AtomicInteger received = new AtomicInteger();
      final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries();
      while (received.get() < maxRetries) {
         Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
         Destination destination = session.createQueue(destinationName);

         MessageConsumer consumer = session.createConsumer(destination);
         TextMessage msg = (TextMessage) consumer.receive(1000);
         if (msg != null) {
            LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID());
            assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount"));
            session.rollback();
         }
         session.close();
      }

      consumeMessage(connection, maxRetries + 1);
   }
}
 
Example 16
Source File: CommitRollbackTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void transactionSharedByConsumers() throws Exception
{
    final Queue queue1 = createQueue("Q1");
    final Queue queue2 = createQueue("Q2");
    Connection connection = getConnection();
    try
    {
        Utils.sendTextMessage(connection, queue1, "queue1Message1");
        Utils.sendTextMessage(connection, queue1, "queue1Message2");
        Utils.sendTextMessage(connection, queue2, "queue2Message1");
        Utils.sendTextMessage(connection, queue2, "queue2Message2");

        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageConsumer messageConsumer1 = session.createConsumer(queue1);
        MessageConsumer messageConsumer2 = session.createConsumer(queue2);
        connection.start();

        Message message1 = messageConsumer1.receive(getReceiveTimeout());
        assertTrue("Text message not received from first queue", message1 instanceof TextMessage);
        assertEquals("Unexpected message received from first queue",
                     "queue1Message1",
                     ((TextMessage) message1).getText());

        Message message2 = messageConsumer2.receive(getReceiveTimeout());
        assertTrue("Text message not received from second queue", message2 instanceof TextMessage);
        assertEquals("Unexpected message received from second queue",
                     "queue2Message1",
                     ((TextMessage) message2).getText());

        session.rollback();

        message1 = messageConsumer1.receive(getReceiveTimeout());
        assertTrue("Text message not received from first queue", message1 instanceof TextMessage);
        assertEquals("Unexpected message received from first queue",
                     "queue1Message1",
                     ((TextMessage) message1).getText());

        message2 = messageConsumer2.receive(getReceiveTimeout());
        assertTrue("Text message not received from second queue", message2 instanceof TextMessage);
        assertEquals("Unexpected message received from second queue",
                     "queue2Message1",
                     ((TextMessage) message2).getText());

        session.commit();

        Message message3 = messageConsumer1.receive(getReceiveTimeout());
        assertTrue("Text message not received from first queue", message3 instanceof TextMessage);
        assertEquals("Unexpected message received from first queue",
                     "queue1Message2",
                     ((TextMessage) message3).getText());

        Message message4 = messageConsumer2.receive(getReceiveTimeout());
        assertTrue("Text message not received from second queue", message4 instanceof TextMessage);
        assertEquals("Unexpected message received from second queue",
                     "queue2Message2",
                     ((TextMessage) message4).getText());
    }
    finally
    {
        connection.close();
    }
}
 
Example 17
Source File: NonBlockingConsumerRedeliveryTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testMessageDeleiveredWhenNonBlockingEnabled() throws Exception {

   final LinkedHashSet<Message> received = new LinkedHashSet<>();
   final LinkedHashSet<Message> beforeRollback = new LinkedHashSet<>();
   final LinkedHashSet<Message> afterRollback = new LinkedHashSet<>();

   Connection connection = connectionFactory.createConnection();
   Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
   Destination destination = session.createQueue(destinationName);
   MessageConsumer consumer = session.createConsumer(destination);

   consumer.setMessageListener(new MessageListener() {
      @Override
      public void onMessage(Message message) {
         received.add(message);
      }
   });

   sendMessages();

   session.commit();
   connection.start();

   assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
      @Override
      public boolean isSatisified() throws Exception {
         LOG.info("Consumer has received " + received.size() + " messages.");
         return received.size() == MSG_COUNT;
      }
   }));

   beforeRollback.addAll(received);
   received.clear();
   session.rollback();

   assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {
      @Override
      public boolean isSatisified() throws Exception {
         LOG.info("Consumer has received " + received.size() + " messages since rollback.");
         return received.size() == MSG_COUNT;
      }
   }));

   afterRollback.addAll(received);
   received.clear();

   assertEquals(beforeRollback.size(), afterRollback.size());
   assertEquals(beforeRollback, afterRollback);
   session.commit();
}
 
Example 18
Source File: QueueLocalTransactionRollbackTest.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 testProducerRollbackTransaction(String port,
                                            String adminUsername,
                                            String adminPassword,
                                            String brokerHostname) throws NamingException, JMSException {
    String queueName = "testProducerRollbackTransaction";
    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();

    // send 100 messages
    Session producerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    // rollback all sent messages
    producerSession.rollback();

    // consume messages
    Session subscriberSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    Message message = consumer.receive(1000);
    Assert.assertNull(message, "Messages should not receive upon publisher rollback");

    producerSession.close();
    subscriberSession.close();
    connection.close();
}
 
Example 19
Source File: TransactedSessionTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSimpleRollback() throws Exception {
   // send a message
   Connection conn = null;

   try {
      conn = createConnection();
      Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      s.createProducer(queue1).send(s.createTextMessage("one"));

      s.close();

      s = conn.createSession(true, Session.SESSION_TRANSACTED);
      MessageConsumer c = s.createConsumer(queue1);
      conn.start();
      Message m = c.receive(1000);
      ProxyAssertSupport.assertNotNull(m);

      ProxyAssertSupport.assertEquals("one", ((TextMessage) m).getText());
      ProxyAssertSupport.assertFalse(m.getJMSRedelivered());
      ProxyAssertSupport.assertEquals(1, m.getIntProperty("JMSXDeliveryCount"));

      s.rollback();

      // get the message again
      m = c.receive(1000);
      ProxyAssertSupport.assertNotNull(m);

      ProxyAssertSupport.assertTrue(m.getJMSRedelivered());
      ProxyAssertSupport.assertEquals(2, m.getIntProperty("JMSXDeliveryCount"));

      conn.close();

      Long i = getMessageCountForQueue("Queue1");

      ProxyAssertSupport.assertEquals(1, i.intValue());
   } finally {
      if (conn != null) {
         conn.close();
      }
      removeAllMessages(queue1.getQueueName(), true);
   }
}
 
Example 20
Source File: PrefetchTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void consumeBeyondPrefetch() throws Exception
{
    Connection connection1 = getConnectionBuilder().setPrefetch(1).build();
    Queue queue = createQueue(getTestName());
    try
    {
        connection1.start();

        final Session session1 = connection1.createSession(true, Session.SESSION_TRANSACTED);
        MessageConsumer consumer1 = session1.createConsumer(queue);

        Utils.sendMessages(connection1, queue, 5);

        Message message = consumer1.receive(getReceiveTimeout());
        assertNotNull(message);
        assertEquals(0, message.getIntProperty(INDEX));

        message = consumer1.receive(getReceiveTimeout());
        assertNotNull(message);
        assertEquals(1, message.getIntProperty(INDEX));
        message = consumer1.receive(getReceiveTimeout());
        assertNotNull(message);
        assertEquals(2, message.getIntProperty(INDEX));

        forceSync(session1);

        // In pre 0-10, in a transaction session the client does not ack the message until the commit occurs
        // so the message observed by another connection will have the index 3 rather than 4.
        Connection connection2 = getConnection();
        try
        {
            Session session2 = connection2.createSession(true, Session.SESSION_TRANSACTED);
            MessageConsumer consumer2 = session2.createConsumer(queue);
            connection2.start();

            message = consumer2.receive(getReceiveTimeout());
            assertNotNull(message);
            assertEquals("Received message has unexpected index",
                         PRE_010_PROTOCOLS.contains(getProtocol()) ? 3 : 4,
                         message.getIntProperty(INDEX));

            session2.rollback();
        }
        finally
        {
            connection2.close();
        }
    }
    finally
    {
        connection1.close();
    }
}