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

The following examples show how to use javax.jms.TopicConnection#createTopicSession() . 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: 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 2
Source File: TopicSessionTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testTopicSessionCannotCreateCreateBrowser() throws Exception
{
    Queue queue = createQueue(getTestName());
    TopicConnection topicConnection = getTopicConnection();
    try
    {
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        topicSession.createBrowser(queue);
        fail("Expected exception was not thrown");
    }
    catch (javax.jms.IllegalStateException s)
    {
        // PASS
    }
    finally
    {
        topicConnection.close();
    }
}
 
Example 3
Source File: NetworkRemovesSubscriptionsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testWithSessionCloseOutsideTheLoop() throws Exception {

      TopicConnection connection = connectionFactory.createTopicConnection();
      connection.start();
      TopicSession subscriberSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      for (int i = 0; i < 100; i++) {

         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 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: 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 6
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoLocalOnClosedConsumer() throws Exception {
   Connection consumerConnection = null;

   try {
      consumerConnection = createConnection();
      TopicConnection tc = (TopicConnection) consumerConnection;

      TopicSession consumerSession = tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

      TopicSubscriber topicConsumer = consumerSession.createSubscriber(ActiveMQServerTestCase.topic1);

      topicConsumer.close();

      try {
         topicConsumer.getNoLocal();
         Assert.fail("must throw a JMS IllegalStateException");
      } catch (javax.jms.IllegalStateException e) {
         // OK
      }
   } finally {
      if (consumerConnection != null) {
         consumerConnection.close();
      }
   }
}
 
Example 7
Source File: PooledConnectionTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testTopicMessageSend() throws Exception {
    cf.setMaxConnections(1);

    TopicConnection connection = cf.createTopicConnection();

    try {
        TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = topicSession.createTopic(getTestName());

        TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.send(topicSession.createMessage());
        assertEquals(1, cf.getNumConnections());
    } finally {
        connection.close();
        cf.stop();
    }
}
 
Example 8
Source File: TopicSessionTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void publisherGetDeliveryModeAfterConnectionClose() throws Exception
{
    Topic topic = createTopic(getTestName());
    TopicConnection connection =  getTopicConnection();
    try
    {
        TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicPublisher publisher = session.createPublisher(topic);
        connection.close();
        try
        {
            publisher.getDeliveryMode();
            fail("Expected exception not thrown");
        }
        catch (javax.jms.IllegalStateException e)
        {
            // PASS
        }
    }
    finally
    {
        connection.close();
    }
}
 
Example 9
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 10
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 11
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 12
Source File: ConnectionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test creation of TopicSession
 */
@Test
public void testTopicConnection() throws Exception {
   TopicConnection tc = topicCf.createTopicConnection();

   tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
}
 
Example 13
Source File: TopicWildcardTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
private void assertNotNullWithPublishSubscribeForTopics(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();

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

    subscriberSession.close();
    connection.close();
}
 
Example 14
Source File: NonDurableSubscriberTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test introduced as a result of a TCK failure.
 */
@Test
public void testNonDurableSubscriberOnNullTopic() throws Exception {
   TopicConnection conn = createTopicConnection();

   TopicSession ts = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

   try {
      ts.createSubscriber(null);
      ProxyAssertSupport.fail("this should fail");
   } catch (javax.jms.InvalidDestinationException e) {
      // OK
   }
}
 
Example 15
Source File: DurableSubscriptionHangTestCase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void registerDurableSubscription() throws JMSException {
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
   TopicConnection connection = connectionFactory.createTopicConnection();
   connection.setClientID(clientID);
   TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
   Topic topic = topicSession.createTopic(topicName);
   TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName);
   connection.start();
   durableSubscriber.close();
   connection.close();
   LOG.info("Durable Sub Registered");
}
 
Example 16
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 17
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 18
Source File: BDBUpgradeTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
/**
 * Test that the DurableSubscription without selector was successfully
 * transfered to the new store, and functions as expected with continued use.
 */
@Test
public void testDurableSubscriptionWithoutSelector() throws Exception
{
    TopicConnection connection = getTopicConnection();
    try
    {
        connection.start();

        TopicSession session = connection.createTopicSession(true, Session.SESSION_TRANSACTED);

        Topic topic = session.createTopic(TOPIC_NAME);
        TopicPublisher publisher = session.createPublisher(topic);

        int index = ThreadLocalRandom.current().nextInt();
        Message messageA = session.createTextMessage("A");
        messageA.setIntProperty("ID", index);
        messageA.setStringProperty("testprop", "false");
        publisher.publish(messageA);

        Message messageB = session.createTextMessage("B");
        messageB.setIntProperty("ID", index);
        messageB.setStringProperty("testprop", "true");
        publisher.publish(messageB);

        session.commit();

        TopicSubscriber subscriber = session.createDurableSubscriber(topic, SUB_NAME);
        Message migrated = subscriber.receive(getReceiveTimeout());
        assertThat("Failed to receive migrated message", migrated, is(notNullValue()));

        Message receivedA = subscriber.receive(getReceiveTimeout());
        session.commit();
        assertThat("Failed to receive published message A", receivedA, is(notNullValue()));
        assertThat("Message A is not Text message", receivedA, is(instanceOf(TextMessage.class)));
        assertThat("Unexpected text for A", ((TextMessage) receivedA).getText(), is(equalTo("A")));
        assertThat("Unexpected index", receivedA.getIntProperty("ID"), is(equalTo(index)));

        Message receivedB = subscriber.receive(getReceiveTimeout());
        session.commit();
        assertThat("Failed to receive published message B", receivedB, is(notNullValue()));
        assertThat("Message B is not Text message", receivedB, is(instanceOf(TextMessage.class)));
        assertThat("Unexpected text for B", ((TextMessage) receivedB).getText(), is(equalTo("B")));
        assertThat("Unexpected index  for B", receivedB.getIntProperty("ID"), is(equalTo(index)));

        session.commit();
        session.close();
    }
    finally
    {
        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 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.");
}