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

The following examples show how to use javax.jms.Session#createSharedDurableConsumer() . 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 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 2
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 3
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public MessageConsumer createSharedDurableConsumer(Topic topic, String name) throws JMSException {
   lock();
   try {
      Session session = getSessionInternal();

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

      MessageConsumer result = session.createSharedDurableConsumer(topic, name);
      result = new ActiveMQRAMessageConsumer(result, this);

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

      addConsumer(result);

      return result;
   } finally {
      unlock();
   }
}
 
Example 4
Source File: JmsConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsubscribeDurable() throws Exception {
   conn = cf.createConnection();
   conn.setClientID("C1");
   conn.start();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   MessageConsumer cons = session.createSharedDurableConsumer(topic, "c1");

   MessageProducer prod = session.createProducer(topic);

   for (int i = 0; i < 100; i++) {
      prod.send(session.createTextMessage("msg" + i));
   }

   Assert.assertNotNull(cons.receive(5000));

   cons.close();

   session.unsubscribe("c1");

   cons = session.createSharedDurableConsumer(topic, "c1");

   // it should be null since the queue was deleted through unsubscribe
   Assert.assertNull(cons.receiveNoWait());
}
 
Example 5
Source File: CreateSubscriptionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedDurableConsumer() 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.createSharedDurableConsumer(topic, "consumer1");
      MessageConsumer messageConsumer2 = session2.createSharedDurableConsumer(topic, "consumer1");



      connection.close();
   } finally {
      connection.close();
      connecton2.close();
   }
}
 
Example 6
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 7
Source File: JmsConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedDurableConsumerWithClientID() throws Exception {
   conn = cf.createConnection();
   conn.setClientID("C1");
   conn.start();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   Connection conn2 = cf.createConnection();
   conn2.setClientID("C2");
   Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);

   {
      Connection conn3 = cf.createConnection();

      boolean exception = false;
      try {
         conn3.setClientID("C2");
      } catch (Exception e) {
         exception = true;
      }

      Assert.assertTrue(exception);
      conn3.close();
   }

   topic = ActiveMQJMSClient.createTopic(T_NAME);

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

   MessageProducer producer = session.createProducer(topic);

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

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

   Assert.assertNotNull(txt);
}
 
Example 8
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 9
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public MessageConsumer createSharedDurableConsumer(Topic topic,
                                                   String name,
                                                   String messageSelector) throws JMSException {
   lock();
   try {
      Session session = getSessionInternal();

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

      MessageConsumer result = session.createSharedDurableConsumer(topic, name, messageSelector);
      result = new ActiveMQRAMessageConsumer(result, this);

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

      addConsumer(result);

      return result;
   } finally {
      unlock();
   }
}
 
Example 10
Source File: JMSSharedDurableConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void testSharedDurableConsumer(Connection connection1, Connection connection2) throws JMSException {
   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.createSharedDurableConsumer(topic, "SharedConsumer");
      final MessageConsumer consumer2 = session2.createSharedDurableConsumer(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);

      consumer1.close();
      consumer2.close();
      session1.unsubscribe("SharedConsumer");
   } finally {
      connection1.close();
      connection2.close();
   }
}
 
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 4 votes vote down vote up
/**
 * Verifies that subscriber cleanup occurs when the session it is on is locally closed.
 *
 * @throws Exception if an unexpected error is encountered
 */
@Test(timeout = 20000)
public void testLocallyEndSessionWithSharedConsumer() 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);

        final CountDownLatch sessionClosed = new CountDownLatch(1);
        ((JmsConnection) connection).addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onSessionClosed(Session session, Throwable exception) {
                sessionClosed.countDown();
            }
        });

        // Create first session
        testPeer.expectBegin();
        Session session1 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session1.createTopic(topicName);

        String subscriptionName = "mySubscription";

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

        MessageConsumer subscriber1 = session1.createSharedDurableConsumer(dest,  subscriptionName);

        // Create second session
        testPeer.expectBegin();
        Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Attach the second shared receiver on the second session
        durableLinkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "2");
        testPeer.expectSharedDurableSubscriberAttach(topicName, subscriptionName, durableLinkNameMatcher, true);
        testPeer.expectLinkFlow();

        MessageConsumer subscriber2 = session2.createSharedDurableConsumer(dest,  subscriptionName);
        assertNotNull(subscriber2);

        // Now close the second session (and thus the subscriber along with it).
        testPeer.expectEnd();
        session2.close();

        // Now try to unsubscribe (using first session, still open). It should fail due to sub still
        // being in use on the first session. No frames should be sent.
        try {
            session1.unsubscribe(subscriptionName);
            fail("Should have thrown a JMSException");
        } catch (JMSException ex) {
            // Expected
        }

        // Now close the first subscriber
        testPeer.expectDetach(false, true, false);
        subscriber1.close();

        testPeer.waitForAllHandlersToComplete(1000);

        // Try to unsubscribe again (using first session, still open), should now work.
        testPeer.expectDurableSubUnsubscribeNullSourceLookup(false, false, subscriptionName, topicName, true);
        testPeer.expectDetach(true, true, true);

        session1.unsubscribe(subscriptionName);

        testPeer.expectClose();
        connection.close();
    }
}
 
Example 13
Source File: JmsConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testShareDurable() throws Exception {
   ((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0);
   conn = cf.createConnection();
   conn.start();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Session session2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   MessageConsumer cons = session.createSharedDurableConsumer(topic, "c1");
   MessageConsumer cons2 = session2.createSharedDurableConsumer(topic, "c1");

   MessageProducer prod = session.createProducer(topic);

   for (int i = 0; i < 100; i++) {
      prod.send(session.createTextMessage("msg" + i));
   }

   for (int i = 0; i < 50; i++) {
      Message msg = cons.receive(5000);
      Assert.assertNotNull(msg);
      msg = cons2.receive(5000);
      Assert.assertNotNull(msg);
   }

   Assert.assertNull(cons.receiveNoWait());
   Assert.assertNull(cons2.receiveNoWait());

   cons.close();

   boolean exceptionHappened = false;

   try {
      session.unsubscribe("c1");
   } catch (JMSException e) {
      exceptionHappened = true;
   }

   Assert.assertTrue(exceptionHappened);

   cons2.close();

   for (int i = 0; i < 100; i++) {
      prod.send(session.createTextMessage("msg" + i));
   }

   session.unsubscribe("c1");

   cons = session.createSharedDurableConsumer(topic, "c1");

   // it should be null since the queue was deleted through unsubscribe
   Assert.assertNull(cons.receiveNoWait());
}
 
Example 14
Source File: QueueAutoDeleteTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testAutoDeleteTopicDurableSubscriptionQueue() throws Exception {
   ConnectionFactory fact = getCF();
   Connection connection = fact.createConnection();
   connection.start();

   try {

      Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

      String testQueueName = getName();
      String sub = testQueueName + "/mysub";

      Topic topic = session.createTopic(testQueueName + "?auto-delete=true");
      ActiveMQDestination activeMQDestination = (ActiveMQDestination) topic;

      assertEquals(testQueueName, topic.getTopicName());
      assertEquals(true, activeMQDestination.getQueueAttributes().getAutoDelete());
      assertEquals(true, activeMQDestination.getQueueConfiguration().isAutoDelete());


      MessageConsumer consumer = session.createSharedDurableConsumer(topic, sub);

      QueueBinding queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(sub));
      assertTrue(queueBinding.getQueue().isAutoDelete());
      assertEquals(0, queueBinding.getQueue().getMessageCount());

      MessageProducer producer = session.createProducer(topic);
      producer.send(session.createTextMessage("hello1"));
      producer.send(session.createTextMessage("hello2"));

      Message message = consumer.receive(5000);
      assertNotNull(message);
      assertEquals("hello1", ((TextMessage)message).getText());
      message.acknowledge();

      consumer.close();

      queueBinding = (QueueBinding) server.getPostOffice().getBinding(SimpleString.toSimpleString(sub));
      assertNotNull(queueBinding);

      consumer = session.createSharedDurableConsumer(topic, sub);
      message = consumer.receive(5000);
      assertNotNull(message);
      assertEquals("hello2", ((TextMessage)message).getText());
      message.acknowledge();

      consumer.close();

      Wait.assertTrue(() -> server.getPostOffice().getBinding(SimpleString.toSimpleString(sub)) == null, 5000, 10);

   } finally {
      connection.close();
   }
}
 
Example 15
Source File: SubscriptionsIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that subscriber cleanup occurs when the session it is on is remotely closed.
 *
 * @throws Exception if an unexpected error is encountered
 */
@Test(timeout = 20000)
public void testRemotelyEndSessionWithDurableSharedConsumer() 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);

        final CountDownLatch sessionClosed = new CountDownLatch(1);
        ((JmsConnection) connection).addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onSessionClosed(Session session, Throwable exception) {
                sessionClosed.countDown();
            }
        });

        // Create first session
        testPeer.expectBegin();
        Session session1 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session1.createTopic(topicName);

        String subscriptionName = "mySubscription";

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

        MessageConsumer subscriber1 = session1.createSharedDurableConsumer(dest,  subscriptionName);

        // Create second session
        testPeer.expectBegin();
        Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Attach the second shared receiver on the second session
        durableLinkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "2");
        testPeer.expectSharedDurableSubscriberAttach(topicName, subscriptionName, durableLinkNameMatcher, true);

        testPeer.expectLinkFlow();

        // Then remotely end the session (and thus the subscriber along with it) after the flow is received.
        testPeer.remotelyEndLastOpenedSession(true, 0, AmqpError.RESOURCE_LIMIT_EXCEEDED, "TestingRemoteClosure");

        MessageConsumer subscriber2 = session2.createSharedDurableConsumer(dest,  subscriptionName);
        assertNotNull(subscriber2);

        assertTrue("Session closed callback didn't trigger", sessionClosed.await(5, TimeUnit.SECONDS));

        testPeer.waitForAllHandlersToComplete(1000);

        // Now try to unsubscribe (using first session, still open). It should fail due to sub still
        // being in use on the first session. No frames should be sent.
        try {
            session1.unsubscribe(subscriptionName);
            fail("Should have thrown a JMSException");
        } catch (JMSException ex) {
            // Expected
        }

        // Now close the first subscriber
        testPeer.expectDetach(false, true, false);
        subscriber1.close();

        testPeer.waitForAllHandlersToComplete(1000);

        // Try to unsubscribe again (using first session, still open), should now work.
        testPeer.expectDurableSubUnsubscribeNullSourceLookup(false, false, subscriptionName, topicName, true);
        testPeer.expectDetach(true, true, true);

        session1.unsubscribe(subscriptionName);

        testPeer.expectClose();
        connection.close();
    }
}
 
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: MessagingAddressJMSTest.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled("Not yet supported")
@DisplayName("testSharedDurableSubscription")
void testSharedDurableSubscription(JmsProvider jmsProvider) throws Exception {
    String topicAddress = "jmsTopicDurable";
    String subID = "sharedConsumerDurable123";
    MessagingAddress addressTopic = new MessagingAddressBuilder()
            .withNewMetadata()
            .withNamespace(tenant.getMetadata().getNamespace())
            .withName("jms-topic-durable")
            .endMetadata()
            .withNewSpec()
            .editOrNewTopic()
            .endTopic()
            .withAddress(topicAddress)
            .endSpec()
            .build();
    MessagingAddress addressSub1= new MessagingAddressBuilder()
            .withNewMetadata()
            .withNamespace(tenant.getMetadata().getNamespace())
            .withName("jms-topic-durable-sub")
            .endMetadata()
            .withNewSpec()
            .editOrNewSubscription()
            .withTopic(topicAddress)
            .endSubscription()
            .withAddress(subID)
            .endSpec()
            .build();
    resourceManager.createResource(addressTopic, addressSub1);

    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(topicAddress);

    log.info("Creating subscriber 1");
    MessageConsumer subscriber1 = session.createSharedDurableConsumer(testTopic, subID);
    log.info("Creating subscriber 2");
    MessageConsumer subscriber2 = session2.createSharedDurableConsumer(testTopic, subID);
    log.info("Creating producer");
    MessageProducer messageProducer = session.createProducer(testTopic);
    messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

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

    List<javax.jms.Message> recvd1 = jmsProvider.receiveMessages(subscriber1, count, 1);
    List<javax.jms.Message> recvd2 = jmsProvider.receiveMessages(subscriber2, count, 1);

    log.info(subID + " :messages received");

    assertThat("Wrong count of messages received: by both receivers",
            recvd1.size() + recvd2.size(), is(2 * count));

    subscriber1.close();
    subscriber2.close();
    session.unsubscribe(subID);
    session2.unsubscribe(subID);
    connection1.stop();
    connection2.stop();
    session.close();
    session2.close();
    connection1.close();
    connection2.close();
}
 
Example 18
Source File: SubscriptionsIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doMultipleConnectionSharedSubscriberLinkNamesHaveUniqueCounterSuffixTestImpl(boolean durable) throws Exception {
    try (TestAmqpPeer peer1 = new TestAmqpPeer();
         TestAmqpPeer peer2 = new TestAmqpPeer();) {
        // Add server connection capability to indicate support for shared-subs
        Symbol[] serverCapabilities = new Symbol[]{SHARED_SUBS};

        // Establish first connection
        Connection connection1 = testFixture.establishConnecton(peer1, serverCapabilities);
        connection1.start();

        peer1.expectBegin();
        Session sessionConn1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Establish second connection
        Connection connection2 = testFixture.establishConnecton(peer2, serverCapabilities);
        connection2.start();

        peer2.expectBegin();
        Session sessionConn2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

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

        Matcher<?> durSubLinkNameMatcher = equalTo(subscriptionName);
        Matcher<?> volatileSubLinkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "volatile1");

        // Attach the first connections shared receiver
        if (durable) {
            peer1.expectSharedDurableSubscriberAttach(topicName, subscriptionName, durSubLinkNameMatcher, true);
        } else {
            peer1.expectSharedVolatileSubscriberAttach(topicName, subscriptionName, volatileSubLinkNameMatcher, true);
        }
        peer1.expectLinkFlow();

        if (durable) {
            sessionConn1.createSharedDurableConsumer(dest, subscriptionName);
        } else {
            sessionConn1.createSharedConsumer(dest, subscriptionName);
        }

        // Attach the second connections shared receiver, expect the link name to be the same since its per-connection
        if (durable) {
            peer2.expectSharedDurableSubscriberAttach(topicName, subscriptionName, durSubLinkNameMatcher, true);
        } else {
            peer2.expectSharedVolatileSubscriberAttach(topicName, subscriptionName, volatileSubLinkNameMatcher, true);
        }
        peer2.expectLinkFlow();

        if (durable) {
            sessionConn2.createSharedDurableConsumer(dest, subscriptionName);
        } else {
            sessionConn2.createSharedConsumer(dest, subscriptionName);
        }

        peer1.expectClose();
        connection1.close();

        peer2.expectClose();
        connection2.close();

        peer1.waitForAllHandlersToComplete(1000);
        peer2.waitForAllHandlersToComplete(1000);
    }
}
 
Example 19
Source File: SubscriptionsIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that subscriber cleanup occurs when the subscriber is remotely closed (after creation).
 *
 * @throws Exception if an unexpected error is encountered
 */
@Test(timeout = 20000)
public void testRemotelyDetachLinkWithDurableSharedConsumer() 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);

        final CountDownLatch subscriberClosed = new CountDownLatch(1);
        ((JmsConnection) connection).addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConsumerClosed(MessageConsumer consumer, Throwable exception) {
                subscriberClosed.countDown();
            }
        });

        // Create first session
        testPeer.expectBegin();
        Session session1 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session1.createTopic(topicName);

        String subscriptionName = "mySubscription";

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

        MessageConsumer subscriber1 = session1.createSharedDurableConsumer(dest,  subscriptionName);

        // Create second session
        testPeer.expectBegin();
        Session session2 = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Attach the second shared receiver on the second session
        durableLinkNameMatcher = equalTo(subscriptionName + SUB_NAME_DELIMITER + "2");
        testPeer.expectSharedDurableSubscriberAttach(topicName, subscriptionName, durableLinkNameMatcher, true);

        testPeer.expectLinkFlow();

        // Then remotely detach the link after the flow is received.
        testPeer.remotelyDetachLastOpenedLinkOnLastOpenedSession(true, false, AmqpError.RESOURCE_LIMIT_EXCEEDED, "TestingRemoteDetach");

        MessageConsumer subscriber2 = session2.createSharedDurableConsumer(dest,  subscriptionName);
        assertNotNull(subscriber2);

        assertTrue("Consumer closed callback didn't trigger", subscriberClosed.await(5, TimeUnit.SECONDS));

        testPeer.waitForAllHandlersToComplete(1000);

        // Now try to unsubscribe (using first session). It should fail due to sub still
        // being in use on the first session. No frames should be sent.
        try {
            session1.unsubscribe(subscriptionName);
            fail("Should have thrown a JMSException");
        } catch (JMSException ex) {
            // Expected
        }

        // Now close the first subscriber
        testPeer.expectDetach(false, true, false);
        subscriber1.close();

        testPeer.waitForAllHandlersToComplete(1000);

        // Try to unsubscribe again (using first session), should now work.
        testPeer.expectDurableSubUnsubscribeNullSourceLookup(false, false, subscriptionName, topicName, true);
        testPeer.expectDetach(true, true, true);

        session1.unsubscribe(subscriptionName);

        testPeer.expectClose();
        connection.close();
    }
}
 
Example 20
Source File: FederatedAddressDivertExample.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
public static void main(final String[] args) throws Exception {
   Connection connectionEUWest = null;

   Connection connectionEUEast = null;


   try {
      // Step 1. Instantiate the Topic (multicast) for the producers
      Topic topic = ActiveMQJMSClient.createTopic("exampleTopic");

      //Create a topic for the consumers
      Topic topic2 = ActiveMQJMSClient.createTopic("divertExampleTopic");

      // Step 2. Instantiate connection towards server EU West
      ConnectionFactory cfEUWest = new ActiveMQConnectionFactory("tcp://localhost:61616");

      // Step 3. Instantiate connection towards server EU East
      ConnectionFactory cfEUEast = new ActiveMQConnectionFactory("tcp://localhost:61617");


      // Step 5. We create a JMS Connection connectionEUWest which is a connection to server EU West
      connectionEUWest = cfEUWest.createConnection();

      // Step 6. We create a JMS Connection connectionEUEast which is a connection to server EU East
      connectionEUEast = cfEUEast.createConnection();

      // Step 8. We create a JMS Session on server EU West
      Session sessionEUWest = connectionEUWest.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // Step 9. We create a JMS Session on server EU East
      Session sessionEUEast = connectionEUEast.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // Step 11. We start the connections to ensure delivery occurs on them
      connectionEUWest.start();

      connectionEUEast.start();

      // Step 12. We create a JMS MessageProducer object on each server
      MessageProducer producerEUEast = sessionEUEast.createProducer(topic);

      // Step 13. We create JMS MessageConsumer objects on each server - Messages will be diverted to this topic
      MessageConsumer consumerEUWest = sessionEUWest.createSharedDurableConsumer(topic2, "exampleSubscription");


      // Step 14. Let a little time for everything to start and form.

      Thread.sleep(5000);

      // Step 13. We send some messages to server EU West
      final int numMessages = 10;

      // Step 15. Repeat same test one last time, this time sending on EU East

      for (int i = 0; i < numMessages; i++) {
         TextMessage message = sessionEUEast.createTextMessage("This is text sent from EU East, message " + i);

         producerEUEast.send(message);

         System.out.println("EU East   :: Sent message: " + message.getText());
      }

      // Step 14. We now consume those messages on *all* servers .
      // We note that every consumer, receives a message even so on seperate servers

      for (int i = 0; i < numMessages; i++) {
         TextMessage messageEUWest = (TextMessage) consumerEUWest.receive(5000);

         System.out.println("EU West   :: Got message: " + messageEUWest.getText());
      }
   } finally {
      // Step 16. Be sure to close our resources!
      if (connectionEUWest != null) {
         connectionEUWest.stop();
         connectionEUWest.close();
      }

      if (connectionEUEast != null) {
         connectionEUEast.stop();
         connectionEUEast.close();
      }
   }
}