⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 consumermanager.java

📁 一个java方面的消息订阅发送的源码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/**
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright
 *    statements and notices.  Redistributions must also contain a
 *    copy of this document.
 *
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. The name "Exolab" must not be used to endorse or promote
 *    products derived from this Software without prior written
 *    permission of Exoffice Technologies.  For written permission,
 *    please contact info@exolab.org.
 *
 * 4. Products derived from this Software may not be called "Exolab"
 *    nor may "Exolab" appear in their names without prior written
 *    permission of Exoffice Technologies. Exolab is a registered
 *    trademark of Exoffice Technologies.
 *
 * 5. Due credit should be given to the Exolab Project
 *    (http://www.exolab.org/).
 *
 * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright 2001-2005 (C) Exoffice Technologies Inc. All Rights Reserved.
 *
 * $Id: ConsumerManager.java,v 1.2 2005/03/18 03:58:39 tanderson Exp $
 */
package org.exolab.jms.messagemgr;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jms.InvalidDestinationException;
import javax.jms.InvalidSelectorException;
import javax.jms.JMSException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.exolab.jms.client.JmsDestination;
import org.exolab.jms.client.JmsQueue;
import org.exolab.jms.client.JmsTopic;
import org.exolab.jms.persistence.DatabaseService;
import org.exolab.jms.persistence.PersistenceAdapter;
import org.exolab.jms.persistence.SQLHelper;
import org.exolab.jms.scheduler.Scheduler;
import org.exolab.jms.server.JmsServerSession;
import org.exolab.jms.service.ServiceException;


/**
 * The consumer manager is responsible for creating and managing the lifecycle
 * of consumers. The consumer manager maintains a list of all active consumers.
 *
 * @author <a href="mailto:jima@comware.com.au">Jim Alateras</a>
 * @author <a href="mailto:tma@netspace.net.au">Tim Anderson</a>
 * @version $Revision: 1.2 $ $Date: 2005/03/18 03:58:39 $
 */
public class ConsumerManager {

    /**
     * Maintains a cache of all active endpoints.
     */
    private HashMap _endpoints = new HashMap();

    /**
     * Maintains a list of all unique consumers, durable and non-durable. Each
     * entry has an associated {@link ConsumerEntry} record. All durable
     * subscribers are maintained in memory until they are removed from the
     * system entirely. All non-durable subscribers are maintained in memory
     * until their endpoint is removed.
     */
    private HashMap _consumerCache = new HashMap();

    /**
     * Maintains a mapping between destinations and consumers. A destination can
     * have more than one consumer and a consumer can also be registered to more
     * than one destination
     */
    private HashMap _destToConsumerMap = new HashMap();

    /**
     * Maintains a list of wildcard subscriptions using subscription name and
     * the JmsTopic.
     */
    private HashMap _wildcardConsumers = new HashMap();

    /**
     * Cache a copy of the scheduler instance
     */
    private Scheduler _scheduler = null;

    /**
     * The consumer Id seed to allocate to new consumers
     */
    private long _consumerIdSeed = 0;

    /**
     * The singleton instance of the consumer manager
     */
    private static ConsumerManager _instance = null;

    /**
     * The logger
     */
    private static final Log _log = LogFactory.getLog(ConsumerManager.class);


    /**
     * Create the singleton instance of the consumer manager
     *
     * @return the singleton instance
     * @throws ServiceException if the service cannot be initialised
     */
    public static ConsumerManager createInstance() throws ServiceException {
        _instance = new ConsumerManager();
        return _instance;
    }

    /**
     * Return the singleton instance of the ConsumerManager
     *
     * @return ConsumerManager
     */
    public static ConsumerManager instance() {
        return _instance;
    }

    /**
     * Construct the <code>ConsumerManager</code>
     *
     * @throws ServiceException - if it fails to initialise
     */
    private ConsumerManager() throws ServiceException {
        init();
    }

    /**
     * This method creates an actual durable consumer for the specified and
     * caches it. It does not create and endpoint. To create the endpoint the
     * client should call createDurableConsumerEndpoint.
     *
     * @param topic the topic destination
     * @param name  the consumer name
     * @throws JMSException if it cannot be created
     */
    public synchronized void createDurableConsumer(JmsTopic topic, String name)
            throws JMSException {

        PersistenceAdapter adapter = DatabaseService.getAdapter();

        Connection connection = null;
        try {

            connection = DatabaseService.getConnection();

            // ensure that we are trying to create a durable consumer to an
            // administered destination.
            if (!adapter.checkDestination(connection, topic.getName())) {
                throw new JMSException("Cannot create durable consumer, name="
                                       + name
                                       + ", for non-administered topic="
                                       + topic.getName());
            }

            if (!adapter.durableConsumerExists(connection, name)) {
                adapter.addDurableConsumer(connection, topic.getName(), name);
            }

            connection.commit();
            // cache the consumer locally
            addToConsumerCache(name, topic, true);
        } catch (JMSException exception) {
            throw exception;
        } catch (Exception exception) { // PersistenceException, SQLException
            SQLHelper.rollback(connection);
            String msg = "Failed to create durable consumer, name=" + name
                    + ", for topic=" + topic.getName();
            _log.error(msg, exception);
            throw new JMSException(msg + ": " + exception.getMessage());
        } finally {
            SQLHelper.close(connection);
        }
    }


    /**
     * This method will remove the durable consumer from the database and from
     * transient memory only if it exists and is inactive. If there is an active
     * endpoint then it cannot be deleted and an exception will be raise.
     * <p/>
     * If the durable consumer does not exist then an exception is also raised.
     *
     * @param name - the consumer name
     * @throws JMSException - if it cannot be removed
     */
    public synchronized void removeDurableConsumer(String name)
            throws JMSException {
        if (_log.isDebugEnabled()) {
            _log.debug("removeDurableConsumer(name=" + name + ")");
        }

        // check to see that the durable consumer exists
        if (!durableConsumerExists(name)) {
            throw new JMSException("Durable consumer " + name
                                   + " is not defined.");
        }
        if (isDurableConsumerActive(name)) {
            throw new JMSException("Cannot remove durable consumer=" + name
                                   + ": consumer is active");
        }

        // remove it from the persistent store.
        Connection connection = null;
        try {
            connection = DatabaseService.getConnection();

            DatabaseService.getAdapter().removeDurableConsumer(connection,
                                                               name);
            // if it has been successfully removed from persistent store then
            // clear up the transient references.
            ConsumerEndpoint endpoint = getConsumerEndpoint(name);
            if (endpoint != null) {
                deleteConsumerEndpoint(endpoint);
            }
            removeFromConsumerCache(name);
            connection.commit();
        } catch (Exception exception) { // PersistenceException, SQLException
            SQLHelper.rollback(connection);
            String msg = "Failed to remove durable consumer, name=" + name;
            _log.error(msg, exception);
            throw new JMSException(msg + ":" + exception.getMessage());
        } finally {
            SQLHelper.close(connection);
        }
    }

    /**
     * This method will remove all the durable consumers from the database and
     * from transient memory whether they are active or not.
     * <p/>
     * If we have problems removing the durable consumers then throw the
     * JMSException.
     *
     * @param topic the topic to remove consumers for
     * @throws JMSException if the consumers cannot be removed
     */
    public synchronized void removeDurableConsumers(JmsDestination topic)
            throws JMSException {

        List consumers = (List) _destToConsumerMap.get(topic);
        if (consumers != null) {
            Iterator iterator = consumers.iterator();
            while (iterator.hasNext()) {
                ConsumerEntry entry = (ConsumerEntry) iterator.next();
                if (entry.isDurable()) {
                    // remove the actual durable consumer from transient and
                    // secondary memory.
                    removeDurableConsumer(entry.getName());
                }
            }
        }

        // remove all consumers for the specified destination
        removeFromConsumerCache(topic);
    }

    /**
     * Create a transient consumer for the specified destination
     *
     * @param destination the destination to consume messages from
     * @param selector    the message selector. May be <code>null</code>
     * @param noLocal     if true, and the destination is a topic, inhibits the
     *                    delivery of messages published by its own connection.
     *                    The behavior for <code>noLocal</code> is not specified
     *                    if the destination is a queue.
     * @return a new transient consumer
     */
    public synchronized ConsumerEndpoint createConsumerEndpoint(
            JmsServerSession session, JmsDestination destination,
            String selector, boolean noLocal)
            throws JMSException, InvalidSelectorException {

        if (_log.isDebugEnabled()) {
            _log.debug("createConsumerEndpoint(session=" + session
                       + ", destination=" + destination
                       + ", selector=" + selector
                       + ", noLocal=" + noLocal + ")");
        }

        ConsumerEndpoint endpoint = null;

        // ensure that the destination is valid before proceeding
        checkDestination(destination);

        long consumerId = getNextConsumerId();

        // determine what type of consumer endpoint to create based on
        // the destination it subscribes to.

        if (destination instanceof JmsTopic) {
            JmsTopic topic = (JmsTopic) destination;
            endpoint
                    = new TopicConsumerEndpoint(consumerId, session, topic,
                                                selector, noLocal, _scheduler);
        } else if (destination instanceof JmsQueue) {
            endpoint = new QueueConsumerEndpoint(consumerId, session,
                                                 (JmsQueue) destination,
                                                 selector, _scheduler);
        }

        if (endpoint != null) {
            // add it to the list of managed consumers. If it has a persistent
            // identity, use that as the key, otherwise use its transient
            // identity.
            Object key = ConsumerEntry.getConsumerKey(endpoint);
            _endpoints.put(key, endpoint);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -