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

📄 jmsmessageconsumer.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 2000-2004 (C) Exoffice Technologies Inc. All Rights Reserved.
 *
 * $Id: JmsMessageConsumer.java,v 1.37 2004/01/20 14:14:21 tanderson Exp $
 */
package org.exolab.jms.client;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;

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

import org.exolab.jms.message.MessageImpl;


/**
 * Client implementation of the <code>javax.jms.MessageConsumer</code>
 * interface
 *
 * @version     $Revision: 1.37 $ $Date: 2004/01/20 14:14:21 $
 * @author      <a href="mailto:jima@comware.com.au">Jim Alateras</a>
 * @author      <a href="mailto:tma@netspace.net.au">Tim Anderson</a>
 */
abstract class JmsMessageConsumer
    implements MessageListener, MessageConsumer {

    /**
     * A message listener may be assigned to this session, for
     * asynchronous message delivery.
     */
    private MessageListener _messageListener = null;

    /**
     * The session which created this
     */
    private JmsSession _session = null;

    /**
     * The message selector, for filtering messages. May be <code>null</code>
     */
    private String _selector = null;

    /**
     * Indicates if the session is closed
     */
    private volatile boolean _closed = false;

    /**
     * The consumer's identity, allocated by the session
     */
    private long _clientId = -1;

    /**
     * This is the last time that the listener had been set through
     * {@link #setMessageListener}
     */
    private long _listenerSetTimestamp = 0;

    /**
     * This is the last message id asynchronously delivered to the listener.
     */
    private String _lastMessageDelivered;

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


    /**
     * Construct a new <code>JmsMessageProducer</code>.
     *
     * @param session the session responsible for the consumer
     * @param clientId the session allocated consumer identifier
     * @param selector the message selector. May be <code>null</code
     */
    public JmsMessageConsumer(JmsSession session, long clientId,
                              String selector) {
        if (session ==  null) {
            throw new IllegalArgumentException("Argument 'session' is null");
        }
        _session = session;
        _clientId = clientId;
        _selector = selector;
    }

    /**
     * Return the session allocated consumer identifier
     *
     * @return the identifier allocated to this by the session
     */
    public long getClientId() {
        return _clientId;
    }

    /**
     * Return the message consumer's message selector expression
     *
     * @return the selector expression, or <code>null</code> if one isn't set
     */
    public String getMessageSelector() {
        return _selector;
    }

    /**
     * Return the consumer's listener
     *
     * @return the listener for the consumer, or <code>null</code> if there
     * isn't one set
     */
    public MessageListener getMessageListener() {
        return _messageListener;
    }

    /**
     * Set the consumer's listener
     *
     * @param listener the message listener, or <code>null</code> to deregister
     * an existing listener
     * @throws JMSException if the listener cannot be set
     */
    public void setMessageListener(MessageListener listener)
        throws JMSException {
        // if listener is not null then enable asynchronous delivery
        // otherwise disable it
        if (listener != null) {
            if (_messageListener == null) {
                // previously asynchronouse messaging was disabled
                _listenerSetTimestamp = System.currentTimeMillis();
                _messageListener = listener;
                _session.setMessageListener(this);
            } else {
                // asynch message deliver is enabled, just changing the
                // client side receiving entity.
                _messageListener = listener;
            }
        } else {
            if (_messageListener != null) {
                _session.removeMessageListener(this);
                _messageListener = listener;
            }
        }

        // reset the lastMessageDelivered regardless what the value
        // of the listener is.
        _lastMessageDelivered = null;
    }

    /**
     * Receive the next message produced for this consumer.
     * This call blocks indefinitely until a message is produced or until
     * this message consumer is closed.
     *
     * @return the next message produced for this consumer, or
     * <code>null</code> if this consumer is concurrently closed
     * @throws JMSException if the next message can't be received
     */
    public Message receive() throws JMSException {
        return retrieveMessage(0);
    }

    /**
     * Receive the next message that arrives within the specified
     * timeout interval.
     * This call blocks until a message arrives, the timeout expires, or this
     * message consumer is closed. A timeout of zero never expires and the call
     * blocks indefinitely.
     *
     * @param timeout the timeout interval, in milliseconds
     * @return the next message produced for this consumer, or
     * <code>null</code> if the timeout expires or the consumer concurrently
     * closed
     * @throws JMSException if the next message can't be received
     */
    public Message receive(long timeout) throws JMSException {
        return retrieveMessage(timeout);
    }

    /**
     * Receive the next message if one is immediately available
     *
     * @return the next message produced for this consumer, or
     * <code>null</code> if one is not available
     * @throws JMSException if the next message can't be received
     */
    public Message receiveNoWait() throws JMSException {
        return retrieveMessage(-1);
    }

    /**
     * Close the consumer.
     * This call blocks until a receive or message listener in progress has
     * completed. A blocked consumer receive call returns <code>null</code>
     * when this consumer is closed.
     *
     * @throws JMSException if this consumer can't be closed
     */
    public synchronized void close() throws JMSException {
        _closed = true;

        // wake up any blocked threads and let them complete
        notifyAll();

        _messageListener = null;
        _session = null;
        _selector = null;
    }

    /**
     * Release all resources used by this consumer
     *
     * @throws JMSException if this consumer can't be destroyed
     */
    public synchronized void destroy() throws JMSException {
        _closed = true;

        // wake up any blocked threads and let them complete
        notifyAll();

        _messageListener = null;
        _session = null;
        _selector = null;
    }

    /**
     * Handles messages received asynchronously via the owning session,
     * passing them to the registered listener
     *
     * @param message the message received
     */
    public synchronized void onMessage(Message message) {
        try {
            if (_messageListener != null) {
                // drop all messages if they were received before the listener
                // had been set.
                long rcvd = message.getLongProperty("JMSXRcvTimestamp");
                if (rcvd < _listenerSetTimestamp) {
                    return;
                }

                // According to section 4.5.2 Asynchronous Delivery messages
                // delivered to consumers, through the MessageListener
                // interface in a transacted session must be treated the same
                // as synchronous delivery.
                // Need to set this field before we actually deliver the
                // message since the client can actually call
                // setMessageListener in onMessage()
                _lastMessageDelivered = ((MessageImpl) message).getId();
                _messageListener.onMessage(message);
            }
        } catch (JMSException exception) {
            //report the exception
            _log.error("Error in onMessage", exception);
        }
    }

    /**
     * Retrieve the next message for the consumer.
     *
     * @param wait the maximum time to wait for a message, in milliseconds.
     * If <code>-1</code>, don't wait, if <code>0</code> wait indefinitely,
     * otherwise wait the specified time.
     * @return the received message, or <code>null</code>, if no message is
     * available
     * @throws JMSException if an error occurs retrieving the message,
     * the session is closed, or a message listener is set.
     */
    public Message retrieveMessage(long wait) throws JMSException {
        if (_messageListener != null) {
            // cannot call this method when a listener is defined
            throw new JMSException("Can't receive when listener defined");
        }

        if (_closed) {
            // cannot call this method when a listener is defined
            throw new JMSException("Can't receive when session closed");
        }

        MessageImpl message =
            (MessageImpl) _session.retrieveMessage(_clientId, wait);
        if (message != null) {
            _lastMessageDelivered = message.getId();
        }

        return message;
    }

    /**
     * Return the last message asynchronously delivered to the consumer
     *
     * @return the last message delivered
     */
    public String getLastMessageDelivered() {
        return _lastMessageDelivered;
    }

    /**
     * Determines if the consumer is closed
     *
     * @return <code>true</code> if the consumer is closed
     */
    public boolean isClosed() {
        return _closed;
    }

    /**
     * Returns the session that created this consumer
     *
     * @return the session that created this consumer
     */
    protected JmsSession getSession() {
        return _session;
    }

}

⌨️ 快捷键说明

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