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

The following examples show how to use javax.jms.TopicSession#createPublisher() . 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: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Create a topic publisher
 *
 * @param topic The topic
 * @return The publisher
 * @throws JMSException Thrown if an error occurs
 */
@Override
public TopicPublisher createPublisher(final Topic topic) throws JMSException {
   lock();
   try {
      TopicSession session = getTopicSessionInternal();

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

      TopicPublisher result = session.createPublisher(topic);
      result = new ActiveMQRATopicPublisher(result, this);

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

      addProducer(result);

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

    assertNotNull(publisher.getTopic());
    assertSame(topic, publisher.getTopic());

    publisher.close();

    try {
        publisher.getTopic();
        fail("Cannot read topic on closed publisher");
    } catch (IllegalStateException ise) {}
}
 
Example 4
Source File: JmsPoolTopicPublisherTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTopicPublisher() throws JMSException {
    JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection();
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTemporaryTopic();
    JmsPoolTopicPublisher publisher = (JmsPoolTopicPublisher) session.createPublisher(topic);

    assertNotNull(publisher.getTopicPublisher());
    assertTrue(publisher.getTopicPublisher() instanceof MockJMSTopicPublisher);

    publisher.close();

    try {
        publisher.getTopicPublisher();
        fail("Cannot read state on closed publisher");
    } catch (IllegalStateException ise) {}
}
 
Example 5
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 6
Source File: PooledSessionTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testCreateTopicPublisher() throws Exception {
    JmsPoolConnection connection = (JmsPoolConnection) pooledFactory.createConnection();
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

    Topic topic1 = session.createTopic("Topic-1");
    Topic topic2 = session.createTopic("Topic-2");

    JmsPoolTopicPublisher publisher1 = (JmsPoolTopicPublisher) session.createPublisher(topic1);
    JmsPoolTopicPublisher publisher2 = (JmsPoolTopicPublisher) session.createPublisher(topic2);

    assertSame(publisher1.getMessageProducer(), publisher2.getMessageProducer());
    connection.close();
}
 
Example 7
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 8
Source File: PooledSessionNoPublisherCachingTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testCreateTopicPublisher() throws Exception {
    JmsPoolConnection connection = (JmsPoolConnection) pooledFactory.createConnection();
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

    Topic topic1 = session.createTopic("Topic-1");
    Topic topic2 = session.createTopic("Topic-2");

    JmsPoolTopicPublisher publisher1 = (JmsPoolTopicPublisher) session.createPublisher(topic1);
    JmsPoolTopicPublisher publisher2 = (JmsPoolTopicPublisher) session.createPublisher(topic2);

    assertNotSame(publisher1.getMessageProducer(), publisher2.getMessageProducer());
}
 
Example 9
Source File: JmsTopicPublisherClosedTest.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());
    publisher = session.createPublisher(destination);
    publisher.close();
}
 
Example 10
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 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: JmsPoolTopicPublisherTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublishToTopicFailsIfNotAnonymousPublisher() throws JMSException {
    JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection();
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTemporaryTopic();
    TopicPublisher publisher = session.createPublisher(topic);

    try {
        publisher.publish(session.createTemporaryTopic(), session.createTextMessage());
        fail("Should not be able to send to alternate destination");
    } catch (UnsupportedOperationException ex) {}
}
 
Example 13
Source File: TopicSubscriberTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void messageDeliveredToAllSubscribers() throws Exception
{
    Topic topic = createTopic(getTestName());
    final TopicConnection connection = getTopicConnection();
    try
    {
        final TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        final TopicPublisher producer = session.createPublisher(topic);
        final TopicSubscriber subscriber1 = session.createSubscriber(topic);
        assertEquals("Unexpected subscriber1 topic", topic.getTopicName(), subscriber1.getTopic().getTopicName());
        final TopicSubscriber subscriber2 = session.createSubscriber(topic);
        assertEquals("Unexpected subscriber2 topic", topic.getTopicName(), subscriber2.getTopic().getTopicName());

        connection.start();
        String messageText = "Test Message";
        producer.send(session.createTextMessage(messageText));

        final Message subscriber1Message = subscriber1.receive(getReceiveTimeout());
        final Message subscriber2Message = subscriber2.receive(getReceiveTimeout());

        assertTrue("TextMessage should be received  by subscriber1", subscriber1Message instanceof TextMessage);
        assertEquals(messageText, ((TextMessage) subscriber1Message).getText());
        assertTrue("TextMessage should be received  by subscriber2", subscriber2Message instanceof TextMessage);
        assertEquals(messageText, ((TextMessage) subscriber2Message).getText());
    }
    finally
    {
        connection.close();
    }
}
 
Example 14
Source File: JMSFacade.java    From iaf with Apache License 2.0 4 votes vote down vote up
protected String sendByTopic(TopicSession session, Topic destination, javax.jms.Message message) throws NamingException, JMSException {
	TopicPublisher tps = session.createPublisher(destination);
	tps.publish(message);
	tps.close();
	return message.getJMSMessageID();
}
 
Example 15
Source File: JMSFacade.java    From iaf with Apache License 2.0 4 votes vote down vote up
/**
 * Gets a topicPublisher for a specified topic
 */
private TopicPublisher getTopicPublisher(TopicSession session, Topic topic) throws NamingException, JMSException {
	return session.createPublisher(topic);
}
 
Example 16
Source File: ConnectionCreateClosePerMessageTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
private TopicPublisher getTopicPublisher(Topic subscriberDestination, TopicSession producerSession)
        throws JMSException {
    return producerSession.createPublisher(subscriberDestination);
}
 
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
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 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: ObjectMessageDeliveryTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
/**
 *
 */
@Test
public void testTopic() throws Exception {
   TopicConnection conn = getTopicConnectionFactory().createTopicConnection();

   try {
      TopicSession s = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
      TopicPublisher publisher = s.createPublisher(ActiveMQServerTestCase.topic1);
      TopicSubscriber sub = s.createSubscriber(ActiveMQServerTestCase.topic1);
      conn.start();

      // Create 3 object messages with different bodies

      TestObject to1 = new TestObject();
      to1.text = "hello1";

      TestObject to2 = new TestObject();
      to1.text = "hello2";

      TestObject to3 = new TestObject();
      to1.text = "hello3";

      ObjectMessage om1 = s.createObjectMessage();
      om1.setObject(to1);

      ObjectMessage om2 = s.createObjectMessage();
      om2.setObject(to2);

      ObjectMessage om3 = s.createObjectMessage();
      om3.setObject(to3);

      // send to topic
      publisher.send(om1);

      publisher.send(om2);

      publisher.send(om3);

      ObjectMessage rm1 = (ObjectMessage) sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT);

      ObjectMessage rm2 = (ObjectMessage) sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT);

      ObjectMessage rm3 = (ObjectMessage) sub.receive(ActiveMQServerTestCase.MAX_TIMEOUT);

      ProxyAssertSupport.assertNotNull(rm1);

      TestObject ro1 = (TestObject) rm1.getObject();

      ProxyAssertSupport.assertEquals(to1.text, ro1.text);
      ProxyAssertSupport.assertNotNull(rm1);

      TestObject ro2 = (TestObject) rm2.getObject();

      ProxyAssertSupport.assertEquals(to2.text, ro2.text);

      ProxyAssertSupport.assertNotNull(rm2);

      TestObject ro3 = (TestObject) rm3.getObject();

      ProxyAssertSupport.assertEquals(to3.text, ro3.text);
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}