javax.jms.TopicSession Java Examples

The following examples show how to use javax.jms.TopicSession. 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: DurableSubscriptionHangTestCase.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception {
   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);
   connection.start();
   TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName);
   LOG.info("About to receive messages");
   Message message = subscriber.receive(120000);
   subscriber.close();
   connection.close();
   LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done");

   return message;
}
 
Example #2
Source File: JMSConnectionFactory.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
protected Session createSession(Connection connection) {
    try {
        if (JMSConstants.JMS_SPEC_VERSION_1_1.equals(jmsSpec) || JMSConstants.JMS_SPEC_VERSION_2_0
                .equals(jmsSpec)) {
            return connection.createSession(transactedSession, sessionAckMode);
        } else {
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                return (QueueSession) ((QueueConnection) (connection))
                        .createQueueSession(transactedSession, sessionAckMode);
            } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
                return (TopicSession) ((TopicConnection) (connection))
                        .createTopicSession(transactedSession, sessionAckMode);
            }
        }
    } catch (JMSException e) {
        logger.error("JMS Exception while obtaining session for factory '" + this.connectionFactoryString + "' " + e
                .getMessage(), e);
    }

    return null;
}
 
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: 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 #5
Source File: JmsPoolTopicSubscriberTest.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();
    TopicSubscriber subscriber = session.createSubscriber(topic);

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

    subscriber.close();

    try {
        subscriber.getTopic();
        fail("Cannot read topic on closed subscriber");
    } catch (IllegalStateException ise) {}
}
 
Example #6
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 #7
Source File: JmsPoolTopicSubscriberTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTopicSubscriber() throws JMSException {
    JmsPoolConnection connection = (JmsPoolConnection) cf.createTopicConnection();
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTemporaryTopic();
    JmsPoolTopicSubscriber subscriber = (JmsPoolTopicSubscriber) session.createDurableSubscriber(topic, "name", "color = red", true);

    assertNotNull(subscriber.getTopicSubscriber());
    assertTrue(subscriber.getTopicSubscriber() instanceof MockJMSTopicSubscriber);

    subscriber.close();

    try {
        subscriber.getTopicSubscriber();
        fail("Cannot read state on closed subscriber");
    } catch (IllegalStateException ise) {}
}
 
Example #8
Source File: JmsTopicPublisherTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTopicPublisher() throws Exception {
    JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
    TopicConnection connection = factory.createTopicConnection();
    assertNotNull(connection);

    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    assertNotNull(session);
    Topic topic = session.createTopic(name.getMethodName());
    TopicPublisher publisher = session.createPublisher(topic);
    assertNotNull(publisher);

    TopicViewMBean proxy = getProxyToTopic(name.getMethodName());
    assertEquals(0, proxy.getEnqueueCount());
    connection.close();
}
 
Example #9
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 #10
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 #11
Source File: JournalPendingMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void publishTestTopicMessages(int publishSize, int deliveryMode, AtomicLong publishedMessageSize)
      throws Exception {
   // create a new queue
   Connection connection = cf.createConnection();
   connection.setClientID("clientId2");
   connection.start();

   // Start the connection
   Session session = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
   Topic topic = session.createTopic(defaultTopicName);

   try {
      // publish a bunch of non-persistent messages to fill up the temp
      // store
      MessageProducer prod = session.createProducer(topic);
      prod.setDeliveryMode(deliveryMode);
      for (int i = 0; i < publishSize; i++) {
         prod.send(createMessage(i, session, JournalPendingMessageTest.maxMessageSize, publishedMessageSize));
      }

   } finally {
      connection.close();
   }
}
 
Example #12
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 #13
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 #14
Source File: JMSFacade.java    From iaf with Apache License 2.0 6 votes vote down vote up
public MessageProducer getMessageProducer(Session session,
		Destination destination) throws NamingException, JMSException {
	MessageProducer mp;
	if (useJms102()) {
		if (useTopicFunctions) {
			mp = getTopicPublisher((TopicSession)session, (Topic)destination);
		} else {
			mp = getQueueSender((QueueSession)session, (Queue)destination);
		}
	} else {
		mp = session.createProducer(destination);
	}
	if (getMessageTimeToLive()>0)
		mp.setTimeToLive(getMessageTimeToLive());
	return mp;
}
 
Example #15
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 #16
Source File: TopicSessionTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testTopicSessionCannotCreateQueues() throws Exception
{
    TopicConnection topicConnection = getTopicConnection();
    try
    {
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        topicSession.createQueue("abc");
        fail("Expected exception was not thrown");
    }
    catch (javax.jms.IllegalStateException s)
    {
        // PASS
    }
    finally
    {
        topicConnection.close();
    }
}
 
Example #17
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 #18
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 #19
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 #20
Source File: JMSFacade.java    From iaf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a MessageConsumer. In this overloaded function the selector is taken into account.
 * This ensures that listeners (or other extensions of this class) do not influence how the selector
 * is used: when a correlationID should be in the filter the  <code>getMessageConsumerForCorrelationId</code>
 * should be used, other wise the <code>getMessageConsumer</code> function which has no attribute for
 * <code>selector</code>. When a MessageSelector is set, it will be used when no correlation id is required.
 * @param session the Session
 * @param destination the Destination
 * @param selector the MessageSelector
 * @return MessageConsumer
 */
public MessageConsumer getMessageConsumer(Session session, Destination destination, String selector) throws NamingException, JMSException {
	if (useTopicFunctions) {
		if (useJms102()) {
			return getTopicSubscriber((TopicSession)session, (Topic)destination, selector);
		} else {
			return getTopicSubscriber(session, (Topic)destination, selector);
		}
	} else {
		if (useJms102()) {
			return getQueueReceiver((QueueSession)session, (Queue)destination, selector);
		} else {
			return session.createConsumer(destination, selector);
		}
	}
}
 
Example #21
Source File: WMB.java    From perf-harness with MIT License 6 votes vote down vote up
public DestinationWrapper<Topic> lookupTopic(String topic, TopicSession session)
		throws JMSException, NamingException {

	if (usingJNDI || session == null) {
		return lookupTopicFromJNDI(topic);
	} else if (usingMQ) {
		//if we are using MQ call the superclass MQ methods to create the
		// topic then we'll do anything MB specific..
		//if we are using MQ call the superclass MQ methods to create the topic then we'll do anything MB specific..
		DestinationWrapper<Topic> dw = super.lookupTopic(topic, session);
		configureWBIMBTopic((MQTopic)dw.destination);
		return dw;
	}
	//if we are here then we need to go create and configure the topic
	// ourselves as it must be for MC or IP
	return new DestinationWrapper<Topic>(topic,
			configureWBIMBTopic((MQTopic) session.createTopic(topic)));
}
 
Example #22
Source File: TibcoMessagingSource.java    From iaf with Apache License 2.0 6 votes vote down vote up
public Destination lookupDestination(String destinationName) throws JmsException {
	Session session=null;		
	try {
		session = createSession(false,Session.AUTO_ACKNOWLEDGE);
		log.debug("Session class ["+session.getClass().getName()+"]");
		Destination destination;

		/* create the destination */
		if (session instanceof TopicSession) {
			destination = ((TopicSession)session).createTopic(destinationName);
		} else {
			destination = ((QueueSession)session).createQueue(destinationName);
		}

		return destination;
	} catch (Exception e) {
		throw new JmsException("cannot create destination", e);
	} finally {
		releaseSession(session);
	}
}
 
Example #23
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 #24
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 #25
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 #26
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 #27
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 #28
Source File: TopicDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublisherWithRollback() throws Exception {

    String subscriptionId = "sub-testPublisherWithRollback";
    String topicName = "testPublisherWithRollback";
    String testMessage = "testPublisherWithRollback-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory().withTopic(topicName).build();
    Topic topic = (Topic) initialContext.lookup(topicName);

    // Setup XA producer.
    XATopicConnectionFactory xaTopicConnectionFactory =
            (XATopicConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);
    XATopicConnection xaTopicConnection = xaTopicConnectionFactory.createXATopicConnection();
    XATopicSession xaTopicSession = xaTopicConnection.createXATopicSession();
    XAResource xaResource = xaTopicSession.getXAResource();
    MessageProducer producer = xaTopicSession.createProducer(topic);

    // Setup non-transactional consumer.
    TopicSession topicSession = xaTopicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
    xaTopicConnection.start();

    // Send message withing a XA transaction.
    XidImpl xid = new XidImpl(0, "branchId".getBytes(), "globalId".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(xaTopicSession.createTextMessage(testMessage));
    xaResource.end(xid, XAResource.TMSUCCESS);

    int response = xaResource.prepare(xid);
    Assert.assertEquals(response, XAResource.XA_OK, "Prepare stage failed.");

    xaResource.rollback(xid);

    durableSubscriber.close();
    xaTopicSession.close();
    xaTopicConnection.close();
    QueueMetadata queueMetadata = restApiClient.getQueueMetadata("carbon:" + subscriptionId);
    Assert.assertEquals((int) queueMetadata.getSize(), 0, "Queue is not empty");
}
 
Example #29
Source File: DynamicDestinationResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveWithPubSubTopicSession() throws Exception {
	Topic expectedDestination = new StubTopic();
	TopicSession session = mock(TopicSession.class);
	given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination);
	testResolveDestination(session, expectedDestination, true);
}
 
Example #30
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();
}