Example usage for javax.jms TopicSubscriber close

List of usage examples for javax.jms TopicSubscriber close

Introduction

In this page you can find the example usage for javax.jms TopicSubscriber close.

Prototype


void close() throws JMSException;

Source Link

Document

Closes the message consumer.

Usage

From source file:org.carewebframework.jms.GlobalEventDispatcher.java

/**
 * Remove all remote subscriptions.//  w w  w  .j a  v  a2 s. c  om
 */
private void removeSubscriptions() {
    for (final TopicSubscriber subscriber : this.subscribers.values()) {
        try {
            subscriber.close();
        } catch (final Throwable e) {
            log.debug("Error closing subscriber", e);//is level appropriate - previously hidden exception -afranken
        }
    }

    this.subscribers.clear();
}

From source file:org.carewebframework.jms.GlobalEventDispatcher.java

/**
 * Removes an event subscription with the global event manager.
 * //from w w w  . j a va 2 s.c  o  m
 * @param eventName Name of event
 * @throws JMSException JMS exception.
 */
private void doHostUnsubscribe(final String eventName) throws JMSException {
    final TopicSubscriber subscriber = this.subscribers.remove(eventName);
    if (subscriber == null) {
        return;
    }
    log.debug(String.format("Unsubscribing Subscriber[%s] for Topic [%s].", subscriber, eventName));
    subscriber.close();
}

From source file:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void unsubscribe(final String topicName) {
    String topicName2 = null;/*from w  ww.  ja  va 2  s .c o m*/
    checkArgument(isNotBlank(topicName2 = trimToEmpty(topicName)), "Uninitialized or invalid topic");
    mutex.lock();
    try {
        boolean found = false;
        final Iterator<TopicSubscriber> it = subscribers.iterator();
        while (it.hasNext() && !found) {
            try {
                final TopicSubscriber subscriber = it.next();
                if (topicName2.equals(subscriber.getTopicName())) {
                    subscriber.close();
                    it.remove();
                    found = true;
                }
            } catch (Exception ignore) {
            }
        }
    } finally {
        mutex.unlock();
    }
}

From source file:org.aludratest.service.jms.impl.JmsActionImpl.java

public void close() {
    LOGGER.info("Closing JmsServcie for clientId " + this.clientId);
    for (TopicSubscriber subscriber : this.durableConsumers.values()) {
        try {/*  ww w .j  a v  a 2 s . co  m*/
            subscriber.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close subscriber: ", e);
        }
    }
    for (Map.Entry<String, Connection> entry : this.dynamicConnections.entrySet()) {
        try {
            Connection dynC = entry.getValue();
            dynC.stop();
            dynC.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close dynamic connection [ " + entry.getKey() + " ] : ", e);
        }
    }
    if (session != null) {
        try {
            session.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close jms session : ", e);
        }
    }
    if (connection != null) {
        try {
            connection.stop();
            connection.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close jms connection for client-id [ " + this.clientId + " ] : ", e);
        }
    }
}

From source file:org.aludratest.service.jms.impl.JmsActionImpl.java

@Override
public void unsubscribeTopic(@TechnicalArgument String subscriptionName) throws JMSException {
    if (StringUtils.isEmpty(clientId)) {
        throw new IllegalArgumentException("Client-Id must be provided to unsubscribe");
    }//from ww  w .  j  a  v  a  2 s.co m
    LOGGER.debug("Unsubscribing from subscription " + subscriptionName);
    Connection c = getDynamicConnection(subscriptionName);
    c.stop();

    TopicSubscriber subscriber = this.durableConsumers.get(subscriptionName);
    if (subscriber != null) {
        subscriber.close();
        c.createSession(false, Session.AUTO_ACKNOWLEDGE).unsubscribe(subscriptionName);
        this.durableConsumers.remove(subscriptionName);
    }
    c.close();
    this.dynamicConnections.remove(c);

}

From source file:org.apache.activemq.bugs.AMQ6131Test.java

@Test(timeout = 300000)
public void testDurableWithOnePendingAfterRestartAndIndexRecovery() throws Exception {
    final File persistentDir = getPersistentDir();

    broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"),
            false);//w  w  w . j  av  a2s  . c  om

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("myId");
    connection.start();
    final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");
    final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub"));

    final int original = new ArrayList<File>(
            FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE))
                    .size();

    // 100k messages
    final byte[] data = new byte[100000];
    final Random random = new Random();
    random.nextBytes(data);

    // run test with enough messages to create a second journal file
    final AtomicInteger messageCount = new AtomicInteger();
    assertTrue("Should have added a journal file", Wait.waitFor(new Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            final ActiveMQBytesMessage message = new ActiveMQBytesMessage();
            message.setContent(new ByteSequence(data));

            for (int i = 0; i < 100; i++) {
                producer.send(message);
                messageCount.getAndIncrement();
            }

            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() > original;
        }
    }));

    // Consume all but 1 message
    for (int i = 0; i < messageCount.get() - 1; i++) {
        durable.receive();
    }

    durable.close();

    // wait until a journal file has been GC'd after receiving messages
    assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1;
        }
    }));

    // force a GC of unneeded journal files
    getBroker().getPersistenceAdapter().checkpoint(true);

    // wait until a journal file has been GC'd after receiving messages
    assertFalse("Should not have garbage collected", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() == original;
        }
    }, 5000, 500));

    // stop the broker so we can blow away the index
    getBroker().stop();
    getBroker().waitUntilStopped();

    // delete the index so that the durables are gone from the index
    // The test passes if you take out this delete section
    for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"),
            TrueFileFilter.INSTANCE)) {
        FileUtils.deleteQuietly(index);
    }

    stopBroker();
    setUpBroker(false);

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

    ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection();
    connection2.setClientID("myId");
    connection2.start();
    final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");

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

    assertNotNull(durable2.receive(5000));
}

From source file:org.apache.activemq.bugs.AMQ6131Test.java

@Test(timeout = 300000)
public void testDurableWithNoMessageAfterRestartAndIndexRecovery() throws Exception {
    final File persistentDir = getPersistentDir();

    broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"),
            false);//from   w  w w  . j a v  a  2  s  .  co m

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("myId");
    connection.start();
    final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");
    final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub"));

    final int original = new ArrayList<File>(
            FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE))
                    .size();

    // 100k messages
    final byte[] data = new byte[100000];
    final Random random = new Random();
    random.nextBytes(data);

    // run test with enough messages to create a second journal file
    final AtomicInteger messageCount = new AtomicInteger();
    assertTrue("Should have added a journal file", Wait.waitFor(new Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            final ActiveMQBytesMessage message = new ActiveMQBytesMessage();
            message.setContent(new ByteSequence(data));

            for (int i = 0; i < 100; i++) {
                producer.send(message);
                messageCount.getAndIncrement();
            }

            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() > original;
        }
    }));

    // Consume all messages
    for (int i = 0; i < messageCount.get(); i++) {
        durable.receive();
    }

    durable.close();

    assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1;
        }
    }));

    // force a GC of unneeded journal files
    getBroker().getPersistenceAdapter().checkpoint(true);

    // wait until a journal file has been GC'd after receiving messages
    assertTrue("Should have garbage collected", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() == original;
        }
    }));

    // stop the broker so we can blow away the index
    getBroker().stop();
    getBroker().waitUntilStopped();

    // delete the index so that the durables are gone from the index
    // The test passes if you take out this delete section
    for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"),
            TrueFileFilter.INSTANCE)) {
        FileUtils.deleteQuietly(index);
    }

    stopBroker();
    setUpBroker(false);

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

    ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection();
    connection2.setClientID("myId");
    connection2.start();
    final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");

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

    assertNull(durable2.receive(500));
}

From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private void registerDurableSubscription() throws JMSException {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.setClientID(clientID);/* w w w  .j  a v  a2 s  . co m*/
    TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = topicSession.createTopic(topicName);
    TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName);
    connection.start();
    durableSubscriber.close();
    connection.close();
    LOG.info("Durable Sub Registered");
}

From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();

    connection.setClientID(clientID);//from ww w  . j  a  va2 s  .c o  m
    TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = topicSession.createTopic(topicName);
    connection.start();
    TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName);
    LOG.info("About to receive messages");
    Message message = subscriber.receive(120000);
    subscriber.close();
    connection.close();
    LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done");

    return message;
}

From source file:org.apache.stratos.adc.topology.mgt.subscriber.TopologySubscriber.java

public static void subscribe(String topicName) {
    Properties initialContextProperties = new Properties();
    TopicSubscriber topicSubscriber = null;
    TopicSession topicSession = null;//from ww w . ja v  a2 s .  com
    TopicConnection topicConnection = null;
    InitialContext initialContext = null;

    initialContextProperties.put("java.naming.factory.initial",
            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");

    String mbServerIp = System.getProperty(TopologyConstants.MB_SERVER_IP) == null
            ? TopologyConstants.DEFAULT_MB_SERVER_IP
            : System.getProperty(TopologyConstants.MB_SERVER_IP);

    String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" + mbServerIp
            + "'&reconnect='true'";
    initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);

    try {
        initialContext = new InitialContext(initialContextProperties);
        TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext
                .lookup("qpidConnectionfactory");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = topicSession.createTopic(topicName);
        topicSubscriber = topicSession.createSubscriber(topic);

        topicSubscriber.setMessageListener(new TopologyListener());

    } catch (Exception e) {
        log.error(e.getMessage(), e);

        try {
            if (topicSubscriber != null) {
                topicSubscriber.close();
            }

            if (topicSession != null) {
                topicSession.close();
            }

            if (topicConnection != null) {
                topicConnection.close();
            }
        } catch (JMSException e1) {
            // ignore
        }

    } finally {
        // start the health checker
        Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
        healthChecker.start();
    }
}