Java Code Examples for javax.jms.TopicConnection#close()

The following examples show how to use javax.jms.TopicConnection#close() . 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: SingleConnectionFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testWithTopicConnection() throws JMSException {
	Connection con = mock(TopicConnection.class);

	SingleConnectionFactory scf = new SingleConnectionFactory(con);
	TopicConnection con1 = scf.createTopicConnection();
	con1.start();
	con1.stop();
	con1.close();
	TopicConnection con2 = scf.createTopicConnection();
	con2.start();
	con2.stop();
	con2.close();
	scf.destroy();  // should trigger actual close

	verify(con, times(2)).start();
	verify(con, times(2)).stop();
	verify(con).close();
	verifyNoMoreInteractions(con);
}
 
Example 2
Source File: JMSSample.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private static void publish() throws JMSException {
    // get topic connection
    TopicConnectionFactory connectionFactory = new WeEventConnectionFactory(defaultBrokerUrl);
    TopicConnection connection = connectionFactory.createTopicConnection();

    // start connection
    connection.start();
    // create session
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

    // create topic
    Topic topic = session.createTopic(topicName);

    // create publisher
    TopicPublisher publisher = session.createPublisher(topic);
    // send message
    BytesMessage msg = session.createBytesMessage();
    msg.writeBytes(("hello WeEvent").getBytes(StandardCharsets.UTF_8));
    publisher.publish(msg);

    System.out.print("send done.");
    connection.close();
}
 
Example 3
Source File: AcknowledgementTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Topics shouldn't hold on to messages if there are no subscribers
 */
@Test
public void testPersistentMessagesForTopicDropped() throws Exception {
   TopicConnection topicConn = createTopicConnection();
   TopicSession sess = topicConn.createTopicSession(true, 0);
   TopicPublisher pub = sess.createPublisher(ActiveMQServerTestCase.topic1);
   pub.setDeliveryMode(DeliveryMode.PERSISTENT);

   Message m = sess.createTextMessage("testing123");
   pub.publish(m);
   sess.commit();

   topicConn.close();

   checkEmpty(ActiveMQServerTestCase.topic1);
}
 
Example 4
Source File: NetworkRemovesSubscriptionsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testWithOneSubscriber() throws Exception {

      TopicConnection connection = connectionFactory.createTopicConnection();
      connection.start();
      TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

      TopicSubscriber subscriber = subscriberSession.createSubscriber(topic);
      DummyMessageListener listener = new DummyMessageListener();
      subscriber.setMessageListener(listener);
      subscriber.close();
      subscriberSession.close();
      connection.close();
      Thread.sleep(1000);
      Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic);
      assertNotNull(dest);
      assertTrue(dest.getConsumers().isEmpty());
   }
 
Example 5
Source File: NetworkRemovesSubscriptionsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Running this test you can produce a leak of only 2 ConsumerInfo on BE
 * broker, NOT 200 as in other cases!
 */
public void testWithoutSessionAndSubsciberClosePlayAround() throws Exception {

   TopicConnection connection = connectionFactory.createTopicConnection();
   connection.start();

   for (int i = 0; i < 100; i++) {
      TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      TopicSubscriber subscriber = subscriberSession.createSubscriber(topic);
      DummyMessageListener listener = new DummyMessageListener();
      subscriber.setMessageListener(listener);
      if (i != 50) {
         subscriber.close();
         subscriberSession.close();
      }
   }

   connection.close();
   Thread.sleep(1000);
   Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic);
   assertNotNull(dest);
   assertTrue(dest.getConsumers().isEmpty());
}
 
Example 6
Source File: XAConnectionPoolTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testSenderAndPublisherDest() throws Exception {
    JmsPoolXAConnectionFactory pcf = createXAPooledConnectionFactory();

    QueueConnection connection = pcf.createQueueConnection();
    QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueSender sender = session.createSender(session.createQueue("AA"));
    assertNotNull(sender.getQueue().getQueueName());

    connection.close();

    TopicConnection topicConnection = pcf.createTopicConnection();
    TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    TopicPublisher topicPublisher = topicSession.createPublisher(topicSession.createTopic("AA"));
    assertNotNull(topicPublisher.getTopic().getTopicName());

    topicConnection.close();
    pcf.stop();
}
 
Example 7
Source File: AcknowledgementTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Topics shouldn't hold on to messages when the non-durable subscribers close
 */
@Test
public void testPersistentMessagesForTopicDropped2() throws Exception {
   TopicConnection topicConn = createTopicConnection();
   topicConn.start();
   TopicSession sess = topicConn.createTopicSession(true, 0);
   TopicPublisher pub = sess.createPublisher(ActiveMQServerTestCase.topic1);
   TopicSubscriber sub = sess.createSubscriber(ActiveMQServerTestCase.topic1);
   pub.setDeliveryMode(DeliveryMode.PERSISTENT);

   Message m = sess.createTextMessage("testing123");
   pub.publish(m);
   sess.commit();

   // receive but rollback
   TextMessage m2 = (TextMessage) sub.receive(3000);

   ProxyAssertSupport.assertNotNull(m2);
   ProxyAssertSupport.assertEquals("testing123", m2.getText());

   sess.rollback();

   topicConn.close();

   checkEmpty(ActiveMQServerTestCase.topic1);
}
 
Example 8
Source File: DurableSubscriptionHangTestCase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void produceExpiredAndOneNonExpiredMessages() throws JMSException {
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
   TopicConnection connection = connectionFactory.createTopicConnection();
   TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
   Topic topic = session.createTopic(topicName);
   MessageProducer producer = session.createProducer(topic);
   producer.setTimeToLive(TimeUnit.SECONDS.toMillis(1));
   for (int i = 0; i < 40000; i++) {
      sendRandomMessage(session, producer);
   }
   producer.setTimeToLive(TimeUnit.DAYS.toMillis(1));
   sendRandomMessage(session, producer);
   connection.close();
   LOG.info("produceExpiredAndOneNonExpiredMessages done");
}
 
Example 9
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 10
Source File: SessionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateQueueOnATopicSession() throws Exception {
   TopicConnection c = (TopicConnection) getConnectionFactory().createConnection();
   TopicSession s = c.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

   try {
      s.createQueue("TestQueue");
      ProxyAssertSupport.fail("should throw IllegalStateException");
   } catch (javax.jms.IllegalStateException e) {
      // OK
   }
   c.close();
}
 
Example 11
Source File: TopicWildcardTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
private void assertNullWithPublishSubscribeForTopics(String publishTopicName,
                                                     String subscribeTopicName) throws Exception {

    int numberOfMessages = 100;

    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .withTopic(publishTopicName)
            .withTopic(subscribeTopicName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic subscriberDestination = (Topic) initialContext.lookup(subscribeTopicName);
    TopicSubscriber subscriber = subscriberSession.createSubscriber(subscriberDestination);

    TopicSession publisherSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic publisherDestination = (Topic) initialContext.lookup(publishTopicName);
    TopicPublisher publisher = publisherSession.createPublisher(publisherDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        publisher.publish(publisherSession.createTextMessage("Test message " + i));
    }

    publisherSession.close();

    Message message = subscriber.receive(1000);
    Assert.assertNull(message, "A message was received where no message was expected");

    subscriberSession.close();
    connection.close();
}
 
Example 12
Source File: AuthenticationTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({ "broker-port", "test-username", "test-password" })
@Test(description = "Test valid user password with special characters")
public void testPasswordWithSpecialCharacters(String port, String testUsername, String testPassword) throws
        Exception {
    String topicName = "MyTopic1";
    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(testUsername, testPassword, "localhost", port).withTopic(topicName).build();
    TopicConnectionFactory connectionFactory = (TopicConnectionFactory) initialContext
            .lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();
    connection.close();
}
 
Example 13
Source File: SingleConnectionFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage() throws JMSException {
	TopicConnectionFactory cf = mock(TopicConnectionFactory.class);
	TopicConnection con = mock(TopicConnection.class);
	TopicSession txSession = mock(TopicSession.class);
	TopicSession nonTxSession = mock(TopicSession.class);

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

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

	verify(txSession).close();
	verify(nonTxSession).close();
	verify(con).start();
	verify(con).stop();
	verify(con).close();
}
 
Example 14
Source File: ConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test that ConnectionFactory can be cast to TopicConnectionFactory and TopicConnection can be
 * created.
 */
@Test
public void testTopicConnectionFactory() throws Exception {
   deployConnectionFactory(0, JMSFactoryType.TOPIC_CF, "CF_TOPIC_XA_FALSE", "/CF_TOPIC_XA_FALSE");
   TopicConnectionFactory qcf = (TopicConnectionFactory) ic.lookup("/CF_TOPIC_XA_FALSE");
   TopicConnection tc = qcf.createTopicConnection();
   tc.close();
   undeployConnectionFactory("CF_TOPIC_XA_FALSE");
}
 
Example 15
Source File: MultipleTopicSubscriberTestCase.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 testMultipleTopicSubscribersOnSameSession(String port,
                                                      String adminUsername,
                                                      String adminPassword,
                                                      String brokerHostname)
        throws NamingException, JMSException, InterruptedException {
    String queueName = "testMultipleTopicSubscribersOnSameSession";
    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withTopic(queueName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    TopicSession subscriberSession = connection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
    Topic topic = (Topic) initialContext.lookup(queueName);

    int numberOfConsumers = 3;
    int messagesPerConsumer = 1000;
    int maxNumberOfMessages = numberOfConsumers * messagesPerConsumer;
    LinkedBlockingQueue<MessageResult> receiveQueue =  new LinkedBlockingQueue<>(maxNumberOfMessages);

    TopicSubscriber consumers[] = new TopicSubscriber[numberOfConsumers];
    int messageCount[] = new int[numberOfConsumers];

    for (int consumerIndex = 0; consumerIndex < numberOfConsumers; consumerIndex++) {
        consumers[consumerIndex] = subscriberSession.createSubscriber(topic);
        int finalConsumerIndex = consumerIndex;
        consumers[consumerIndex].setMessageListener(message -> {
            messageCount[finalConsumerIndex]++;
            try {
                message.acknowledge();
            } catch (JMSException e) {
                LOGGER.error("Message acknowledging failed.", e);
            }
            receiveQueue.offer(new MessageResult(message, finalConsumerIndex));
        });
    }

    // publish messages with property.
    TopicSession producerSession = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    TopicPublisher producer = producerSession.createPublisher(topic);

    TextMessage textMessage;
    String consumerMessage = "testMessage";
    for (int i = 0; i < messagesPerConsumer; i++) {
        textMessage = producerSession.createTextMessage(consumerMessage);
        producer.send(textMessage);
    }


    for (int i = 0; i < maxNumberOfMessages; i++) {
        MessageResult result = receiveQueue.poll(5, TimeUnit.SECONDS);
        if (result == null) {
            StringBuilder countSummary = new StringBuilder();
            for (int consumerIndex = 0; consumerIndex < numberOfConsumers; consumerIndex++) {
                countSummary.append("Consumer ")
                            .append(consumerIndex)
                            .append(" received ")
                            .append(messageCount[consumerIndex])
                            .append(" messages, ");
            }

            Assert.fail("Messages stopped receiving after " + i + " iterations. " + countSummary.toString());
        } else {
            TextMessage textMessage1 = (TextMessage) result.getMessage();
            Assert.assertEquals(textMessage1.getText(),
                                consumerMessage,
                                "Incorrect message received for consumer " + result.getConsumerId());
        }

    }

    for (int consumerIndex = 0; consumerIndex < numberOfConsumers; consumerIndex++) {
        Assert.assertEquals(messageCount[consumerIndex],
                            messagesPerConsumer,
                            "Message " + messageCount[consumerIndex]
                                    + " received for consumer " + consumerIndex + ".");
    }

    producer.close();
    for (int consumerIndex = 0; consumerIndex < numberOfConsumers; consumerIndex++) {
        consumers[consumerIndex].close();
    }

    connection.close();
}
 
Example 16
Source File: TopicMessagesOrderTest.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 test1338TopicMessagesOrderSingleSubscriber(String port,
                                                       String adminUsername,
                                                       String adminPassword,
                                                       String brokerHostname) throws NamingException, JMSException {
    String topicName = "test1338TopicMessagesOrderSingleSubscriber";
    List<String> subscriberOneMessages = new ArrayList<>();
    int numberOfMessages = 1338;

    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withTopic(topicName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    // Initialize subscriber
    TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic subscriberDestination = (Topic) initialContext.lookup(topicName);
    TopicSubscriber subscriber = subscriberSession.createSubscriber(subscriberDestination);

    // publish 1338 messages
    TopicSession producerSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    TopicPublisher producer = producerSession.createPublisher(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        producer.publish(producerSession.createTextMessage(String.valueOf(i)));
    }

    producerSession.close();

    for (int i = 0; i < numberOfMessages; i++) {
        TextMessage message = (TextMessage) subscriber.receive(1000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
        subscriberOneMessages.add(message.getText());
    }

    subscriberSession.close();

    connection.close();

    // verify order is preserved
    boolean isOrderPreserved = true;
    for (int i = 0; i < numberOfMessages; i++) {
        if (!(i == Integer.parseInt(subscriberOneMessages.get(i)))) {
            isOrderPreserved = false;
            break;
        }
    }

    Assert.assertTrue(isOrderPreserved, "Topic messages order not preserved for single subscriber.");
}
 
Example 17
Source File: AndesJMSConsumer.java    From product-ei with Apache License 2.0 4 votes vote down vote up
public void stopClientSync(){
    if (null != connection && null != session && null != receiver) {
        try {
            log.info("Closing Consumer");
            if (ExchangeType.TOPIC == consumerConfig.getExchangeType()) {
                if (null != receiver) {
                    TopicSubscriber topicSubscriber = (TopicSubscriber) receiver;
                    topicSubscriber.close();
                }

                if (null != session) {
                    TopicSession topicSession = (TopicSession) session;
                    topicSession.close();
                }

                if (null != connection) {
                    TopicConnection topicConnection = (TopicConnection) connection;
                    topicConnection.close();
                }
            } else if (ExchangeType.QUEUE == consumerConfig.getExchangeType()) {
                if (null != receiver) {
                    QueueReceiver queueReceiver = (QueueReceiver) receiver;
                    queueReceiver.close();
                }

                if (null != session) {
                    QueueSession queueSession = (QueueSession) session;
                    queueSession.close();
                }

                if (null != connection) {
                    QueueConnection queueConnection = (QueueConnection) connection;
                    queueConnection.stop();
                    queueConnection.close();
                }
            }

            receiver = null;
            session = null;
            connection = null;

            log.info("Consumer Closed");

        } catch (JMSException e) {
            log.error("Error in stopping client.", e);
            throw new RuntimeException("Error in stopping client.", e);
        }
    }
}
 
Example 18
Source File: TopicLocalTransactionRollbackTest.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(expectedExceptions = javax.jms.IllegalStateException.class,
        expectedExceptionsMessageRegExp = ".*Session is not transacted")
public void testRollbackOnNonTransactionTopicSession(String port,
                                                     String adminUsername,
                                                     String adminPassword,
                                                     String brokerHostname) throws NamingException, JMSException {
    String topicName = "testRollbackOnNonTransactionTopicSession";
    int numberOfMessages = 100;

    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withTopic(topicName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    // Initialize subscriber
    TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic subscriberDestination = (Topic) initialContext.lookup(topicName);
    TopicSubscriber subscriber = subscriberSession.createSubscriber(subscriberDestination);

    // publish 100 messages
    TopicSession producerSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    TopicPublisher producer = producerSession.createPublisher(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        producer.publish(producerSession.createTextMessage("Test message " + i));
    }
    try {
        // commit all publish messages
        producerSession.rollback();
        Message message = subscriber.receive(1000);
        Assert.assertNull(message, "Messages should not receive message after calling rollback on "
                                   + "non transaction channel");
    } catch (JMSException e) {
        throw e;
    } finally {
        producerSession.close();
        subscriberSession.close();
        connection.close();
    }
}
 
Example 19
Source File: TopicLocalTransactionRollbackTest.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 testPublisherCloseBeforeRollbackTransaction(String port,
                                                        String adminUsername,
                                                        String adminPassword,
                                                        String brokerHostname)
        throws NamingException, JMSException {
    String topicName = "testPublisherCloseBeforeRollbackTransaction";
    int numberOfMessages = 100;

    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withTopic(topicName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    // initialize subscriber
    TopicSession subscriberSession = connection.createTopicSession(true, Session.SESSION_TRANSACTED);
    Topic subscriberDestination = (Topic) initialContext.lookup(topicName);
    TopicSubscriber subscriber = subscriberSession.createSubscriber(subscriberDestination);

    // publish 100 messages
    TopicSession producerSession = connection.createTopicSession(true, Session.SESSION_TRANSACTED);
    TopicPublisher producer = producerSession.createPublisher(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        producer.publish(producerSession.createTextMessage("Test message " + i));
    }

    // close publisher before rollback
    producer.close();

    // rollback all publish messages
    producerSession.rollback();

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

    producerSession.close();
    subscriberSession.close();
    connection.close();
}
 
Example 20
Source File: JMSSelectorTest.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 testPositiveJMSSelectorConsumerProducer(String port,
                                                    String adminUsername,
                                                    String adminPassword,
                                                    String brokerHostname) throws NamingException, JMSException {
    String queueName = "testPositiveJMSSelectorConsumerProducer";
    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withTopic(queueName)
            .build();


    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    TopicSession subscriberSession = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    Topic topic = (Topic) initialContext.lookup(queueName);

    // Subscribe with a selector
    String propertyName = "MyProperty";
    String propertyValue = "propertyValue";
    String jmsPropertySelector = propertyName + " = '" + propertyValue + "'";
    TopicSubscriber consumer = subscriberSession.createSubscriber(topic, jmsPropertySelector, false);

    // publish messages with property
    TopicSession producerSession = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    TopicPublisher producer = producerSession.createPublisher(topic);

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        TextMessage textMessage = producerSession.createTextMessage("Test message " + i);
        textMessage.setStringProperty(propertyName, propertyValue);
        producer.send(textMessage);
    }

    // consume messages
    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive(1000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    producerSession.close();
    connection.close();
}