Java Code Examples for javax.jms.Session#createSharedConsumer()

The following examples show how to use javax.jms.Session#createSharedConsumer() . 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: AbstractMessageListenerContainer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a JMS MessageConsumer for the given Session and Destination.
 * <p>This implementation uses JMS 1.1 API.
 * @param session the JMS Session to create a MessageConsumer for
 * @param destination the JMS Destination to create a MessageConsumer for
 * @return the new JMS MessageConsumer
 * @throws javax.jms.JMSException if thrown by JMS API methods
 */
protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException {
	if (isPubSubDomain() && destination instanceof Topic) {
		if (isSubscriptionShared()) {
			return (isSubscriptionDurable() ?
					session.createSharedDurableConsumer((Topic) destination, getSubscriptionName(), getMessageSelector()) :
					session.createSharedConsumer((Topic) destination, getSubscriptionName(), getMessageSelector()));
		}
		else if (isSubscriptionDurable()) {
			return session.createDurableSubscriber(
					(Topic) destination, getSubscriptionName(), getMessageSelector(), isPubSubNoLocal());
		}
		else {
			// Only pass in the NoLocal flag in case of a Topic (pub-sub mode):
			// Some JMS providers, such as WebSphere MQ 6.0, throw IllegalStateException
			// in case of the NoLocal flag being specified for a Queue.
			return session.createConsumer(destination, getMessageSelector(), isPubSubNoLocal());
		}
	}
	else {
		return session.createConsumer(destination, getMessageSelector());
	}
}
 
Example 2
Source File: AbstractMessageListenerContainer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a JMS MessageConsumer for the given Session and Destination.
 * <p>This implementation uses JMS 1.1 API.
 * @param session the JMS Session to create a MessageConsumer for
 * @param destination the JMS Destination to create a MessageConsumer for
 * @return the new JMS MessageConsumer
 * @throws javax.jms.JMSException if thrown by JMS API methods
 */
protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException {
	if (isPubSubDomain() && destination instanceof Topic) {
		if (isSubscriptionShared()) {
			return (isSubscriptionDurable() ?
					session.createSharedDurableConsumer((Topic) destination, getSubscriptionName(), getMessageSelector()) :
					session.createSharedConsumer((Topic) destination, getSubscriptionName(), getMessageSelector()));
		}
		else if (isSubscriptionDurable()) {
			return session.createDurableSubscriber(
					(Topic) destination, getSubscriptionName(), getMessageSelector(), isPubSubNoLocal());
		}
		else {
			// Only pass in the NoLocal flag in case of a Topic (pub-sub mode):
			// Some JMS providers, such as WebSphere MQ 6.0, throw IllegalStateException
			// in case of the NoLocal flag being specified for a Queue.
			return session.createConsumer(destination, getMessageSelector(), isPubSubNoLocal());
		}
	}
	else {
		return session.createConsumer(destination, getMessageSelector());
	}
}
 
Example 3
Source File: SharedSubscriptionTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDurableSharedAndNonDurableSharedCanUseTheSameSubscriptionName() throws Exception
{
    try (Connection connection = getConnectionBuilder().setPrefetch(0).build())
    {
        Session publishingSession = connection.createSession();
        Session subscriberSession = connection.createSession();

        String topicName = getTestName();
        Topic topic = publishingSession.createTopic("amq.direct/" + topicName);
        MessageConsumer consumer1 = subscriberSession.createSharedDurableConsumer(topic, "testSharedSubscription");
        MessageConsumer consumer2 = subscriberSession.createSharedConsumer(topic, "testSharedSubscription");
        connection.start();

        Utils.sendMessages(publishingSession, topic, 1);

        Message message1 = consumer1.receive(getReceiveTimeout());
        Message message2 = consumer2.receive(getReceiveTimeout());

        assertNotNull("Message 1 was not received", message1);
        assertNotNull("Message 2 was not received", message2);

        assertEquals("Unexpected index for message 1", 0, message1.getIntProperty(Utils.INDEX));
        assertEquals("Unexpected index for message 2", 0, message2.getIntProperty(Utils.INDEX));
    }
}
 
Example 4
Source File: JournalPendingMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testTopicMessageSizeShared() throws Exception {
   AtomicLong publishedMessageSize = new AtomicLong();

   Connection connection = cf.createConnection();
   connection.setClientID("clientId");
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");
   MessageConsumer consumer2 = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");

   publishTestTopicMessages(200, publishedMessageSize);

   verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
   verifyPendingDurableStats(defaultTopicName, 0, 0);
   consumer2.close();

   // consume all messages
   consumeTestMessages(consumer, 200);

   // All messages should now be gone
   verifyPendingStats(defaultTopicName, 0, 0);
   verifyPendingDurableStats(defaultTopicName, 0, 0);

   connection.close();
}
 
Example 5
Source File: CreateSubscriptionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedConsumer() throws Exception {

   server.addAddressInfo(new AddressInfo(SimpleString.toSimpleString("myTopic")).addRoutingType(RoutingType.MULTICAST));
   ConnectionFactory cf = CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616");
   Connection connection = cf.createConnection();
   Session session = connection.createSession();
   Connection connecton2 = cf.createConnection();
   Session session2 = connecton2.createSession();

   try {

      Topic topic = session.createTopic("myTopic");

      MessageConsumer messageConsumer = session.createSharedConsumer(topic, "consumer1");
      MessageConsumer messageConsumer2 = session2.createSharedConsumer(topic, "consumer1");



      connection.close();
   } finally {
      connection.close();
      connecton2.close();
   }
}
 
Example 6
Source File: JmsConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedConsumer() throws Exception {
   conn = cf.createConnection();
   conn.start();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   topic = ActiveMQJMSClient.createTopic(T_NAME);

   MessageConsumer cons = session.createSharedConsumer(topic, "test1");

   MessageProducer producer = session.createProducer(topic);

   producer.send(session.createTextMessage("test"));

   TextMessage txt = (TextMessage) cons.receive(5000);

   Assert.assertNotNull(txt);
}
 
Example 7
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public MessageConsumer createSharedConsumer(final Topic topic,
                                            final String sharedSubscriptionName) throws JMSException {
   lock();
   try {
      Session session = getSessionInternal();

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

      MessageConsumer result = session.createSharedConsumer(topic, sharedSubscriptionName);
      result = new ActiveMQRAMessageConsumer(result, this);

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

      addConsumer(result);

      return result;
   } finally {
      unlock();
   }
}
 
Example 8
Source File: JMSConsumer.java    From nifi with Apache License 2.0 6 votes vote down vote up
private MessageConsumer createMessageConsumer(final Session session, final String destinationName, final boolean durable, final boolean shared, final String subscriberName) throws JMSException {
    final boolean isPubSub = JMSConsumer.this.jmsTemplate.isPubSubDomain();
    final Destination destination = JMSConsumer.this.jmsTemplate.getDestinationResolver().resolveDestinationName(session, destinationName, isPubSub);

    if (isPubSub) {
        if (shared) {
            try {
                if (durable) {
                    return session.createSharedDurableConsumer((Topic) destination, subscriberName);
                } else {
                    return session.createSharedConsumer((Topic) destination, subscriberName);
                }
            } catch (AbstractMethodError e) {
                throw new ProcessException("Failed to create a shared consumer. Make sure the target broker is JMS 2.0 compliant.", e);
            }
        } else {
            if (durable) {
                return session.createDurableConsumer((Topic) destination, subscriberName, null, JMSConsumer.this.jmsTemplate.isPubSubDomain());
            } else {
                return session.createConsumer(destination, null, JMSConsumer.this.jmsTemplate.isPubSubDomain());
            }
        }
    } else {
        return session.createConsumer(destination, null, JMSConsumer.this.jmsTemplate.isPubSubDomain());
    }
}
 
Example 9
Source File: SharedSubscriptionTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedNonDurableSubscription() throws Exception
{
    try (Connection connection = getConnectionBuilder().setPrefetch(0).build())
    {
        Session publishingSession = connection.createSession();
        Session subscriber1Session = connection.createSession();
        Session subscriber2Session = connection.createSession();

        String topicName = getTestName();
        Topic topic = publishingSession.createTopic("amq.direct/" + topicName);

        MessageConsumer consumer1 = subscriber1Session.createSharedConsumer(topic, "subscription");
        MessageConsumer consumer2 = subscriber2Session.createSharedConsumer(topic, "subscription");

        Utils.sendMessages(publishingSession, topic, 2);

        connection.start();

        Message message1 = consumer1.receive(getReceiveTimeout());
        Message message2 = consumer2.receive(getReceiveTimeout());

        assertNotNull("Message 1 was not received", message1);
        assertNotNull("Message 2 was not received", message2);

        assertEquals("Unexpected index for message 1", 0, message1.getIntProperty(Utils.INDEX));
        assertEquals("Unexpected index for message 2", 1, message2.getIntProperty(Utils.INDEX));

        Message message3 = consumer1.receive(getReceiveTimeout());
        Message message4 = consumer2.receive(getReceiveTimeout());

        assertNull("Unexpected message received by first shared consumer", message3);
        assertNull("Unexpected message received by second shared consumer", message4);
    }
}
 
Example 10
Source File: SharedSubscriptionTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalAndNotGlobalCanUseTheSameSubscriptionName() throws Exception
{
    try (Connection connection =  getConnectionBuilder().setClientId("testClientId").build();
         Connection connection2 = getConnectionBuilder().setClientId(null).build())
    {
        Session publishingSession = connection.createSession();
        Session subscriber1Session = connection.createSession();
        Session subscriber2Session = connection2.createSession();

        String topicName = getTestName();
        Topic topic = publishingSession.createTopic("amq.direct/" + topicName);
        MessageConsumer consumer1 = subscriber1Session.createSharedConsumer(topic, "testSharedSubscription");
        MessageConsumer consumer2 = subscriber2Session.createSharedConsumer(topic, "testSharedSubscription");
        connection.start();
        connection2.start();

        Utils.sendMessages(publishingSession, topic, 1);

        Message message1 = consumer1.receive(getReceiveTimeout());
        Message message2 = consumer2.receive(getReceiveTimeout());

        assertNotNull("Message 1 was not received", message1);
        assertNotNull("Message 2 was not received", message2);

        assertEquals("Unexpected index for message 1", 0, message1.getIntProperty(Utils.INDEX));
        assertEquals("Unexpected index for message 2", 0, message2.getIntProperty(Utils.INDEX));
    }
}
 
Example 11
Source File: JMSConnectionFactory.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public MessageConsumer createMessageConsumer(Session session, Destination destination) {
    try {
        if (JMSConstants.JMS_SPEC_VERSION_2_0.equals(jmsSpec) && isSharedSubscription) {
            if (isDurable) {
                return session.createSharedDurableConsumer((Topic) destination, subscriptionName, messageSelector);
            } else {
                return session.createSharedConsumer((Topic) destination, subscriptionName, messageSelector);
            }
        } else if ((JMSConstants.JMS_SPEC_VERSION_1_1.equals(jmsSpec)) || (
                JMSConstants.JMS_SPEC_VERSION_2_0.equals(jmsSpec) && !isSharedSubscription)) {
            if (isDurable) {
                return session.createDurableSubscriber((Topic) destination, subscriptionName, messageSelector,
                                                       noPubSubLocal);
            } else {
                return session.createConsumer(destination, messageSelector);
            }
        } else {
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                return ((QueueSession) session).createReceiver((Queue) destination, messageSelector);
            } else {
                if (isDurable) {
                    return ((TopicSession) session)
                            .createDurableSubscriber((Topic) destination, subscriptionName, messageSelector,
                                                     noPubSubLocal);
                } else {
                    return ((TopicSession) session).createSubscriber((Topic) destination, messageSelector, false);
                }
            }
        }
    } catch (JMSException e) {
        logger.error("JMS Exception while creating consumer. " + e.getMessage(), e);
    }
    return null;
}
 
Example 12
Source File: SubscriptionsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void doSharedSubscriptionLinkCapabilitySupportedTestImpl(boolean durable) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // DONT include server connection capability to indicate support for shared-subs.
        // This will cause the link capability to be desired, and we verify success if offered.
        Symbol[] serverCapabilities = new Symbol[]{};

        Connection connection = testFixture.establishConnecton(testPeer, serverCapabilities);
        connection.start();

        testPeer.expectBegin();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session.createTopic(topicName);
        String subscriptionName = "mySubscription";

        // Expect a shared receiver to attach, and succeed due to the server offering
        // the shared subs capability, i.e sharing is supported.
        if (durable) {
            Matcher<?> durableLinkNameMatcher = equalTo(subscriptionName);
            testPeer.expectSharedSubscriberAttach(topicName, subscriptionName, durableLinkNameMatcher, true, false, true, true, true);
            testPeer.expectLinkFlow();

            session.createSharedDurableConsumer(dest, subscriptionName);
        } else {
            Matcher<?> volatileLinkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "volatile1");
            testPeer.expectSharedSubscriberAttach(topicName, subscriptionName, volatileLinkNameMatcher, false, false, true, true, true);
            testPeer.expectLinkFlow();

            session.createSharedConsumer(dest, subscriptionName);
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 13
Source File: SubscriptionsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that a shared volatile subscriber and shared durable subscriber with the same subscription name
 * can be active on the same connection at the same time and names their links appropriately to distinguish
 * themselves from each other.
 *
 * @throws Exception if an unexpected exception occurs
 */
@Test(timeout = 20000)
public void testSharedDurableAndVolatileSubsCoexistUsingDistinctLinkNames() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // Add server connection capability to indicate support for shared-subs
        Symbol[] serverCapabilities = new Symbol[]{SHARED_SUBS};

        // Establish connection
        Connection connection = testFixture.establishConnecton(testPeer, serverCapabilities);
        connection.start();

        testPeer.expectBegin();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session.createTopic(topicName);
        String subscriptionName = "mySubscription";

        // Attach the durable shared receiver
        Matcher<?> durableLinkNameMatcher = equalTo(subscriptionName);
        testPeer.expectSharedDurableSubscriberAttach(topicName, subscriptionName, durableLinkNameMatcher, true);
        testPeer.expectLinkFlow();

        session.createSharedDurableConsumer(dest, subscriptionName);

        // Attach the volatile shared receiver
        Matcher<?> volatileLinkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "volatile1");
        testPeer.expectSharedVolatileSubscriberAttach(topicName, subscriptionName, volatileLinkNameMatcher, true);
        testPeer.expectLinkFlow();

        session.createSharedConsumer(dest, subscriptionName);

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 14
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public MessageConsumer createSharedConsumer(final Topic topic,
                                            final String sharedSubscriptionName,
                                            final String messageSelector) throws JMSException {
   lock();
   try {
      Session session = getSessionInternal();

      if (ActiveMQRALogger.LOGGER.isTraceEnabled()) {
         ActiveMQRALogger.LOGGER.trace("createSharedConsumer " + session + " topic=" + topic +
                                          ", sharedSubscriptionName=" + sharedSubscriptionName + ", messageSelector=" + messageSelector);
      }

      MessageConsumer result = session.createSharedConsumer(topic, sharedSubscriptionName, messageSelector);
      result = new ActiveMQRAMessageConsumer(result, this);

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

      addConsumer(result);

      return result;
   } finally {
      unlock();
   }
}
 
Example 15
Source File: SubscriptionsIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testSharedTopicSubscriberBehavesLikeNoClientIDWasSetWhenAwaitClientIdOptionIsFalse() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        int serverPort = testPeer.getServerPort();

        // Add server connection capability to indicate support for shared-subs
        Symbol[] serverCapabilities = new Symbol[]{SHARED_SUBS};

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen(null, serverCapabilities);
        testPeer.expectBegin();

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + serverPort + "?jms.awaitClientID=false");
        Connection connection = factory.createConnection();

        // Verify that all handlers complete, i.e. the awaitClientID=false option
        // setting was effective in provoking the AMQP Open immediately even
        // though it has no ClientID and we haven't used the Connection.
        testPeer.waitForAllHandlersToComplete(3000);

        testPeer.expectBegin();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session.createTopic(topicName);
        String subscriptionName = "mySubscription";

        // Expect a shared subscription with 'global' capability and link name qualifier,
        // since this connection does not have a ClientID set.
        Matcher<?> linkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "global-volatile1");
        testPeer.expectSharedVolatileSubscriberAttach(topicName, subscriptionName, linkNameMatcher, false);
        testPeer.expectLinkFlow();

        MessageConsumer subscriber = session.createSharedConsumer(dest, subscriptionName);

        testPeer.expectDetach(true, true, true);
        subscriber.close();

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 16
Source File: SubscriptionsIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doSharedSubscriptionNotSupportedTestImpl(boolean durable, boolean repeat) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // DONT include server connection capability to indicate support for shared-subs
        // This will cause the link capability to be desired, and we verify failure if not offered.
        Symbol[] serverCapabilities = new Symbol[]{};

        Connection connection = testFixture.establishConnecton(testPeer, serverCapabilities);
        connection.start();

        testPeer.expectBegin();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session.createTopic(topicName);
        String subscriptionName = "mySubscription";

        int iterations = repeat ? 2 : 1;

        // Expect a shared receiver to attach, then detach due to the link also not
        // reporting it offers the shared subs capability, i.e sharing not supported.
        for (int i = 0; i < iterations; i++) {
            try {
                if (durable) {
                    Matcher<?> durableLinkNameMatcher = equalTo(subscriptionName);
                    testPeer.expectSharedSubscriberAttach(topicName, subscriptionName, durableLinkNameMatcher, true, false, true, true, false);
                    testPeer.expectDetach(false, true, false);

                    session.createSharedDurableConsumer(dest, subscriptionName);
                } else {
                    Matcher<?> volatileLinkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "volatile1");
                    testPeer.expectSharedSubscriberAttach(topicName, subscriptionName, volatileLinkNameMatcher, false, false, true, true, false);
                    testPeer.expectDetach(true, true, true);

                    session.createSharedConsumer(dest, subscriptionName);
                }

                fail("Expected an exception to be thrown");
            } catch (JMSException jmse) {
                // expected
            }
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 17
Source File: SoakPagingTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void consume(ConnectionFactory factory, int index, CountDownLatch latch) {
   try {
      Connection connection = factory.createConnection("admin", "admin");

      final Session session;

      if (transaction) {
         session = connection.createSession(true, Session.SESSION_TRANSACTED);
      } else {
         session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
      }

      Destination address;

      if (consumerType.equals("queue")) {
         address = session.createQueue(destination);
      } else {
         address = session.createTopic(destination);
      }

      String consumerId = "ss" + (index % 5);
      MessageConsumer messageConsumer;

      if (protocol.equals("shared")) {
         messageConsumer = session.createSharedConsumer((Topic)address, consumerId);
      } else {
         messageConsumer = session.createConsumer(address);
      }

      if (LAG_CONSUMER_TIME > 0) Thread.sleep(LAG_CONSUMER_TIME);

      latch.countDown();
      connection.start();
      System.out.println("Consumer" + index + " started");

      int i = 0;
      while (true) {
         Message m = messageConsumer.receive(1000);
         consumed.incrementAndGet();
         if (m == null)
            System.out.println("Consumer" + index + "received null");
         i++;
         if (i % 100 == 0) {
            System.out.println("Consumer" + index + "received " + i + " messages");
            if (transaction) {
               session.commit();
            }
         }
      }
   } catch (Exception e) {
      System.err.println("Error on Consumer" + index + ": " + e.getMessage());
      e.printStackTrace();
   }
}
 
Example 18
Source File: TopicDurableTests.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSharedNonDurableSubscription() throws Exception {
   int iterations = 10;
   for (int i = 0; i < iterations; i++) {
      instanceLog.debug("testSharedNonDurableSubscription; iteration: " + i);
      //SETUP-START
      JmsConnectionFactory connectionFactory1 = new JmsConnectionFactory(getBrokerQpidJMSConnectionURI());
      Connection connection1 = connectionFactory1.createConnection();


      Hashtable env2 = new Hashtable<Object, Object>();
      env2.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
      env2.put("connectionfactory.qpidConnectionFactory", "amqp://localhost:5672");
      env2.put("topic." + "jmsTopic", "jmsTopic");
      Context context2 = new InitialContext(env2);
      ConnectionFactory connectionFactory2 = (ConnectionFactory) context2.lookup("qpidConnectionFactory");
      Connection connection2 = connectionFactory2.createConnection();

      connection1.start();
      connection2.start();

      Session session = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic testTopic = session.createTopic("jmsTopic");
      //SETUP-END

      //BODY-S
      String subID = "sharedConsumerNonDurable123";
      MessageConsumer subscriber1 = session.createSharedConsumer(testTopic, subID);
      MessageConsumer subscriber2 = session2.createSharedConsumer(testTopic, subID);
      MessageConsumer subscriber3 = session2.createSharedConsumer(testTopic, subID);
      MessageProducer messageProducer = session.createProducer(testTopic);
      messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

      int count = 10;
      List<Message> listMsgs = generateMessages(session, count);
      List<CompletableFuture<List<Message>>> results = receiveMessagesAsync(count, subscriber1, subscriber2, subscriber3);
      sendMessages(messageProducer, listMsgs);
      instanceLog.debug("messages sent");

      assertThat("Each message should be received only by one consumer",
                 results.get(0).get(20, TimeUnit.SECONDS).size() +
                    results.get(1).get(20, TimeUnit.SECONDS).size() +
                    results.get(2).get(20, TimeUnit.SECONDS).size(),
                 is(count));
      instanceLog.debug("messages received");
      //BODY-E

      //TEAR-DOWN-S
      connection1.stop();
      connection2.stop();
      subscriber1.close();
      subscriber2.close();
      session.close();
      session2.close();
      connection1.close();
      connection2.close();
      //TEAR-DOWN-E

      // ensure the topic is auto-deleted before continuing to the next iteration
      Wait.assertTrue(() -> server.getAddressInfo(SimpleString.toSimpleString("jmsTopic")) == null, 2000, 100);
   }
}
 
Example 19
Source File: JMSSharedConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void testSharedConsumer(Connection connection1, Connection connection2, boolean amqpQueueName) throws Exception {
   try {
      Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Topic topic = session1.createTopic(getTopicName());
      Topic topic2 = session2.createTopic(getTopicName());

      final MessageConsumer consumer1 = session1.createSharedConsumer(topic, "SharedConsumer");
      final MessageConsumer consumer2 = session2.createSharedConsumer(topic2, "SharedConsumer");

      MessageProducer producer = session1.createProducer(topic);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);
      connection1.start();

      TextMessage message = session1.createTextMessage();
      message.setText("hello");
      producer.send(message);

      Message message1 = consumer1.receive(100);
      Message message2 = consumer2.receive(100);

      Message received = null;
      if (message1 != null) {
         assertNull("Message should only be delivered once per subscribtion but see twice", message2);
         received = message1;
      } else {
         received = message2;
      }
      assertNotNull("Should have received a message by now.", received);
      assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);

      String consumerQueueName = "nonDurable.SharedConsumer";
      if (amqpQueueName) {
         consumerQueueName = "SharedConsumer:shared-volatile:global";
      }
      QueueBinding queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(consumerQueueName));
      assertTrue(queueBinding.getQueue().isTemporary());
   } finally {
      connection1.close();
      connection2.close();
   }
}
 
Example 20
Source File: MessagingAddressJMSTest.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled("javax.jms.JMSException: Remote peer does not support shared subscriptions")
@DisplayName("testSharedNonDurableSubscription")
void testSharedNonDurableSubscription(JmsProvider jmsProvider) throws Exception {
    String topicAddress = "jmsTopicNonDurable";
    String subID = "sharedConsumerDurable123";
    MessagingAddress addressTopic = new MessagingAddressBuilder()
            .withNewMetadata()
            .withNamespace(tenant.getMetadata().getNamespace())
            .withName("jms-topic-nondurable")
            .endMetadata()
            .withNewSpec()
            .editOrNewTopic()
            .endTopic()
            .withAddress(topicAddress)
            .endSpec()
            .build();
    resourceManager.createResource(addressTopic);

    Context context1 = createContext(jmsProvider, addressTopic);
    Connection connection1 = jmsProvider.createConnection(context1);
    Context context2 = createContext(jmsProvider, addressTopic);
    Connection connection2 = jmsProvider.createConnection(context2);
    connection1.start();
    connection2.start();

    Session session = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

    Topic testTopic = (Topic) jmsProvider.getDestination(addressTopic.getSpec().getAddress());
    MessageConsumer subscriber1 = session.createSharedConsumer(testTopic, subID);
    MessageConsumer subscriber2 = session2.createSharedConsumer(testTopic, subID);
    MessageConsumer subscriber3 = session2.createSharedConsumer(testTopic, subID);
    MessageProducer messageProducer = session.createProducer(testTopic);
    messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    int count = 10;
    List<javax.jms.Message> listMsgs = jmsProvider.generateMessages(session, count);
    List<CompletableFuture<List<javax.jms.Message>>> results = jmsProvider.receiveMessagesAsync(count, subscriber1, subscriber2, subscriber3);
    jmsProvider.sendMessages(messageProducer, listMsgs);
    log.info("messages sent");

    assertThat("Each message should be received only by one consumer",
            results.get(0).get(20, TimeUnit.SECONDS).size() +
                    results.get(1).get(20, TimeUnit.SECONDS).size() +
                    results.get(2).get(20, TimeUnit.SECONDS).size(),
            is(count));
    log.info("messages received");

    connection1.stop();
    connection2.stop();
    subscriber1.close();
    subscriber2.close();
    subscriber3.close();
    session.close();
    session2.close();
    connection1.close();
    connection2.close();
}