Java Code Examples for javax.jms.TopicSession#createSubscriber()

The following examples show how to use javax.jms.TopicSession#createSubscriber() . 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: NetworkRemovesSubscriptionsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testWithSessionAndSubsciberClose() 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);
         subscriber.close();
         subscriberSession.close();
      }
      connection.close();
      Thread.sleep(1000);
      Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic);
      assertNotNull(dest);
      assertTrue(dest.getConsumers().isEmpty());
   }
 
Example 2
Source File: NetworkRemovesSubscriptionsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testWithoutSessionAndSubsciberClose() 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);
         assertNotNull(subscriber);
      }

      connection.close();
      Thread.sleep(1000);
      Destination dest = backEnd.getRegionBroker().getDestinationMap().get(topic);
      assertNotNull(dest);
      assertTrue(dest.getConsumers().isEmpty());
   }
 
Example 3
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotificationProperties() throws Exception {
   try (TopicConnection topicConnection = factory.createTopicConnection()) {
      TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic notificationsTopic = topicSession.createTopic("activemq.notifications");
      TopicSubscriber subscriber = topicSession.createSubscriber(notificationsTopic);
      List<Message> receivedMessages = new CopyOnWriteArrayList<>();
      subscriber.setMessageListener(receivedMessages::add);
      topicConnection.start();

      Wait.waitFor(() -> receivedMessages.size() > 0);

      Assert.assertTrue(receivedMessages.size() > 0);

      for (Message message : receivedMessages) {
         assertNotNull(message);
         assertNotNull(message.getStringProperty("_AMQ_NotifType"));
      }
   }
}
 
Example 4
Source File: JMSSink.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public JMSSink(final String tcfBindingName, final String topicBindingName, final String username,
               final String password) {

   try {
      final Context ctx = new InitialContext();
      final TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) lookup(ctx,
              tcfBindingName);

      final TopicConnection topicConnection =
              topicConnectionFactory.createTopicConnection(username,
                      password);
      topicConnection.start();

      final TopicSession topicSession = topicConnection.createTopicSession(false,
              Session.AUTO_ACKNOWLEDGE);

      final Topic topic = (Topic) ctx.lookup(topicBindingName);

      final TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);

      topicSubscriber.setMessageListener(this);

   } catch (final Exception e) {
      logger.error("Could not read JMS message.", e);
   }
}
 
Example 5
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a topic subscriber
 *
 * @param topic The topic
 * @return The subscriber
 * @throws JMSException Thrown if an error occurs
 */
@Override
public TopicSubscriber createSubscriber(final Topic topic) throws JMSException {
   lock();
   try {
      TopicSession session = getTopicSessionInternal();

      if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
         ActiveMQRALogger.LOGGER.trace("createSubscriber " + session + " topic=" + topic);
      }

      TopicSubscriber result = session.createSubscriber(topic);
      result = new ActiveMQRATopicSubscriber(result, this);

      if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
         ActiveMQRALogger.LOGGER.trace("createdSubscriber " + session + " ActiveMQTopicSubscriber=" + result);
      }

      addConsumer(result);

      return result;
   } finally {
      unlock();
   }
}
 
Example 6
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 7
Source File: JmsPoolTopicSubscriberTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testToString() throws JMSException {
    JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection();
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTemporaryTopic();
    TopicSubscriber subscriber = session.createSubscriber(topic);

    assertNotNull(subscriber.toString());
}
 
Example 8
Source File: JMSTopicConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testTemporarySubscriptionDeleted() throws Exception {
   Connection connection = createConnection();

   try {
      TopicSession session = (TopicSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic topic = session.createTopic(getTopicName());
      TopicSubscriber myNonDurSub = session.createSubscriber(topic);
      assertNotNull(myNonDurSub);

      Bindings bindingsForAddress = server.getPostOffice().getBindingsForAddress(new SimpleString(getTopicName()));
      Assert.assertEquals(2, bindingsForAddress.getBindings().size());
      session.close();

      final CountDownLatch latch = new CountDownLatch(1);
      server.getRemotingService().getConnections().iterator().next().addCloseListener(new CloseListener() {
         @Override
         public void connectionClosed() {
            latch.countDown();
         }
      });

      connection.close();
      latch.await(5, TimeUnit.SECONDS);
      bindingsForAddress = server.getPostOffice().getBindingsForAddress(new SimpleString(getTopicName()));
      Assert.assertEquals(1, bindingsForAddress.getBindings().size());
   } finally {
      connection.close();
   }
}
 
Example 9
Source File: SimpleOpenWireTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testTempTopicDelete() throws Exception {
   connection.start();
   TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

   TemporaryTopic tempTopic = topicSession.createTemporaryTopic();

   ActiveMQConnection newConn = (ActiveMQConnection) factory.createConnection();

   try {
      TopicSession newTopicSession = newConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      TopicPublisher publisher = newTopicSession.createPublisher(tempTopic);

      // need to wait here because the ActiveMQ client's temp destination map is updated asynchronously, not waiting can introduce a race
      assertTrue(Wait.waitFor(() -> newConn.activeTempDestinations.size() == 1, 2000, 100));

      TextMessage msg = newTopicSession.createTextMessage("Test Message");

      publisher.publish(msg);

      try {
         TopicSubscriber consumer = newTopicSession.createSubscriber(tempTopic);
         fail("should have gotten exception but got consumer: " + consumer);
      } catch (JMSException ex) {
         //correct
      }

      connection.close();

      try {
         Message newMsg = newTopicSession.createMessage();
         publisher.publish(newMsg);
      } catch (JMSException e) {
         //ok
      }

   } finally {
      newConn.close();
   }
}
 
Example 10
Source File: JMSFacade.java    From iaf with Apache License 2.0 5 votes vote down vote up
private TopicSubscriber getTopicSubscriber(TopicSession session, Topic topic, String selector) throws NamingException, JMSException {

		TopicSubscriber topicSubscriber;
		if (subscriberType.equalsIgnoreCase("DURABLE")) {
			topicSubscriber = session.createDurableSubscriber(topic, destinationName, selector, false);
			if (log.isDebugEnabled()) log.debug("[" + name + "] got durable subscriber for topic [" + destinationName + "] with selector [" + selector + "]");

		} else {
			topicSubscriber = session.createSubscriber(topic, selector, false);
			if (log.isDebugEnabled()) log.debug("[" + name + "] got transient subscriber for topic [" + destinationName + "] with selector [" + selector + "]");
		}

		return topicSubscriber;
	}
 
Example 11
Source File: JmsTopicSubscriberClosedTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
protected void createTestResources() throws Exception {
    connection = createTopicConnectionToMockProvider();
    TopicSession session = ((TopicConnection) connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic destination = session.createTopic(_testName.getMethodName());
    subscriber = session.createSubscriber(destination);
    subscriber.close();
}
 
Example 12
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Create a topic subscriber
 *
 * @param topic           The topic
 * @param messageSelector The message selector
 * @param noLocal         If true inhibits the delivery of messages published by its own connection
 * @return The subscriber
 * @throws JMSException Thrown if an error occurs
 */
@Override
public TopicSubscriber createSubscriber(final Topic topic,
                                        final String messageSelector,
                                        final boolean noLocal) throws JMSException {
   lock();
   try {
      TopicSession session = getTopicSessionInternal();

      if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
         ActiveMQRALogger.LOGGER.trace("createSubscriber " + session +
                                          " topic=" +
                                          topic +
                                          " selector=" +
                                          messageSelector +
                                          " noLocal=" +
                                          noLocal);
      }

      TopicSubscriber result = session.createSubscriber(topic, messageSelector, noLocal);
      result = new ActiveMQRATopicSubscriber(result, this);

      if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
         ActiveMQRALogger.LOGGER.trace("createdSubscriber " + session + " ActiveMQTopicSubscriber=" + result);
      }

      addConsumer(result);

      return result;
   } finally {
      unlock();
   }
}
 
Example 13
Source File: TopicSubscriberTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({ "broker-port"})
@Test
public void testSubscriberPublisher(String port) throws Exception {
    String topicName = "MyTopic1";
    int numberOfMessages = 100;

    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", 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));
    }

    producerSession.close();

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

    connection.close();
}
 
Example 14
Source File: NonDurableSubscriberTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidSelectorOnSubscription() throws Exception {
   TopicConnection c = createTopicConnection();
   c.setClientID("something");

   TopicSession s = c.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

   try {
      s.createSubscriber(ActiveMQServerTestCase.topic1, "=TEST 'test'", false);
      ProxyAssertSupport.fail("this should fail");
   } catch (InvalidSelectorException e) {
      // OK
   }
}
 
Example 15
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 testNegativeJMSSelectorConsumerProducer(String port,
                                                    String adminUsername,
                                                    String adminPassword,
                                                    String brokerHostname) throws NamingException, JMSException {
    String queueName = "testNegativeJMSSelectorConsumerProducer";
    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);

    // Send messages with a different property value
    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        TextMessage textMessage = producerSession.createTextMessage("Test message " + i);
        textMessage.setStringProperty(propertyName, propertyValue + "-1");
        producer.send(textMessage);
    }

    // consume messages
    Message message = consumer.receive(100);
    Assert.assertNull(message, "Message received. Shouldn't receive any messages.");

    producerSession.close();
    connection.close();
}
 
Example 16
Source File: TopicLocalTransactionCommitTest.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 testCommitOnNonTransactionTopicSession(String port,
        String adminUsername,
        String adminPassword,
        String brokerHostname) throws NamingException, JMSException {
    String topicName = "testCommitOnNonTransactionTopicSession";
    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.commit();

        Message message = subscriber.receive(1000);
        Assert.assertNull(message, "Messages should not receive message after calling commit on "
                                   + "non transaction channel");

    } catch (JMSException e) {
        //catch exception and re-throw it since we need the connection to be closed
        throw e;
    } finally {
        producerSession.close();
        subscriberSession.close();
        connection.close();
    }
}
 
Example 17
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 18
Source File: AndesJMSConsumer.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a topic connection, session and receiver.
 *
 * @throws NamingException
 * @throws JMSException
 */
private void createTopicConnection() throws NamingException, JMSException {
    // Creates a topic connection, sessions and receiver
    TopicConnectionFactory connFactory = (TopicConnectionFactory) super.getInitialContext()
            .lookup(AndesClientConstants.CF_NAME);
    TopicConnection topicConnection = connFactory.createTopicConnection();
    topicConnection.setClientID(this.consumerConfig.getSubscriptionID());
    topicConnection.start();
    TopicSession topicSession;
    // Sets acknowledgement mode
    if (TopicSession.SESSION_TRANSACTED == this.consumerConfig.getAcknowledgeMode().getType()) {
        topicSession = topicConnection
                .createTopicSession(true, this.consumerConfig.getAcknowledgeMode().getType());
    } else {
        topicSession = topicConnection
                .createTopicSession(false, this.consumerConfig.getAcknowledgeMode().getType());
    }

    Topic topic =
            (Topic) super.getInitialContext().lookup(this.consumerConfig.getDestinationName());

    connection = topicConnection;
    session = topicSession;
    // If topic is durable
    if (this.consumerConfig.isDurable()) {
        // If selectors exists
        if (null != this.consumerConfig.getSelectors()) {
            receiver = topicSession.createDurableSubscriber(topic, this.consumerConfig
                    .getSubscriptionID(), this.consumerConfig.getSelectors(), false);
        } else {
            receiver = topicSession
                    .createDurableSubscriber(topic, this.consumerConfig.getSubscriptionID());
        }
    } else {
        // If selectors exists
        if (null != this.consumerConfig.getSelectors()) {
            receiver = topicSession
                    .createSubscriber(topic, this.consumerConfig.getSelectors(), false);
        } else {
            receiver = topicSession.createSubscriber(topic);
        }
    }
}
 
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 testPublisherRollbackTransaction(String port,
                                             String adminUsername,
                                             String adminPassword,
                                             String brokerHostname) throws NamingException, JMSException {
    String topicName = "testPublisherRollbackTransaction";
    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));
    }
    // rollback all publish messages
    producerSession.rollback();

    // Consume published messages
    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: 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.");
}