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

The following examples show how to use javax.jms.Session#commit() . 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: TestIntegrationActiveMQ.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
private void putQueue(List<String> events) throws Exception {
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  Connection connection = factory.createConnection();
  connection.start();

  Session session = connection.createSession(true,
      Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createQueue(DESTINATION_NAME);
  MessageProducer producer = session.createProducer(destination);


  for(String event : events) {
    TextMessage message = session.createTextMessage();
    message.setText(event);
    producer.send(message);
  }
  session.commit();
  session.close();
  connection.close();
}
 
Example 2
Source File: MessagingACLTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublishToTempTopicSuccess() throws Exception
{
    configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1),
                 isLegacyClient() ? String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE name=\"amq.topic\"", USER1) :
                         String.format("ACL ALLOW-LOG %s PUBLISH EXCHANGE temporary=\"true\"", USER1));

    Connection connection = getConnectionBuilder().setUsername(USER1).setPassword(USER1_PASSWORD).build();
    try
    {
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        connection.start();

        TemporaryTopic temporaryTopic = session.createTemporaryTopic();
        MessageProducer producer = session.createProducer(temporaryTopic);
        producer.send(session.createMessage());
        session.commit();
    }
    finally
    {
        connection.close();
    }
}
 
Example 3
Source File: PersistentMessagingTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private List<Message> sendMessages(Session session, MessageProducer producer,
                                   final int deliveryMode,
                                   final int startIndex, final int count) throws Exception
{
    final List<Message> sentMessages = new ArrayList<>();
    for (int i = startIndex; i < startIndex + count; i++)
    {
        Message message = session.createTextMessage(UUID.randomUUID().toString());
        message.setIntProperty(INT_PROPERTY, i);
        message.setStringProperty(STRING_PROPERTY, UUID.randomUUID().toString());

        producer.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
        sentMessages.add(message);
    }

    session.commit();
    return sentMessages;
}
 
Example 4
Source File: JmsTransactedConsumerTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=60000)
public void testJMSXDeliveryCount() throws Exception {
    sendToAmqQueue(1);

    connection = createAmqpConnection();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    assertEquals(true, session.getTransacted());
    Queue queue = session.createQueue(name.getMethodName());
    MessageConsumer consumer = session.createConsumer(queue);
    connection.start();

    // we receive a message...it should be delivered once and not be Re-delivered.
    Message message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(false, message.getJMSRedelivered());
    int jmsxDeliveryCount = message.getIntProperty("JMSXDeliveryCount");
    LOG.info("Incoming message has delivery count: {}", jmsxDeliveryCount);
    assertEquals(1, jmsxDeliveryCount);
    session.rollback();

    // we receive again a message
    message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(true, message.getJMSRedelivered());
    jmsxDeliveryCount = message.getIntProperty("JMSXDeliveryCount");
    LOG.info("Redelivered message has delivery count: {}", jmsxDeliveryCount);
    assertEquals(2, jmsxDeliveryCount);
    session.rollback();

    // we receive again a message
    message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(true, message.getJMSRedelivered());
    jmsxDeliveryCount = message.getIntProperty("JMSXDeliveryCount");
    LOG.info("Redelivered message has delivery count: {}", jmsxDeliveryCount);
    assertEquals(3, jmsxDeliveryCount);
    session.commit();
}
 
Example 5
Source File: AcknowledgeTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void acknowledge(final int ackMode, final Session session, final Message message) throws JMSException
{
    switch(ackMode)
    {
        case Session.SESSION_TRANSACTED:
            session.commit();
            break;
        case Session.CLIENT_ACKNOWLEDGE:
            message.acknowledge();
            break;
        default:
    }
}
 
Example 6
Source File: JMSConsumer2Test.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedispatchOfUncommittedTx() throws Exception {
   connection.start();
   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);

   sendMessages(connection, destination, 2);

   MessageConsumer consumer = session.createConsumer(destination);
   Message m = consumer.receive(1000);
   assertNotNull(m);
   m = consumer.receive(5000);
   assertNotNull(m);
   assertFalse("redelivered flag set", m.getJMSRedelivered());

   // install another consumer while message dispatch is unacked/uncommitted
   Session redispatchSession = connection.createSession(true, Session.SESSION_TRANSACTED);
   MessageConsumer redispatchConsumer = redispatchSession.createConsumer(destination);

   // no commit so will auto rollback and get re-dispatched to
   // redisptachConsumer
   session.close();

   Message msg = redispatchConsumer.receive(3000);
   assertNotNull(msg);

   assertTrue("redelivered flag set", msg.getJMSRedelivered());
   assertEquals(2, msg.getLongProperty("JMSXDeliveryCount"));

   msg = redispatchConsumer.receive(1000);
   assertNotNull(msg);
   assertTrue(msg.getJMSRedelivered());
   assertEquals(2, msg.getLongProperty("JMSXDeliveryCount"));
   redispatchSession.commit();

   assertNull(redispatchConsumer.receive(500));
   redispatchSession.close();
}
 
Example 7
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testPassthroughOfRollbackErrorCoordinatorClosedOnCommit() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        final String testPeerURI = createPeerURI(testPeer);
        LOG.info("Original peer is at: {}", testPeerURI);

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen();
        testPeer.expectBegin();
        testPeer.expectBegin();
        testPeer.expectCoordinatorAttach();

        JmsConnection connection = establishAnonymousConnecton(testPeer);
        connection.start();

        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, false, true, txnId2);
        testPeer.expectCoordinatorAttach();
        testPeer.expectDeclare(txnId2);
        testPeer.expectDischarge(txnId2, true);

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

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

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 8
Source File: TransactionsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testTransactionCommitTimesOut() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.setRequestTimeout(500);
        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);

        // Expect discharge but don't respond so that the request timeout kicks in and fails
        // the discharge.  The pipelined declare should arrive as well and we respond with
        // successful declare.
        testPeer.expectDischargeButDoNotRespond(txnId1, false);
        testPeer.expectDeclare(txnId2);

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

        try {
            session.commit();
            fail("Should have timed out waiting for declare.");
        } catch (JmsOperationTimedOutException jmsEx) {
        } catch (Throwable error) {
            fail("Should have caught an timed out exception:");
            LOG.error("Caught -> ", error);
        }

        // Session rolls back on close
        testPeer.expectDischarge(txnId2, true);

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 9
Source File: TopicRedeliverTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * check messages are actuallly sent on a tx rollback
 *
 * @throws Exception
 */

public void testTransactionRollbackOnSend() 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 = 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);
   consumerSession.commit();
   assertTrue(recMsg.equals(sentMsg));

   sentMsg = producerSession.createTextMessage();
   sentMsg.setText("msg2");
   producer.send(sentMsg);
   producerSession.rollback();

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

   recMsg = consumer.receive(RECEIVE_TIMEOUT);
   assertTrue(recMsg.equals(sentMsg));
   consumerSession.commit();

   connection.close();
}
 
Example 10
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 11
Source File: JmsTxProducerFailoverTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=60000)
@Repeat(repetitions = 1)
public void testTxProducerSendsThenFailoverCommitFails() throws Exception {
    URI brokerURI = new URI(getAmqpFailoverURI());

    connection = createAmqpConnection(brokerURI);
    connection.start();

    final int MSG_COUNT = 5;
    final Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(name.getMethodName());
    final MessageProducer producer = session.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
    assertEquals(0, proxy.getQueueSize());

    for (int i = 0; i < MSG_COUNT; ++i) {
        LOG.debug("Producer sening message #{}", i + 1);
        producer.send(session.createTextMessage("Message: " + i));
    }

    assertEquals(0, proxy.getQueueSize());

    stopPrimaryBroker();
    restartPrimaryBroker();

    proxy = getProxyToQueue(name.getMethodName());
    assertEquals(0, proxy.getQueueSize());

    try {
        session.commit();
        fail("Session commit should have failed with TX rolled back.");
    } catch (TransactionRolledBackException rb) {
        LOG.info("Transacted commit failed after failover: {}", rb.getMessage());
    }

    assertEquals(0, proxy.getQueueSize());
}
 
Example 12
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 13
Source File: SortedQueueTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void sendAndCommitMessage(final Session producerSession, final MessageProducer producer,
                                  final String keyValue) throws Exception
{
    final Message message = producerSession.createTextMessage("Message Text: Key Value" + keyValue);
    message.setStringProperty(TEST_SORT_KEY, keyValue);
    producer.send(message);
    producerSession.commit();
}
 
Example 14
Source File: TestGetJMSQueue.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendTextToQueue() throws Exception {
    PutJMS putJms = new PutJMS();
    TestRunner putRunner = TestRunners.newTestRunner(putJms);
    putRunner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER);
    putRunner.setProperty(JmsProperties.URL, "vm://localhost?broker.persistent=false");
    putRunner.setProperty(JmsProperties.DESTINATION_TYPE, JmsProperties.DESTINATION_TYPE_QUEUE);
    putRunner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing");
    putRunner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO);

    WrappedMessageProducer wrappedProducer = JmsFactory.createMessageProducer(putRunner.getProcessContext(), true);
    final Session jmsSession = wrappedProducer.getSession();
    final MessageProducer producer = wrappedProducer.getProducer();
    final Message message = jmsSession.createTextMessage("Hello World");

    producer.send(message);
    jmsSession.commit();

    GetJMSQueue getJmsQueue = new GetJMSQueue();
    TestRunner runner = TestRunners.newTestRunner(getJmsQueue);
    runner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER);
    runner.setProperty(JmsProperties.URL, "vm://localhost?broker.persistent=false");
    runner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing");
    runner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO);

    runner.run();

    List<MockFlowFile> flowFiles = runner
            .getFlowFilesForRelationship(new Relationship.Builder().name("success").build());

    assertTrue(flowFiles.size() == 1);
    MockFlowFile successFlowFile = flowFiles.get(0);
    successFlowFile.assertContentEquals("Hello World");
    successFlowFile.assertAttributeEquals("jms.JMSDestination", "queue.testing");
    producer.close();
    jmsSession.close();
}
 
Example 15
Source File: AbstractConsumer.java    From jim-framework with Apache License 2.0 4 votes vote down vote up
private void commit(Session session) throws JMSException {
    if(session.getTransacted()) {
        session.commit();
    }
}
 
Example 16
Source File: ForceDeleteQueue.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testForceDelete() throws Exception {
   SimpleString queueName = SimpleString.toSimpleString("testForceDelete");
   server.addAddressInfo(new AddressInfo(queueName, RoutingType.ANYCAST));
   server.createQueue(queueName, RoutingType.ANYCAST, queueName, null, true, false);

   ConnectionFactory factory = CFUtil.createConnectionFactory(protocol, uri);
   Connection conn = factory.createConnection();

   AssertionLoggerHandler.startCapture();
   try {
      Session session = conn.createSession(true, Session.SESSION_TRANSACTED);
      Queue queue = session.createQueue(queueName.toString());
      MessageProducer producer = session.createProducer(queue);
      for (int i = 0; i < 1000; i++) {
         TextMessage message = session.createTextMessage("Text " + i);
         producer.send(message);
      }
      session.commit();

      org.apache.activemq.artemis.core.server.Queue serverQueue = server.locateQueue(queueName);

      Wait.assertEquals(1000, serverQueue::getMessageCount);

      conn.close();

      conn = factory.createConnection();
      session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      conn.start();

      LinkedListIterator<MessageReference> queueiterator =  serverQueue.browserIterator();
      ArrayList<Long> listQueue = new ArrayList<>(1000);

      while (queueiterator.hasNext()) {
         MessageReference ref = queueiterator.next();

         listQueue.add(ref.getMessageID());
      }

      queueiterator.close();

      MessageConsumer consumer = session.createConsumer(queue);

      Wait.assertTrue(() -> serverQueue.getDeliveringCount() > 100);

      for (Long l : listQueue) {
         // this is forcing an artificial situation where the message was removed during a failure condition
         server.getStorageManager().deleteMessage(l);
      }

      server.destroyQueue(queueName, null, false);

      for (RemotingConnection connection : server.getRemotingService().getConnections()) {
         connection.fail(new ActiveMQException("failure"));
      }


      Assert.assertFalse(AssertionLoggerHandler.findText("Cannot find add info"));


   } finally {
      AssertionLoggerHandler.stopCapture();
      try {
         conn.close();
      } catch (Throwable ignored) {
      }
   }

}
 
Example 17
Source File: FailoverTransactionTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailoverWithConnectionConsumer() throws Exception {
   LOG.info(this + " running test testFailoverWithConnectionConsumer");
   startCleanBroker();
   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
   configureConnectionFactory(cf);
   Connection connection = cf.createConnection();
   connection.start();
   final CountDownLatch connectionConsumerGotOne = new CountDownLatch(1);

   try {
      Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
      Queue destination = session.createQueue(QUEUE_NAME);

      final Session poolSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      connection.createConnectionConsumer(destination, null, new ServerSessionPool() {
         @Override
         public ServerSession getServerSession() throws JMSException {
            return new ServerSession() {
               @Override
               public Session getSession() throws JMSException {
                  return poolSession;
               }

               @Override
               public void start() throws JMSException {
                  connectionConsumerGotOne.countDown();
                  poolSession.run();
               }
            };
         }
      }, 1);

      MessageConsumer consumer = session.createConsumer(destination);
      MessageProducer producer;
      TextMessage message;
      final int count = 10;
      for (int i = 0; i < count; i++) {
         producer = session.createProducer(destination);
         message = session.createTextMessage("Test message: " + count);
         producer.send(message);
         producer.close();
      }

      // restart to force failover and connection state recovery before the commit
      broker.stop();
      startBroker();

      session.commit();
      for (int i = 0; i < count - 1; i++) {
         Message received = consumer.receive(20000);
         Assert.assertNotNull("Failed to get message: " + count, received);
      }
      session.commit();
   } finally {
      connection.close();
   }

   Assert.assertTrue("connectionconsumer did not get a message", connectionConsumerGotOne.await(10, TimeUnit.SECONDS));
}
 
Example 18
Source File: SuperTestPayload.java    From jqm with Apache License 2.0 4 votes vote down vote up
@Override
public void start()
{
	System.out.println("Thread context class loader is: " + Thread.currentThread().getContextClassLoader());
	System.out.println("Class class loader used for loading test class is: " + this.getClass().getClassLoader());
	int nb = 0;

	try
	{
		// Get the QCF
		Object o = NamingManager.getInitialContext(null).lookup("jms/qcf");
		System.out.println("Received a " + o.getClass());

		// Do as cast & see if no errors
		QueueConnectionFactory qcf = (QueueConnectionFactory) o;

		// Get the Queue
		Object p = NamingManager.getInitialContext(null).lookup("jms/testqueue");
		System.out.println("Received a " + p.getClass());
		Queue q = (Queue) p;

		// Now that we are sure that JNDI works, let's write a message
		System.out.println("Opening connection & session to the broker");
		Connection connection = qcf.createConnection();
		connection.start();
		Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

		System.out.println("Creating producer");
		MessageProducer producer = session.createProducer(q);
		TextMessage message = session.createTextMessage("HOUBA HOP. SIGNED: MARSUPILAMI");

		System.out.println("Sending message");
		producer.send(message);
		producer.close();
		session.commit();
		System.out.println("A message was sent to the broker");

		// Browse and check the message is there
		Connection connection2 = qcf.createConnection();
		connection2.start();
		Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
		QueueBrowser qb = session2.createBrowser(q);
		Enumeration<TextMessage> msgs = qb.getEnumeration();
		while (msgs.hasMoreElements())
		{
			TextMessage msg = msgs.nextElement();
			System.out.println("Message received: " + msg.getText());
			nb++;
		}
		System.out.println("Browsing will end here");
		qb.close();
		System.out.println("End of browsing. Nb of message read: " + nb);

		// We are done!
		connection.close();
		connection2.close();

	} catch (Exception e)
	{
		e.printStackTrace();
	}

	if (nb == 0)
		throw new RuntimeException("test has failed - no messages were received.");
}
 
Example 19
Source File: FailoverConsumerOutstandingCommitTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testRollbackFailoverConsumerTx() throws Exception {
   server = createBroker();
   server.start();

   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
   cf.setConsumerFailoverRedeliveryWaitPeriod(10000);
   final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
   connection.start();

   final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   final Queue destination = producerSession.createQueue(QUEUE_NAME);

   final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
   final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
   assertNull("no message yet", testConsumer.receiveNoWait());

   produceMessage(producerSession, destination, 1);
   producerSession.close();

   // consume then rollback after restart
   Message msg = testConsumer.receive(5000);
   assertNotNull(msg);

   // restart with outstanding delivered message
   server.stop();
   server = createBroker();
   server.start();

   consumerSession.rollback();

   // receive again
   msg = testConsumer.receive(10000);
   assertNotNull("got message again after rollback", msg);

   consumerSession.commit();

   // close before sweep
   consumerSession.close();
   msg = receiveMessage(cf, destination);
   assertNull("should be nothing left after commit", msg);
   connection.close();
}
 
Example 20
Source File: JmsTxConsumerFailoverTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout=60000)
public void testTxConsumerReceiveAfterFailoverCommits() throws Exception {
    URI brokerURI = new URI(getAmqpFailoverURI());

    connection = createAmqpConnection(brokerURI);
    connection.start();

    final int MSG_COUNT = 5;
    final Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(name.getMethodName());
    final MessageConsumer consumer = session.createConsumer(queue);

    sendMessages(connection, queue, MSG_COUNT);
    QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
    assertEquals(MSG_COUNT, proxy.getQueueSize());

    stopPrimaryBroker();
    restartPrimaryBroker();

    assertTrue("Should have a new connection.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisfied() throws Exception {
            return brokerService.getAdminView().getCurrentConnectionsCount() == 1;
        }
    }, TimeUnit.SECONDS.toMillis(30), TimeUnit.MILLISECONDS.toMillis(100)));

    assertTrue("Should have a recovered consumer.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisfied() throws Exception {
            return brokerService.getAdminView().getQueueSubscribers().length == 1;
        }
    }, TimeUnit.SECONDS.toMillis(30), TimeUnit.MILLISECONDS.toMillis(50)));

    for (int i = 0; i < MSG_COUNT; ++i) {
        Message received = consumer.receive(3000);
        assertNotNull("Mesage was not expected but not received", received);
    }

    try {
        session.commit();
        LOG.info("Transacted commit ok after failover.");
    } catch (TransactionRolledBackException rb) {
        fail("Session commit should not have failed with TX rolled back.");
    }

    assertEquals(0, proxy.getQueueSize());
}