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

📄 jmsserversession.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 2000-2004 (C) Exoffice Technologies Inc. All Rights Reserved.
 *
 * $Id: JmsServerSession.java,v 1.2 2005/03/18 04:07:02 tanderson Exp $
 */
package org.exolab.jms.server;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.jms.DeliveryMode;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;

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

import org.exolab.jms.client.JmsDestination;
import org.exolab.jms.client.JmsMessageListener;
import org.exolab.jms.client.JmsQueue;
import org.exolab.jms.client.JmsTopic;
import org.exolab.jms.message.MessageImpl;
import org.exolab.jms.messagemgr.ConsumerEndpoint;
import org.exolab.jms.messagemgr.ConsumerManager;
import org.exolab.jms.messagemgr.DestinationManager;
import org.exolab.jms.messagemgr.ConsumerEndpointListener;
import org.exolab.jms.messagemgr.MessageHandle;
import org.exolab.jms.messagemgr.MessageMgr;
import org.exolab.jms.messagemgr.QueueBrowserEndpoint;
import org.exolab.jms.messagemgr.ResourceManager;
import org.exolab.jms.messagemgr.ResourceManagerException;
import org.exolab.jms.server.ServerSession;
import org.exolab.jms.server.JmsServerConnection;
import org.exolab.jms.server.SentMessageCache;


/**
 * A session represents a server side endpoint to the JMSServer. A client can
 * create producers, consumers and destinations through the session in addi-
 * tion to other functions. A session has a unique identifer which is a comb-
 * ination of clientId-connectionId-sessionId.
 * <p/>
 * A session represents a single-threaded context which implies that it cannot
 * be used with more than one thread concurrently. Threads registered with this
 * session are synchronized.
 * <p/>
 * Finally, instances of this object can only be created by classes within the
 * same package.
 *
 * @author <a href="mailto:jima@exoffice.com">Jim Alateras</a>
 * @author <a href="mailto:tma@netspace.net.au">Tim Anderson</a>
 * @version $Revision: 1.2 $ $Date: 2005/03/18 04:07:02 $
 * @see JmsServerConnection
 */
public class JmsServerSession
        implements ServerSession, ConsumerEndpointListener, XAResource {

    /**
     * Back pointer to the connection that created this session. This is set
     * during object creation time
     */
    private JmsServerConnection _connection = null;

    /**
     * Maintain a set of ConsumerEndpoint instances, keyed on id
     */
    private HashMap _consumers = new HashMap();

    /**
     * The message listener is the reference to a remote client that will
     * receive the messages
     */
    private JmsMessageListener _listener = null;

    /**
     * This is the acknowledgement mode for the session
     */
    private int _ackMode = Session.AUTO_ACKNOWLEDGE;

    /**
     * Indicates whether the session is transactional
     */
    private boolean _transacted = false;

    /**
     * Holds the current xid that this session is associated with. A session can
     * olny be associated with one xid at any one time.
     */
    private Xid _xid = null;

    /**
     * Indicates if the underlying connection of this session has been stopped
     */
    private boolean _stopped = true;

    /**
     * Indicated that the session has been closed
     */
    private boolean _closed = false;

    /**
     * Caches all sent messages
     */
    private SentMessageCache _sentMessageCache;

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


    /**
     * Construct a new <code>JmsServerSession</code>
     *
     * @param connection the connection that created this session
     * @param ackMode    the acknowledgement mode for the session
     * @param transacted <code>true</code> if the session is transactional
     */
    public JmsServerSession(JmsServerConnection connection, int ackMode,
                               boolean transacted) {
        _connection = connection;
        _ackMode = ackMode;
        _transacted = transacted;
        _stopped = true;
        _sentMessageCache = new SentMessageCache(this);
    }

    /**
     * Returns the identifier of the connection that created this session
     *
     * @return the connection identifier
     */
    public long getConnectionId() {
        return _connection.getConnectionId();
    }

    /**
     * Acknowledge that a message has been processed
     *
     * @param consumerId the identity of the consumer performing the ack
     * @param messageId  the message identifier
     * @throws JMSException for any error
     */
    public void acknowledgeMessage(long consumerId, String messageId)
            throws JMSException {
        _sentMessageCache.acknowledgeMessage(messageId, consumerId);
    }

    /**
     * Send a message
     *
     * @param message the message to send
     * @throws JMSException for any error
     */
    public void send(MessageImpl message) throws JMSException {
        if (message == null) {
            throw new JMSException("Message is null");
        }

        try {
            // check the delivery mode of the message
            checkDeliveryMode((MessageImpl) message);

            // set the connection identity and then let the message manager
            // process it
            ((MessageImpl) message).setConnectionId(_connection.getConnectionId());

            // if there is a global transaction currently in process then
            // we must send the message to the resource manager, otherwise
            // send it directly to the message manager
            if (_xid != null) {
                ResourceManager.instance().logPublishedMessage(_xid,
                                                               (MessageImpl) message);
            } else {
                MessageMgr.instance().add((MessageImpl) message);
            }
        } catch (JMSException exception) {
            _log.error("Failed to process message", exception);
            throw exception;
        } catch (OutOfMemoryError exception) {
            String msg =
                    "Failed to process message due to out-of-memory error";
            _log.error(msg, exception);
            throw new JMSException(msg);
        } catch (Exception exception) {
            String msg = "Failed to process message";
            _log.error(msg, exception);
            throw new JMSException(msg);
        }
    }

    /**
     * Send a set of messages
     *
     * @param messages a list of <code>MessageImpl</code> instances
     * @throws JMSException for any JMS error
     */
    public void send(List messages) throws JMSException {
        if (messages == null) {
            throw new JMSException("Argument 'messages' is null");
        }

        Iterator iterator = messages.iterator();
        while (iterator.hasNext()) {
            MessageImpl message = (MessageImpl) iterator.next();
            send(message);
        }
    }

    /**
     * Return the next available message to the specified consumer.
     * <p/>
     * The <code>wait</code> parameter indicates how many milliseconds to wait
     * for a message before returning. If <code>wait</code> is <code>0</code>
     * then do not wait. If <code>wait</code> is <code>-1</code> then wait
     * indefinitely for the next message.
     *
     * @param consumerId the consumer identifier
     * @param wait       number of milliseconds to wait
     * @return the next message or <code>null</code>
     * @throws JMSException for any JMS error
     */
    public MessageImpl receive(long consumerId, long wait)
            throws JMSException {
        MessageImpl message = null;
        ConsumerEndpoint consumer = getConsumerEndpoint(consumerId);
        if (consumer == null) {
            throw new JMSException("Can't receive message: no consumer registered with "
                                   + "identifier "
                                   + consumerId
                                   + " on session");
        }

        // got a valid consumer, so retrieve a handle.
        MessageHandle handle = consumer.receive(wait);

        if (handle != null) {
            // if we get a non-null handle, retrieve the message
            MessageImpl orig = handle.getMessage();
            if (orig != null) {
                // now clone the message to set client specific properties
                try {
                    message = (MessageImpl) orig.clone();
                    message.setJMSRedelivered(handle.getDelivered());
                    message.setConsumerId(handle.getConsumerId());
                } catch (Exception exception) {
                    _log.error(exception);
                }
            }
        }

        // if we have a non-null message then add it to the sent message
        // cache. Additionally, if we are part of a global transaction then
        // we must also sent it to the ResourceManager for recovery.
        if (message != null) {
            _sentMessageCache.process(handle);

            if (_xid != null) {
                try {
                    ResourceManager.instance().logReceivedMessage(_xid,
                                                                  consumer.getId(),
                                                                  handle);
                } catch (Exception exception) {
                    _log.error(exception);
                    JMSException error = new JMSException("Error in receive");
                    error.setLinkedException(exception);
                    throw error;
                }
            }
        }

        return message;
    }

⌨️ 快捷键说明

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