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

The following examples show how to use javax.jms.Session#unsubscribe() . 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: DurableSubscriptionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribeWithActiveSubscription() throws Exception {
   Connection conn = createConnection();
   conn.setClientID("zeke");

   Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

   TopicSubscriber dursub1 = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "dursub1");

   try {
      s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "dursub1");
      ProxyAssertSupport.fail();
   } catch (IllegalStateException e) {
      // Ok - it is illegal to have more than one active subscriber on a subscrtiption at any one time
   }

   dursub1.close();

   s.unsubscribe("dursub1");
}
 
Example 2
Source File: ActiveMQRASession.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Unsubscribe
 *
 * @param name The name
 * @throws JMSException Thrown if an error occurs
 */
@Override
public void unsubscribe(final String name) throws JMSException {
   if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) {
      throw new IllegalStateException("Cannot unsubscribe for javax.jms.QueueSession");
   }

   lock();
   try {
      Session session = getSessionInternal();

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

      session.unsubscribe(name);
   } finally {
      unlock();
   }
}
 
Example 3
Source File: JMSTopicConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testDurableSubscriptionUnsubscribe() throws Exception {
   Connection connection = createConnection("myClientId");

   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic topic = session.createTopic(getTopicName());
      TopicSubscriber myDurSub = session.createDurableSubscriber(topic, "myDurSub");
      session.close();
      connection.close();

      connection = createConnection("myClientId");
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      myDurSub = session.createDurableSubscriber(topic, "myDurSub");
      myDurSub.close();

      Assert.assertNotNull(server.getPostOffice().getBinding(new SimpleString("myClientId.myDurSub")));
      session.unsubscribe("myDurSub");
      Assert.assertNull(server.getPostOffice().getBinding(new SimpleString("myClientId.myDurSub")));
      session.close();
      connection.close();
   } finally {
      connection.close();
   }
}
 
Example 4
Source File: JmsDurableSubscriberTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testDurableSubscriptionUnsubscribeNoExistingSubThrowsJMSEx() throws Exception {
    connection = createAmqpConnection();
    connection.setClientID("DURABLE-AMQP");
    connection.start();

    assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
    assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

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

    BrokerViewMBean broker = getProxyToBroker();
    assertEquals(0, broker.getDurableTopicSubscribers().length);
    assertEquals(0, broker.getInactiveDurableTopicSubscribers().length);

    try {
        session.unsubscribe(getSubscriptionName());
        fail("Should have thrown an InvalidDestinationException");
    } catch (InvalidDestinationException ide) {
    }
}
 
Example 5
Source File: DurableSubscriptionTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsubscribeDurableSubscription() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();
      conn.setClientID("ak47");

      Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer cons = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "uzzi");
      MessageProducer prod = s.createProducer(ActiveMQServerTestCase.topic1);
      prod.setDeliveryMode(DeliveryMode.PERSISTENT);

      prod.send(s.createTextMessage("one"));

      cons.close();
      s.unsubscribe("uzzi");

      MessageConsumer ds = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "uzzi");
      conn.start();

      ProxyAssertSupport.assertNull(ds.receiveNoWait());

      ds.close();

      s.unsubscribe("uzzi");
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}
 
Example 6
Source File: JmsDurableSubscriberTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testDurableGoesOfflineAndReturns() throws Exception {
    connection = createAmqpConnection();
    connection.setClientID("DURABLE-AMQP");
    connection.start();

    assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
    assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    assertNotNull(session);
    Topic topic = session.createTopic(name.getMethodName());
    TopicSubscriber subscriber = session.createDurableSubscriber(topic, getSubscriptionName());

    TopicViewMBean proxy = getProxyToTopic(name.getMethodName());
    assertEquals(0, proxy.getQueueSize());

    assertEquals(1, brokerService.getAdminView().getDurableTopicSubscribers().length);
    assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

    subscriber.close();

    assertEquals(0, brokerService.getAdminView().getDurableTopicSubscribers().length);
    assertEquals(1, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

    subscriber = session.createDurableSubscriber(topic, getSubscriptionName());

    assertEquals(1, brokerService.getAdminView().getDurableTopicSubscribers().length);
    assertEquals(0, brokerService.getAdminView().getInactiveDurableTopicSubscribers().length);

    subscriber.close();

    session.unsubscribe(getSubscriptionName());
}
 
Example 7
Source File: DurableSubSelectorDelayWithRestartTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void unsubscribe() throws JMSException {
   Connection con = openConnection();
   Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.unsubscribe(subName);
   session.close();
   con.close();
}
 
Example 8
Source File: DurableSubProcessTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void unsubscribe() throws JMSException {
   Connection con = openConnection();
   Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.unsubscribe(SUBSCRIPTION_NAME);
   session.close();
   con.close();
}
 
Example 9
Source File: JMSBridgeTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void internalTestDurableSubscriber(final boolean largeMessage, final int batchSize) throws Exception {
   JMSBridgeImpl bridge = null;

   try {
      final int NUM_MESSAGES = 10;

      bridge = new JMSBridgeImpl(cff0, cff1, sourceTopicFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, batchSize, -1, "subTest", "clientid123", false).setBridgeName("test-bridge");

      bridge.start();

      sendMessages(cf0, sourceTopic, 0, NUM_MESSAGES, true, largeMessage);

      checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES, largeMessage);
      Assert.assertEquals(0L, bridge.getAbortedMessageCount());
      Assert.assertEquals("We didn't get the correct number processed messages", NUM_MESSAGES, bridge.getMessageCount());
   } finally {
      if (bridge != null) {
         bridge.stop();
      }

      // Now unsubscribe
      Connection conn = cf0.createConnection();
      conn.setClientID("clientid123");
      Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      sess.unsubscribe("subTest");
      conn.close();
   }
}
 
Example 10
Source File: FailoverProviderTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testSessionUnsubscribePassthrough() throws Exception {
    JmsConnectionFactory factory = new JmsConnectionFactory(
        "failover:(mock://localhost)");

    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    session.unsubscribe("some-subscription");
    connection.close();

    assertEquals(1, mockPeer.getContextStats().getUnsubscribeCalls());
}
 
Example 11
Source File: JMSDurableConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testDurableConsumerUnsubscribe() throws Exception {
   String durableClientId = getTopicName() + "-ClientId";

   Connection connection = createConnection(durableClientId);
   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic topic = session.createTopic(getTopicName());
      MessageConsumer consumer = session.createDurableSubscriber(topic, "DurbaleTopic");

      assertTrue(Wait.waitFor(new Wait.Condition() {

         @Override
         public boolean isSatisfied() throws Exception {
            return server.getTotalConsumerCount() == 1;
         }
      }, TimeUnit.SECONDS.toMillis(20), TimeUnit.MILLISECONDS.toMillis(250)));

      consumer.close();

      assertTrue(Wait.waitFor(new Wait.Condition() {

         @Override
         public boolean isSatisfied() throws Exception {
            return server.getTotalConsumerCount() == 0;
         }
      }, TimeUnit.SECONDS.toMillis(20), TimeUnit.MILLISECONDS.toMillis(250)));

      session.unsubscribe("DurbaleTopic");
      assertTrue(Wait.waitFor(new Wait.Condition() {

         @Override
         public boolean isSatisfied() throws Exception {
            return server.getTotalConsumerCount() == 0;
         }
      }, TimeUnit.SECONDS.toMillis(20), TimeUnit.MILLISECONDS.toMillis(250)));
   } finally {
      connection.close();
   }
}
 
Example 12
Source File: DurableSubProcessConcurrentCommitActivateNoDuplicateTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void unsubscribe() throws JMSException {
   processLock.readLock().lock();
   LOG.info("Unsubscribe: " + this);
   try {
      Connection con = openConnection();
      Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      session.unsubscribe(SUBSCRIPTION_NAME);
      session.close();
      con.close();
   } finally {
      processLock.readLock().unlock();
   }
}
 
Example 13
Source File: SessionIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testDurableSubscriptionUnsubscribeInUseThrowsJMSEx() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

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

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

        testPeer.expectDurableSubscriberAttach(topicName, subscriptionName);
        testPeer.expectLinkFlow();

        TopicSubscriber subscriber = session.createDurableSubscriber(dest, subscriptionName);
        assertNotNull("TopicSubscriber object was null", subscriber);

        try {
            session.unsubscribe(subscriptionName);
            fail("Should have thrown a JMSException");
        } catch (JMSException ex) {
        }

        testPeer.expectDetach(false, true, false);

        subscriber.close();

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 14
Source File: DurableSubscriptionTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
/**
 * JMS 1.1 6.11.1: A client can change an existing durable subscription by creating a durable
 * TopicSubscriber with the same name and a new topic and/or message selector, or NoLocal
 * attribute. Changing a durable subscription is equivalent to deleting and recreating it.
 * <br>
 * Test with a different selector.
 */
@Test
public void testDurableSubscriptionDifferentSelector() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();

      conn.setClientID("brookeburke");

      Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer prod = s.createProducer(ActiveMQServerTestCase.topic1);
      prod.setDeliveryMode(DeliveryMode.PERSISTENT);

      MessageConsumer durable = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "monicabelucci", "color = 'red' AND shape = 'square'", false);

      TextMessage tm = s.createTextMessage("A red square message");
      tm.setStringProperty("color", "red");
      tm.setStringProperty("shape", "square");

      prod.send(tm);

      conn.start();

      TextMessage rm = (TextMessage) durable.receive(5000);
      ProxyAssertSupport.assertEquals("A red square message", rm.getText());

      tm = s.createTextMessage("Another red square message");
      tm.setStringProperty("color", "red");
      tm.setStringProperty("shape", "square");
      prod.send(tm);

      // TODO: when subscriptions/durable subscription will be registered as MBean, use the JMX
      // interface to make sure the 'another red square message' is maintained by the
      // durable subascription
      // http://jira.jboss.org/jira/browse/JBMESSAGING-217

      conn.close();

      conn = createConnection();

      conn.setClientID("brookeburke");

      s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // modify the selector
      durable = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "monicabelucci", "color = 'red'", false);

      conn.start();

      Message m = durable.receiveNoWait();

      // the durable subscription is destroyed and re-created. The red square message stored by
      // the previous durable subscription is lost and (hopefully) garbage collected.
      ProxyAssertSupport.assertNull(m);

      durable.close();

      s.unsubscribe("monicabelucci");
   } finally {
      if (conn != null) {
         conn.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 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 16
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 17
Source File: DurableSubscriptionOffline4Test.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 60 * 1000)
// https://issues.apache.org/jira/browse/AMQ-3206
public void testCleanupDeletedSubAfterRestart() throws Exception {
   Connection con = createConnection("cli1");
   Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.createDurableSubscriber(topic, "SubsId", null, true);
   session.close();
   con.close();

   con = createConnection("cli2");
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.createDurableSubscriber(topic, "SubsId", null, true);
   session.close();
   con.close();

   con = createConnection();
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(null);

   final int toSend = 500;
   final String payload = Arrays.toString(new byte[40 * 1024]);
   int sent = 0;
   for (int i = sent; i < toSend; i++) {
      Message message = session.createTextMessage(payload);
      message.setStringProperty("filter", "false");
      message.setIntProperty("ID", i);
      producer.send(topic, message);
      sent++;
   }
   con.close();
   LOG.info("sent: " + sent);

   // kill off cli1
   con = createConnection("cli1");
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.unsubscribe("SubsId");

   destroyBroker();
   createBroker(false);

   con = createConnection("cli2");
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true);
   final DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener();
   consumer.setMessageListener(listener);
   assertTrue("got all sent", Wait.waitFor(new Wait.Condition() {
      @Override
      public boolean isSatisified() throws Exception {
         LOG.info("Want: " + toSend + ", current: " + listener.count);
         return listener.count == toSend;
      }
   }));
   session.close();
   con.close();

   destroyBroker();
   createBroker(false);
   final KahaDBPersistenceAdapter pa = (KahaDBPersistenceAdapter) broker.getPersistenceAdapter();
   assertTrue("Should have less than three journal files left but was: " + pa.getStore().getJournal().getFileMap().size(), Wait.waitFor(new Wait.Condition() {

      @Override
      public boolean isSatisified() throws Exception {
         return pa.getStore().getJournal().getFileMap().size() <= 3;
      }
   }));
}
 
Example 18
Source File: MessagingAddressJMSTest.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Test
@Disabled("Not yet supported")
@DisplayName("testMessageDurableSubscriptionTransacted")
void testMessageDurableSubscriptionTransacted(JmsProvider jmsProvider) throws Exception {
    String topicAddress = "jmsTopicTrans";
    String sub1ID = "sub1DurSubTrans";
    String sub2ID = "sub2DurSubTrans";
    MessagingAddress addressTopic = new MessagingAddressBuilder()
            .withNewMetadata()
            .withNamespace(tenant.getMetadata().getNamespace())
            .withName("jms-topic-trans")
            .endMetadata()
            .withNewSpec()
            .editOrNewTopic()
            .endTopic()
            .withAddress(topicAddress)
            .endSpec()
            .build();
    MessagingAddress addressSub1= new MessagingAddressBuilder()
            .withNewMetadata()
            .withNamespace(tenant.getMetadata().getNamespace())
            .withName("jms-topic-trans-sub1")
            .endMetadata()
            .withNewSpec()
            .editOrNewSubscription()
            .withTopic(topicAddress)
            .endSubscription()
            .withAddress(sub1ID)
            .endSpec()
            .build();
    MessagingAddress addressSub2= new MessagingAddressBuilder()
            .withNewMetadata()
            .withNamespace(tenant.getMetadata().getNamespace())
            .withName("jms-topic-trans-sub2")
            .endMetadata()
            .withNewSpec()
            .editOrNewSubscription()
            .withTopic(topicAddress)
            .endSubscription()
            .withAddress(sub2ID)
            .endSpec()
            .build();
    resourceManager.createResource(addressTopic, addressSub1, addressSub2);

    Context context = createContext(jmsProvider, addressTopic);
    Connection connection = jmsProvider.createConnection(context);
    connection.start();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Topic testTopic = (Topic) jmsProvider.getDestination(addressTopic.getSpec().getAddress());


    MessageConsumer subscriber1 = session.createDurableSubscriber(testTopic, sub1ID);
    MessageConsumer subscriber2 = session.createDurableSubscriber(testTopic, sub2ID);
    MessageProducer messageProducer = session.createProducer(testTopic);

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

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

    log.info(sub1ID + " :messages received");
    log.info(sub2ID + " :messages received");

    assertAll(
            () -> assertThat("Wrong count of messages received: by " + sub1ID, recvd1.size(), is(count)),
            () -> assertThat("Wrong count of messages received: by " + sub2ID, recvd2.size(), is(count)));

    subscriber1.close();
    subscriber2.close();

    session.unsubscribe(sub1ID);
    session.unsubscribe(sub2ID);
}
 
Example 19
Source File: DurableSubscriptionTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
/**
 * JMS 1.1 6.11.1: A client can change an existing durable subscription by creating a durable
 * TopicSubscriber with the same name and a new topic and/or message selector, or NoLocal
 * attribute. Changing a durable subscription is equivalent to deleting and recreating it.
 * <br>
 * Test with a different topic (a redeployed topic is a different topic).
 */
@Test
public void testDurableSubscriptionOnNewTopic() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();

      conn.setClientID("brookeburke");

      Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer prod = s.createProducer(ActiveMQServerTestCase.topic1);
      prod.setDeliveryMode(DeliveryMode.PERSISTENT);

      s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "monicabelucci");

      prod.send(s.createTextMessage("one"));

      conn.close();

      conn = createConnection();

      conn.setClientID("brookeburke");

      s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer durable = s.createDurableSubscriber(ActiveMQServerTestCase.topic2, "monicabelucci");

      conn.start();

      Message m = durable.receiveNoWait();
      ProxyAssertSupport.assertNull(m);

      durable.close();

      s.unsubscribe("monicabelucci");
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}
 
Example 20
Source File: DurableSubscribtionTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that messages are delivered normally to a subscriber on a separate connection despite
 * the use of durable subscriber with no-local on the first connection.
 */
@Test
public void testNoLocalSubscriberAndSubscriberOnSeparateConnection() throws Exception
{
    String noLocalSubscriptionName = getTestName() + "_no_local_sub";
    String subscriobtionName = getTestName() + "_sub";
    Topic topic = createTopic(getTestName());
    final String clientId = "clientId";

    Connection noLocalConnection = getConnectionBuilder().setClientId(clientId).build();
    try
    {
        Connection connection = getConnection();
        try
        {
            Session noLocalSession = noLocalConnection.createSession(true, Session.SESSION_TRANSACTED);
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

            MessageProducer noLocalSessionProducer = noLocalSession.createProducer(topic);
            MessageProducer sessionProducer = session.createProducer(topic);

            try
            {
                TopicSubscriber noLocalSubscriber =
                        noLocalSession.createDurableSubscriber(topic, noLocalSubscriptionName, null, true);
                TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriobtionName, null, false);
                noLocalConnection.start();
                connection.start();

                noLocalSessionProducer.send(noLocalSession.createTextMessage("Message1"));
                noLocalSession.commit();
                sessionProducer.send(session.createTextMessage("Message2"));
                sessionProducer.send(session.createTextMessage("Message3"));
                session.commit();

                Message durableSubscriberMessage = noLocalSubscriber.receive(getReceiveTimeout());
                assertTrue(durableSubscriberMessage instanceof TextMessage);
                assertEquals("Unexpected local message received",
                             "Message2",
                             ((TextMessage) durableSubscriberMessage).getText());
                noLocalSession.commit();

                Message nonDurableSubscriberMessage = subscriber.receive(getReceiveTimeout());
                assertTrue(nonDurableSubscriberMessage instanceof TextMessage);
                assertEquals("Unexpected message received",
                             "Message1",
                             ((TextMessage) nonDurableSubscriberMessage).getText());

                session.commit();
                noLocalSubscriber.close();
                subscriber.close();
            }
            finally
            {
                noLocalSession.unsubscribe(noLocalSubscriptionName);
                session.unsubscribe(subscriobtionName);
            }
        }
        finally
        {
            connection.close();
        }
    }
    finally
    {
        noLocalConnection.close();
    }
}