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

📄 sentmessagecache.java

📁 实现了Jms的服务器源码,支持多种适配器,DB,FTP,支持多种数据库
💻 JAVA
字号:
/**
 * 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 2002-2003 (C) Exoffice Technologies Inc. All Rights Reserved.
 *
 * $Id: SentMessageCache.java,v 1.5 2003/08/07 13:33:08 tanderson Exp $
 *
 * Date         Author     Changes
 * 30/12/2002   tanderson  Extracted from JmsServerSession
 */
package org.exolab.jms.server;

import java.sql.Connection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.jms.Session;

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.message.MessageHandle;
import org.exolab.jms.message.MessageId;
import org.exolab.jms.messagemgr.ConsumerManager;
import org.exolab.jms.messagemgr.DestinationManager;
import org.exolab.jms.messagemgr.MessageHandleFactory;
import org.exolab.jms.messagemgr.PersistentMessageHandle;
import org.exolab.jms.messagemgr.QueueDestinationCache;
import org.exolab.jms.messagemgr.TopicConsumerEndpoint;
import org.exolab.jms.persistence.DatabaseService;
import org.exolab.jms.persistence.PersistenceException;


/**
 * Helper class to cache all sent messages and unacked messages for a
 * session. It also does some other processing like marking the message
 * as sent to minimize the number of transactions.
 * <p>
 * Messages will only be added to the cache, if the session is transacted
 * or the ack mode for the session is set to CLIENT_ACKNOWLEDGE
 *
 * @version     $Revision: 1.5 $ $Date: 2003/08/07 13:33:08 $
 * @author      <a href="mailto:jima@exoffice.com">Jim Alateras</a>
 * @author      <a href="mailto:tma@netspace.net.au">Tim Anderson</a>
 * @see         JmsServerSession
 */
class SentMessageCache {

    /**
     * The session which owns this instance
     */
    private JmsServerSession _session;

    /**
     * Holds a list of unacked messages in the order they were sent
     */
    private List _unackedMessages = Collections.synchronizedList(
        new LinkedList());

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


    /**
     * Construct a new <code>SentMessageCache</code>
     *
     * @param session the session which manages this
     */
    public SentMessageCache(JmsServerSession session) {
        _session = session;
    }

    /**
     * Mark the message as delivered and do one of the following.
     * <p>
     * If the session is transacted or the session ack mode is set to
     * CLIENT_ACKNOWLEDGE then add this message to the list of unacked
     * messages.
     * <p>
     * If the session ack mode is anything else then destroy the handle.
     * <p>
     * If the handle is a reference to a persistent message then conduct
     * this work in the context of a transaction.
     *
     * @param handle the message handle that should be acked
     */
    public void process(MessageHandle handle) {
        if (handle instanceof PersistentMessageHandle) {
            PersistentMessageHandle phandle = (PersistentMessageHandle) handle;
            Connection connection = null;
            try {
                connection = DatabaseService.getConnection();

                phandle.setDelivered(true);
                if (_session.isTransacted() ||
                    _session.getAckMode() == Session.CLIENT_ACKNOWLEDGE) {
                    _unackedMessages.add(handle);
                    MessageHandleFactory.updatePersistentHandle(
                        connection, phandle);
                } else {
                    // in all other ack modes, simply destroy the handle
                    MessageHandleFactory.destroyPersistentHandle(
                        connection, phandle);
                }
                connection.commit();
            } catch (PersistenceException exception) {
                if (connection != null) {
                    try {
                        connection.rollback();
                    } catch (Exception ignore) {
                    }
                }
                _log.error("Error in SentMessageCache.process", exception);
            } catch (Exception exception) {
                _log.error("Error in SentMessageCache.process", exception);
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (Exception ignore) {
                    }
                }
            }
        } else {
            handle.setDelivered();
            if (_session.isTransacted() ||
                _session.getAckMode() == Session.CLIENT_ACKNOWLEDGE) {
                _unackedMessages.add(handle);
            } else {
                handle.destroy();
            }
        }
    }

    /**
     * Acknowledge the specified messages in the cache and all previously
     * sent messages.
     *
     * @param msgid the message id of the message to ack
     * @param clientid the client id that sent the ack.
     */
    public void acknowledgeMessage(MessageId msgid, long clientid) {
        // first check that the message exists in the list of unacked
        // messages
        boolean exists = false;
        Iterator iterator = _unackedMessages.iterator();
        while (iterator.hasNext()) {
            MessageHandle handle = (MessageHandle) iterator.next();
            if (handle.getClientId() == clientid &&
                handle.getMessageId().equals(msgid)) {
                exists = true;
                break;
            }
        }

        if (exists) {
            boolean intransaction = false;
            Connection connection = null;

            try {
                // start from the top of the cache and remove each
                // message and then call destroy on it.
                // We should do this in one transaction.
                while (!_unackedMessages.isEmpty()) {
                    MessageHandle handle =
                        (MessageHandle) _unackedMessages.remove(0);
                    if (handle instanceof PersistentMessageHandle) {
                        if (!intransaction) {
                            connection = DatabaseService.getConnection();

                            // begin the transaction
                            intransaction = true;
                        }
                        MessageHandleFactory.destroyPersistentHandle(
                            connection, (PersistentMessageHandle) handle);
                    } else {
                        handle.destroy();
                    }

                    // if the handle is equal to the source handle then
                    // break the loop
                    if (handle.getClientId() == clientid &&
                        handle.getMessageId().equals(msgid)) {
                        if (intransaction) {
                            connection.commit();
                            intransaction = false;
                        }
                        break;
                    }
                }
            } catch (PersistenceException exception) {
                if (connection != null) {
                    try {
                        connection.rollback();
                    } catch (Exception ignore) {
                    }
                }
                _log.error("Error in SentMessageCache.acknowledgeMessage",
                    exception);
            } catch (Exception exception) {
                _log.error("Error in SentMessageCache.acknowledgeMessage",
                    exception);
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (Exception ignore) {
                    }
                }
            }
        }
    }

    /**
     * Acknowledge all the messages in the cache
     */
    public void acknowledgeAllMessages() {
        boolean intransaction = false;
        Connection connection = null;

        try {
            // start from the top of the cache and remove each
            // message and then call destroy on it.
            // We should do this in one transaction.
            while (!_unackedMessages.isEmpty()) {
                MessageHandle handle =
                    (MessageHandle) _unackedMessages.remove(0);
                if (handle instanceof PersistentMessageHandle) {
                    if (!intransaction) {
                        connection = DatabaseService.getConnection();
                        intransaction = true;
                    }
                    MessageHandleFactory.destroyPersistentHandle(
                        connection, (PersistentMessageHandle) handle);
                } else {
                    handle.destroy();
                }
            }

            if (intransaction) {
                connection.commit();
                intransaction = false;
            }
        } catch (PersistenceException exception) {
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (Exception ignore) {
                }
            }
            _log.error("Error in SentMessageCache.acknowledgeMessage",
                exception);
        } catch (Exception exception) {
            _log.error("Error in SentMessageCache.acknowledgeMessage",
                exception);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ignore) {
                }
            }
        }
    }

    /**
     * Clear the cache by removing each entry and doing one of the
     * following.
     * <p>
     * If the entry is for a queue destination then return it to
     * the appropriate destination cache. If the cache does not
     * exist, because it may have been garbage collected then we
     * need to recreated.
     * <p>
     * If the entry is for a topic destination and check if the
     * corresponding endpoint is still active. If it is then return it
     * to the endpoint, otherwise do nothing.
     */
    public void clear() {
        // copy the array of unacked messages
        Object[] unacked = _unackedMessages.toArray();
        _unackedMessages.clear();

        int count = unacked.length;
        for (int index = 0; index < count; index++) {
            MessageHandle handle = (MessageHandle) unacked[index];
            JmsDestination dest = handle.getDestination();

            if (dest instanceof JmsTopic) {
                ConsumerManager conmgr = ConsumerManager.instance();
                long clientId = handle.getClientId();
                TopicConsumerEndpoint endpoint = (TopicConsumerEndpoint)
                    _session.getConsumerEndpoint(clientId);
                // if the endpoint is still active then return the message
                // back to it
                if (endpoint != null) {
                    endpoint.returnMessage(handle);
                }
            } else if (dest instanceof JmsQueue) {
                DestinationManager destmgr = DestinationManager.instance();
                QueueDestinationCache cache = (QueueDestinationCache)
                    destmgr.getDestinationCache(dest);

                // if the cache does not exist, because it has been garbage
                // collected, recreate it
                if (cache == null) {
                    cache = (QueueDestinationCache)
                        destmgr.createDestinationCache(dest);
                    // make sure that one has been created, although this
                    // shouldn't really fail
                    if (cache != null) {
                        cache.returnMessage(handle);
                    } else {
                        _log.error("Failed to return message " + handle
                            + " to destination cache " + dest);
                    }
                } else {
                    // return the message
                    cache.returnMessage(handle);
                }
            }
        }
    }

    /**
     * Check whether the specified handle is in the list of unacked
     * messages
     *
     * @param handle the handle to check
     * @return <code>true</code> if it is in the list of unacked messages
     */
    public boolean handleInCache(MessageHandle handle) {
        return _unackedMessages.contains(handle);
    }

    /**
     * Remove the specified handle from the cache
     *
     * @param handle the handle to remove
     */
    public void removeHandle(MessageHandle handle) {
        _unackedMessages.remove(handle);
    }

} //-- SentMessageCache

⌨️ 快捷键说明

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