001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq;
018
019import java.io.File;
020import java.io.InputStream;
021import java.io.Serializable;
022import java.net.URL;
023import java.util.Collections;
024import java.util.Iterator;
025import java.util.List;
026import java.util.concurrent.CopyOnWriteArrayList;
027import java.util.concurrent.ThreadPoolExecutor;
028import java.util.concurrent.atomic.AtomicBoolean;
029import java.util.concurrent.atomic.AtomicInteger;
030
031import javax.jms.BytesMessage;
032import javax.jms.Destination;
033import javax.jms.IllegalStateException;
034import javax.jms.InvalidDestinationException;
035import javax.jms.InvalidSelectorException;
036import javax.jms.JMSException;
037import javax.jms.MapMessage;
038import javax.jms.Message;
039import javax.jms.MessageConsumer;
040import javax.jms.MessageListener;
041import javax.jms.MessageProducer;
042import javax.jms.ObjectMessage;
043import javax.jms.Queue;
044import javax.jms.QueueBrowser;
045import javax.jms.QueueReceiver;
046import javax.jms.QueueSender;
047import javax.jms.QueueSession;
048import javax.jms.Session;
049import javax.jms.StreamMessage;
050import javax.jms.TemporaryQueue;
051import javax.jms.TemporaryTopic;
052import javax.jms.TextMessage;
053import javax.jms.Topic;
054import javax.jms.TopicPublisher;
055import javax.jms.TopicSession;
056import javax.jms.TopicSubscriber;
057import javax.jms.TransactionRolledBackException;
058
059import org.apache.activemq.blob.BlobDownloader;
060import org.apache.activemq.blob.BlobTransferPolicy;
061import org.apache.activemq.blob.BlobUploader;
062import org.apache.activemq.command.ActiveMQBlobMessage;
063import org.apache.activemq.command.ActiveMQBytesMessage;
064import org.apache.activemq.command.ActiveMQDestination;
065import org.apache.activemq.command.ActiveMQMapMessage;
066import org.apache.activemq.command.ActiveMQMessage;
067import org.apache.activemq.command.ActiveMQObjectMessage;
068import org.apache.activemq.command.ActiveMQQueue;
069import org.apache.activemq.command.ActiveMQStreamMessage;
070import org.apache.activemq.command.ActiveMQTempDestination;
071import org.apache.activemq.command.ActiveMQTempQueue;
072import org.apache.activemq.command.ActiveMQTempTopic;
073import org.apache.activemq.command.ActiveMQTextMessage;
074import org.apache.activemq.command.ActiveMQTopic;
075import org.apache.activemq.command.Command;
076import org.apache.activemq.command.ConsumerId;
077import org.apache.activemq.command.MessageAck;
078import org.apache.activemq.command.MessageDispatch;
079import org.apache.activemq.command.MessageId;
080import org.apache.activemq.command.ProducerId;
081import org.apache.activemq.command.RemoveInfo;
082import org.apache.activemq.command.Response;
083import org.apache.activemq.command.SessionId;
084import org.apache.activemq.command.SessionInfo;
085import org.apache.activemq.command.TransactionId;
086import org.apache.activemq.management.JMSSessionStatsImpl;
087import org.apache.activemq.management.StatsCapable;
088import org.apache.activemq.management.StatsImpl;
089import org.apache.activemq.thread.Scheduler;
090import org.apache.activemq.transaction.Synchronization;
091import org.apache.activemq.usage.MemoryUsage;
092import org.apache.activemq.util.Callback;
093import org.apache.activemq.util.LongSequenceGenerator;
094import org.slf4j.Logger;
095import org.slf4j.LoggerFactory;
096
097/**
098 * <P>
099 * A <CODE>Session</CODE> object is a single-threaded context for producing
100 * and consuming messages. Although it may allocate provider resources outside
101 * the Java virtual machine (JVM), it is considered a lightweight JMS object.
102 * <P>
103 * A session serves several purposes:
104 * <UL>
105 * <LI>It is a factory for its message producers and consumers.
106 * <LI>It supplies provider-optimized message factories.
107 * <LI>It is a factory for <CODE>TemporaryTopics</CODE> and
108 * <CODE>TemporaryQueues</CODE>.
109 * <LI>It provides a way to create <CODE>Queue</CODE> or <CODE>Topic</CODE>
110 * objects for those clients that need to dynamically manipulate
111 * provider-specific destination names.
112 * <LI>It supports a single series of transactions that combine work spanning
113 * its producers and consumers into atomic units.
114 * <LI>It defines a serial order for the messages it consumes and the messages
115 * it produces.
116 * <LI>It retains messages it consumes until they have been acknowledged.
117 * <LI>It serializes execution of message listeners registered with its message
118 * consumers.
119 * <LI>It is a factory for <CODE>QueueBrowsers</CODE>.
120 * </UL>
121 * <P>
122 * A session can create and service multiple message producers and consumers.
123 * <P>
124 * One typical use is to have a thread block on a synchronous
125 * <CODE>MessageConsumer</CODE> until a message arrives. The thread may then
126 * use one or more of the <CODE>Session</CODE>'s<CODE>MessageProducer</CODE>s.
127 * <P>
128 * If a client desires to have one thread produce messages while others consume
129 * them, the client should use a separate session for its producing thread.
130 * <P>
131 * Once a connection has been started, any session with one or more registered
132 * message listeners is dedicated to the thread of control that delivers
133 * messages to it. It is erroneous for client code to use this session or any of
134 * its constituent objects from another thread of control. The only exception to
135 * this rule is the use of the session or connection <CODE>close</CODE>
136 * method.
137 * <P>
138 * It should be easy for most clients to partition their work naturally into
139 * sessions. This model allows clients to start simply and incrementally add
140 * message processing complexity as their need for concurrency grows.
141 * <P>
142 * The <CODE>close</CODE> method is the only session method that can be called
143 * while some other session method is being executed in another thread.
144 * <P>
145 * A session may be specified as transacted. Each transacted session supports a
146 * single series of transactions. Each transaction groups a set of message sends
147 * and a set of message receives into an atomic unit of work. In effect,
148 * transactions organize a session's input message stream and output message
149 * stream into series of atomic units. When a transaction commits, its atomic
150 * unit of input is acknowledged and its associated atomic unit of output is
151 * sent. If a transaction rollback is done, the transaction's sent messages are
152 * destroyed and the session's input is automatically recovered.
153 * <P>
154 * The content of a transaction's input and output units is simply those
155 * messages that have been produced and consumed within the session's current
156 * transaction.
157 * <P>
158 * A transaction is completed using either its session's <CODE>commit</CODE>
159 * method or its session's <CODE>rollback </CODE> method. The completion of a
160 * session's current transaction automatically begins the next. The result is
161 * that a transacted session always has a current transaction within which its
162 * work is done.
163 * <P>
164 * The Java Transaction Service (JTS) or some other transaction monitor may be
165 * used to combine a session's transaction with transactions on other resources
166 * (databases, other JMS sessions, etc.). Since Java distributed transactions
167 * are controlled via the Java Transaction API (JTA), use of the session's
168 * <CODE>commit</CODE> and <CODE>rollback</CODE> methods in this context is
169 * prohibited.
170 * <P>
171 * The JMS API does not require support for JTA; however, it does define how a
172 * provider supplies this support.
173 * <P>
174 * Although it is also possible for a JMS client to handle distributed
175 * transactions directly, it is unlikely that many JMS clients will do this.
176 * Support for JTA in the JMS API is targeted at systems vendors who will be
177 * integrating the JMS API into their application server products.
178 *
179 *
180 * @see javax.jms.Session
181 * @see javax.jms.QueueSession
182 * @see javax.jms.TopicSession
183 * @see javax.jms.XASession
184 */
185public class ActiveMQSession implements Session, QueueSession, TopicSession, StatsCapable, ActiveMQDispatcher {
186
187    /**
188     * Only acknowledge an individual message - using message.acknowledge()
189     * as opposed to CLIENT_ACKNOWLEDGE which
190     * acknowledges all messages consumed by a session at when acknowledge()
191     * is called
192     */
193    public static final int INDIVIDUAL_ACKNOWLEDGE = 4;
194    public static final int MAX_ACK_CONSTANT = INDIVIDUAL_ACKNOWLEDGE;
195
196    public static interface DeliveryListener {
197        void beforeDelivery(ActiveMQSession session, Message msg);
198
199        void afterDelivery(ActiveMQSession session, Message msg);
200    }
201
202    private static final Logger LOG = LoggerFactory.getLogger(ActiveMQSession.class);
203    private final ThreadPoolExecutor connectionExecutor;
204
205    protected int acknowledgementMode;
206    protected final ActiveMQConnection connection;
207    protected final SessionInfo info;
208    protected final LongSequenceGenerator consumerIdGenerator = new LongSequenceGenerator();
209    protected final LongSequenceGenerator producerIdGenerator = new LongSequenceGenerator();
210    protected final LongSequenceGenerator deliveryIdGenerator = new LongSequenceGenerator();
211    protected final ActiveMQSessionExecutor executor;
212    protected final AtomicBoolean started = new AtomicBoolean(false);
213
214    protected final CopyOnWriteArrayList<ActiveMQMessageConsumer> consumers = new CopyOnWriteArrayList<ActiveMQMessageConsumer>();
215    protected final CopyOnWriteArrayList<ActiveMQMessageProducer> producers = new CopyOnWriteArrayList<ActiveMQMessageProducer>();
216
217    protected boolean closed;
218    private volatile boolean synchronizationRegistered;
219    protected boolean asyncDispatch;
220    protected boolean sessionAsyncDispatch;
221    protected final boolean debug;
222    protected final Object sendMutex = new Object();
223    protected final Object redeliveryGuard = new Object();
224
225    private final AtomicBoolean clearInProgress = new AtomicBoolean();
226
227    private MessageListener messageListener;
228    private final JMSSessionStatsImpl stats;
229    private TransactionContext transactionContext;
230    private DeliveryListener deliveryListener;
231    private MessageTransformer transformer;
232    private BlobTransferPolicy blobTransferPolicy;
233    private long lastDeliveredSequenceId = -2;
234
235    /**
236     * Construct the Session
237     *
238     * @param connection
239     * @param sessionId
240     * @param acknowledgeMode n.b if transacted - the acknowledgeMode ==
241     *                Session.SESSION_TRANSACTED
242     * @param asyncDispatch
243     * @param sessionAsyncDispatch
244     * @throws JMSException on internal error
245     */
246    protected ActiveMQSession(ActiveMQConnection connection, SessionId sessionId, int acknowledgeMode, boolean asyncDispatch, boolean sessionAsyncDispatch) throws JMSException {
247        this.debug = LOG.isDebugEnabled();
248        this.connection = connection;
249        this.acknowledgementMode = acknowledgeMode;
250        this.asyncDispatch = asyncDispatch;
251        this.sessionAsyncDispatch = sessionAsyncDispatch;
252        this.info = new SessionInfo(connection.getConnectionInfo(), sessionId.getValue());
253        setTransactionContext(new TransactionContext(connection));
254        stats = new JMSSessionStatsImpl(producers, consumers);
255        this.connection.asyncSendPacket(info);
256        setTransformer(connection.getTransformer());
257        setBlobTransferPolicy(connection.getBlobTransferPolicy());
258        this.connectionExecutor=connection.getExecutor();
259        this.executor = new ActiveMQSessionExecutor(this);
260        connection.addSession(this);
261        if (connection.isStarted()) {
262            start();
263        }
264
265    }
266
267    protected ActiveMQSession(ActiveMQConnection connection, SessionId sessionId, int acknowledgeMode, boolean asyncDispatch) throws JMSException {
268        this(connection, sessionId, acknowledgeMode, asyncDispatch, true);
269    }
270
271    /**
272     * Sets the transaction context of the session.
273     *
274     * @param transactionContext - provides the means to control a JMS
275     *                transaction.
276     */
277    public void setTransactionContext(TransactionContext transactionContext) {
278        this.transactionContext = transactionContext;
279    }
280
281    /**
282     * Returns the transaction context of the session.
283     *
284     * @return transactionContext - session's transaction context.
285     */
286    public TransactionContext getTransactionContext() {
287        return transactionContext;
288    }
289
290    /*
291     * (non-Javadoc)
292     *
293     * @see org.apache.activemq.management.StatsCapable#getStats()
294     */
295    @Override
296    public StatsImpl getStats() {
297        return stats;
298    }
299
300    /**
301     * Returns the session's statistics.
302     *
303     * @return stats - session's statistics.
304     */
305    public JMSSessionStatsImpl getSessionStats() {
306        return stats;
307    }
308
309    /**
310     * Creates a <CODE>BytesMessage</CODE> object. A <CODE>BytesMessage</CODE>
311     * object is used to send a message containing a stream of uninterpreted
312     * bytes.
313     *
314     * @return the an ActiveMQBytesMessage
315     * @throws JMSException if the JMS provider fails to create this message due
316     *                 to some internal error.
317     */
318    @Override
319    public BytesMessage createBytesMessage() throws JMSException {
320        ActiveMQBytesMessage message = new ActiveMQBytesMessage();
321        configureMessage(message);
322        return message;
323    }
324
325    /**
326     * Creates a <CODE>MapMessage</CODE> object. A <CODE>MapMessage</CODE>
327     * object is used to send a self-defining set of name-value pairs, where
328     * names are <CODE>String</CODE> objects and values are primitive values
329     * in the Java programming language.
330     *
331     * @return an ActiveMQMapMessage
332     * @throws JMSException if the JMS provider fails to create this message due
333     *                 to some internal error.
334     */
335    @Override
336    public MapMessage createMapMessage() throws JMSException {
337        ActiveMQMapMessage message = new ActiveMQMapMessage();
338        configureMessage(message);
339        return message;
340    }
341
342    /**
343     * Creates a <CODE>Message</CODE> object. The <CODE>Message</CODE>
344     * interface is the root interface of all JMS messages. A
345     * <CODE>Message</CODE> object holds all the standard message header
346     * information. It can be sent when a message containing only header
347     * information is sufficient.
348     *
349     * @return an ActiveMQMessage
350     * @throws JMSException if the JMS provider fails to create this message due
351     *                 to some internal error.
352     */
353    @Override
354    public Message createMessage() throws JMSException {
355        ActiveMQMessage message = new ActiveMQMessage();
356        configureMessage(message);
357        return message;
358    }
359
360    /**
361     * Creates an <CODE>ObjectMessage</CODE> object. An
362     * <CODE>ObjectMessage</CODE> object is used to send a message that
363     * contains a serializable Java object.
364     *
365     * @return an ActiveMQObjectMessage
366     * @throws JMSException if the JMS provider fails to create this message due
367     *                 to some internal error.
368     */
369    @Override
370    public ObjectMessage createObjectMessage() throws JMSException {
371        ActiveMQObjectMessage message = new ActiveMQObjectMessage();
372        configureMessage(message);
373        return message;
374    }
375
376    /**
377     * Creates an initialized <CODE>ObjectMessage</CODE> object. An
378     * <CODE>ObjectMessage</CODE> object is used to send a message that
379     * contains a serializable Java object.
380     *
381     * @param object the object to use to initialize this message
382     * @return an ActiveMQObjectMessage
383     * @throws JMSException if the JMS provider fails to create this message due
384     *                 to some internal error.
385     */
386    @Override
387    public ObjectMessage createObjectMessage(Serializable object) throws JMSException {
388        ActiveMQObjectMessage message = new ActiveMQObjectMessage();
389        configureMessage(message);
390        message.setObject(object);
391        return message;
392    }
393
394    /**
395     * Creates a <CODE>StreamMessage</CODE> object. A
396     * <CODE>StreamMessage</CODE> object is used to send a self-defining
397     * stream of primitive values in the Java programming language.
398     *
399     * @return an ActiveMQStreamMessage
400     * @throws JMSException if the JMS provider fails to create this message due
401     *                 to some internal error.
402     */
403    @Override
404    public StreamMessage createStreamMessage() throws JMSException {
405        ActiveMQStreamMessage message = new ActiveMQStreamMessage();
406        configureMessage(message);
407        return message;
408    }
409
410    /**
411     * Creates a <CODE>TextMessage</CODE> object. A <CODE>TextMessage</CODE>
412     * object is used to send a message containing a <CODE>String</CODE>
413     * object.
414     *
415     * @return an ActiveMQTextMessage
416     * @throws JMSException if the JMS provider fails to create this message due
417     *                 to some internal error.
418     */
419    @Override
420    public TextMessage createTextMessage() throws JMSException {
421        ActiveMQTextMessage message = new ActiveMQTextMessage();
422        configureMessage(message);
423        return message;
424    }
425
426    /**
427     * Creates an initialized <CODE>TextMessage</CODE> object. A
428     * <CODE>TextMessage</CODE> object is used to send a message containing a
429     * <CODE>String</CODE>.
430     *
431     * @param text the string used to initialize this message
432     * @return an ActiveMQTextMessage
433     * @throws JMSException if the JMS provider fails to create this message due
434     *                 to some internal error.
435     */
436    @Override
437    public TextMessage createTextMessage(String text) throws JMSException {
438        ActiveMQTextMessage message = new ActiveMQTextMessage();
439        message.setText(text);
440        configureMessage(message);
441        return message;
442    }
443
444    /**
445     * Creates an initialized <CODE>BlobMessage</CODE> object. A
446     * <CODE>BlobMessage</CODE> object is used to send a message containing a
447     * <CODE>URL</CODE> which points to some network addressible BLOB.
448     *
449     * @param url the network addressable URL used to pass directly to the
450     *                consumer
451     * @return a BlobMessage
452     * @throws JMSException if the JMS provider fails to create this message due
453     *                 to some internal error.
454     */
455    public BlobMessage createBlobMessage(URL url) throws JMSException {
456        return createBlobMessage(url, false);
457    }
458
459    /**
460     * Creates an initialized <CODE>BlobMessage</CODE> object. A
461     * <CODE>BlobMessage</CODE> object is used to send a message containing a
462     * <CODE>URL</CODE> which points to some network addressible BLOB.
463     *
464     * @param url the network addressable URL used to pass directly to the
465     *                consumer
466     * @param deletedByBroker indicates whether or not the resource is deleted
467     *                by the broker when the message is acknowledged
468     * @return a BlobMessage
469     * @throws JMSException if the JMS provider fails to create this message due
470     *                 to some internal error.
471     */
472    public BlobMessage createBlobMessage(URL url, boolean deletedByBroker) throws JMSException {
473        ActiveMQBlobMessage message = new ActiveMQBlobMessage();
474        configureMessage(message);
475        message.setURL(url);
476        message.setDeletedByBroker(deletedByBroker);
477        message.setBlobDownloader(new BlobDownloader(getBlobTransferPolicy()));
478        return message;
479    }
480
481    /**
482     * Creates an initialized <CODE>BlobMessage</CODE> object. A
483     * <CODE>BlobMessage</CODE> object is used to send a message containing
484     * the <CODE>File</CODE> content. Before the message is sent the file
485     * conent will be uploaded to the broker or some other remote repository
486     * depending on the {@link #getBlobTransferPolicy()}.
487     *
488     * @param file the file to be uploaded to some remote repo (or the broker)
489     *                depending on the strategy
490     * @return a BlobMessage
491     * @throws JMSException if the JMS provider fails to create this message due
492     *                 to some internal error.
493     */
494    public BlobMessage createBlobMessage(File file) throws JMSException {
495        ActiveMQBlobMessage message = new ActiveMQBlobMessage();
496        configureMessage(message);
497        message.setBlobUploader(new BlobUploader(getBlobTransferPolicy(), file));
498        message.setBlobDownloader(new BlobDownloader((getBlobTransferPolicy())));
499        message.setDeletedByBroker(true);
500        message.setName(file.getName());
501        return message;
502    }
503
504    /**
505     * Creates an initialized <CODE>BlobMessage</CODE> object. A
506     * <CODE>BlobMessage</CODE> object is used to send a message containing
507     * the <CODE>File</CODE> content. Before the message is sent the file
508     * conent will be uploaded to the broker or some other remote repository
509     * depending on the {@link #getBlobTransferPolicy()}. <br/>
510     * <p>
511     * The caller of this method is responsible for closing the
512     * input stream that is used, however the stream can not be closed
513     * until <b>after</b> the message has been sent.  To have this class
514     * manage the stream and close it automatically, use the method
515     * {@link ActiveMQSession#createBlobMessage(File)}
516     *
517     * @param in the stream to be uploaded to some remote repo (or the broker)
518     *                depending on the strategy
519     * @return a BlobMessage
520     * @throws JMSException if the JMS provider fails to create this message due
521     *                 to some internal error.
522     */
523    public BlobMessage createBlobMessage(InputStream in) throws JMSException {
524        ActiveMQBlobMessage message = new ActiveMQBlobMessage();
525        configureMessage(message);
526        message.setBlobUploader(new BlobUploader(getBlobTransferPolicy(), in));
527        message.setBlobDownloader(new BlobDownloader(getBlobTransferPolicy()));
528        message.setDeletedByBroker(true);
529        return message;
530    }
531
532    /**
533     * Indicates whether the session is in transacted mode.
534     *
535     * @return true if the session is in transacted mode
536     * @throws JMSException if there is some internal error.
537     */
538    @Override
539    public boolean getTransacted() throws JMSException {
540        checkClosed();
541        return isTransacted();
542    }
543
544    /**
545     * Returns the acknowledgement mode of the session. The acknowledgement mode
546     * is set at the time that the session is created. If the session is
547     * transacted, the acknowledgement mode is ignored.
548     *
549     * @return If the session is not transacted, returns the current
550     *         acknowledgement mode for the session. If the session is
551     *         transacted, returns SESSION_TRANSACTED.
552     * @throws JMSException
553     * @see javax.jms.Connection#createSession(boolean,int)
554     * @since 1.1 exception JMSException if there is some internal error.
555     */
556    @Override
557    public int getAcknowledgeMode() throws JMSException {
558        checkClosed();
559        return this.acknowledgementMode;
560    }
561
562    /**
563     * Commits all messages done in this transaction and releases any locks
564     * currently held.
565     *
566     * @throws JMSException if the JMS provider fails to commit the transaction
567     *                 due to some internal error.
568     * @throws TransactionRolledBackException if the transaction is rolled back
569     *                 due to some internal error during commit.
570     * @throws javax.jms.IllegalStateException if the method is not called by a
571     *                 transacted session.
572     */
573    @Override
574    public void commit() throws JMSException {
575        checkClosed();
576        if (!getTransacted()) {
577            throw new javax.jms.IllegalStateException("Not a transacted session");
578        }
579        if (LOG.isDebugEnabled()) {
580            LOG.debug(getSessionId() + " Transaction Commit :" + transactionContext.getTransactionId());
581        }
582        transactionContext.commit();
583    }
584
585    /**
586     * Rolls back any messages done in this transaction and releases any locks
587     * currently held.
588     *
589     * @throws JMSException if the JMS provider fails to roll back the
590     *                 transaction due to some internal error.
591     * @throws javax.jms.IllegalStateException if the method is not called by a
592     *                 transacted session.
593     */
594    @Override
595    public void rollback() throws JMSException {
596        checkClosed();
597        if (!getTransacted()) {
598            throw new javax.jms.IllegalStateException("Not a transacted session");
599        }
600        if (LOG.isDebugEnabled()) {
601            LOG.debug(getSessionId() + " Transaction Rollback, txid:"  + transactionContext.getTransactionId());
602        }
603        transactionContext.rollback();
604    }
605
606    /**
607     * Closes the session.
608     * <P>
609     * Since a provider may allocate some resources on behalf of a session
610     * outside the JVM, clients should close the resources when they are not
611     * needed. Relying on garbage collection to eventually reclaim these
612     * resources may not be timely enough.
613     * <P>
614     * There is no need to close the producers and consumers of a closed
615     * session.
616     * <P>
617     * This call will block until a <CODE>receive</CODE> call or message
618     * listener in progress has completed. A blocked message consumer
619     * <CODE>receive</CODE> call returns <CODE>null</CODE> when this session
620     * is closed.
621     * <P>
622     * Closing a transacted session must roll back the transaction in progress.
623     * <P>
624     * This method is the only <CODE>Session</CODE> method that can be called
625     * concurrently.
626     * <P>
627     * Invoking any other <CODE>Session</CODE> method on a closed session must
628     * throw a <CODE> JMSException.IllegalStateException</CODE>. Closing a
629     * closed session must <I>not </I> throw an exception.
630     *
631     * @throws JMSException if the JMS provider fails to close the session due
632     *                 to some internal error.
633     */
634    @Override
635    public void close() throws JMSException {
636        if (!closed) {
637            if (getTransactionContext().isInXATransaction()) {
638                if (!synchronizationRegistered) {
639                    synchronizationRegistered = true;
640                    getTransactionContext().addSynchronization(new Synchronization() {
641
642                                        @Override
643                                        public void afterCommit() throws Exception {
644                                            doClose();
645                                            synchronizationRegistered = false;
646                                        }
647
648                                        @Override
649                                        public void afterRollback() throws Exception {
650                                            doClose();
651                                            synchronizationRegistered = false;
652                                        }
653                                    });
654                }
655
656            } else {
657                doClose();
658            }
659        }
660    }
661
662    private void doClose() throws JMSException {
663        boolean interrupted = Thread.interrupted();
664        dispose();
665        RemoveInfo removeCommand = info.createRemoveCommand();
666        removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId);
667        connection.asyncSendPacket(removeCommand);
668        if (interrupted) {
669            Thread.currentThread().interrupt();
670        }
671    }
672
673    final AtomicInteger clearRequestsCounter = new AtomicInteger(0);
674    void clearMessagesInProgress(AtomicInteger transportInterruptionProcessingComplete) {
675        clearRequestsCounter.incrementAndGet();
676        executor.clearMessagesInProgress();
677        // we are called from inside the transport reconnection logic which involves us
678        // clearing all the connections' consumers dispatch and delivered lists. So rather
679        // than trying to grab a mutex (which could be already owned by the message listener
680        // calling the send or an ack) we allow it to complete in a separate thread via the
681        // scheduler and notify us via connection.transportInterruptionProcessingComplete()
682        //
683        // We must be careful though not to allow multiple calls to this method from a
684        // connection that is having issue becoming fully established from causing a large
685        // build up of scheduled tasks to clear the same consumers over and over.
686        if (consumers.isEmpty()) {
687            return;
688        }
689
690        if (clearInProgress.compareAndSet(false, true)) {
691            for (final ActiveMQMessageConsumer consumer : consumers) {
692                consumer.inProgressClearRequired();
693                transportInterruptionProcessingComplete.incrementAndGet();
694                try {
695                    connection.getScheduler().executeAfterDelay(new Runnable() {
696                        @Override
697                        public void run() {
698                            consumer.clearMessagesInProgress();
699                        }}, 0l);
700                } catch (JMSException e) {
701                    connection.onClientInternalException(e);
702                }
703            }
704
705            try {
706                connection.getScheduler().executeAfterDelay(new Runnable() {
707                    @Override
708                    public void run() {
709                        clearInProgress.set(false);
710                    }}, 0l);
711            } catch (JMSException e) {
712                connection.onClientInternalException(e);
713            }
714        }
715    }
716
717    void deliverAcks() {
718        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
719            ActiveMQMessageConsumer consumer = iter.next();
720            consumer.deliverAcks();
721        }
722    }
723
724    public synchronized void dispose() throws JMSException {
725        if (!closed) {
726
727            try {
728                executor.close();
729
730                for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
731                    ActiveMQMessageConsumer consumer = iter.next();
732                    consumer.setFailureError(connection.getFirstFailureError());
733                    consumer.dispose();
734                    lastDeliveredSequenceId = Math.max(lastDeliveredSequenceId, consumer.getLastDeliveredSequenceId());
735                }
736                consumers.clear();
737
738                for (Iterator<ActiveMQMessageProducer> iter = producers.iterator(); iter.hasNext();) {
739                    ActiveMQMessageProducer producer = iter.next();
740                    producer.dispose();
741                }
742                producers.clear();
743
744                try {
745                    if (getTransactionContext().isInLocalTransaction()) {
746                        rollback();
747                    }
748                } catch (JMSException e) {
749                }
750
751            } finally {
752                connection.removeSession(this);
753                this.transactionContext = null;
754                closed = true;
755            }
756        }
757    }
758
759    /**
760     * Checks that the session is not closed then configures the message
761     */
762    protected void configureMessage(ActiveMQMessage message) throws IllegalStateException {
763        checkClosed();
764        message.setConnection(connection);
765    }
766
767    /**
768     * Check if the session is closed. It is used for ensuring that the session
769     * is open before performing various operations.
770     *
771     * @throws IllegalStateException if the Session is closed
772     */
773    protected void checkClosed() throws IllegalStateException {
774        if (closed) {
775            throw new IllegalStateException("The Session is closed");
776        }
777    }
778
779    /**
780     * Checks if the session is closed.
781     *
782     * @return true if the session is closed, false otherwise.
783     */
784    public boolean isClosed() {
785        return closed;
786    }
787
788    /**
789     * Stops message delivery in this session, and restarts message delivery
790     * with the oldest unacknowledged message.
791     * <P>
792     * All consumers deliver messages in a serial order. Acknowledging a
793     * received message automatically acknowledges all messages that have been
794     * delivered to the client.
795     * <P>
796     * Restarting a session causes it to take the following actions:
797     * <UL>
798     * <LI>Stop message delivery
799     * <LI>Mark all messages that might have been delivered but not
800     * acknowledged as "redelivered"
801     * <LI>Restart the delivery sequence including all unacknowledged messages
802     * that had been previously delivered. Redelivered messages do not have to
803     * be delivered in exactly their original delivery order.
804     * </UL>
805     *
806     * @throws JMSException if the JMS provider fails to stop and restart
807     *                 message delivery due to some internal error.
808     * @throws IllegalStateException if the method is called by a transacted
809     *                 session.
810     */
811    @Override
812    public void recover() throws JMSException {
813
814        checkClosed();
815        if (getTransacted()) {
816            throw new IllegalStateException("This session is transacted");
817        }
818
819        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
820            ActiveMQMessageConsumer c = iter.next();
821            c.rollback();
822        }
823
824    }
825
826    /**
827     * Returns the session's distinguished message listener (optional).
828     *
829     * @return the message listener associated with this session
830     * @throws JMSException if the JMS provider fails to get the message
831     *                 listener due to an internal error.
832     * @see javax.jms.Session#setMessageListener(javax.jms.MessageListener)
833     * @see javax.jms.ServerSessionPool
834     * @see javax.jms.ServerSession
835     */
836    @Override
837    public MessageListener getMessageListener() throws JMSException {
838        checkClosed();
839        return this.messageListener;
840    }
841
842    /**
843     * Sets the session's distinguished message listener (optional).
844     * <P>
845     * When the distinguished message listener is set, no other form of message
846     * receipt in the session can be used; however, all forms of sending
847     * messages are still supported.
848     * <P>
849     * If this session has been closed, then an {@link IllegalStateException} is
850     * thrown, if trying to set a new listener. However setting the listener
851     * to <tt>null</tt> is allowed, to clear the listener, even if this session
852     * has been closed prior.
853     * <P>
854     * This is an expert facility not used by regular JMS clients.
855     *
856     * @param listener the message listener to associate with this session
857     * @throws JMSException if the JMS provider fails to set the message
858     *                 listener due to an internal error.
859     * @see javax.jms.Session#getMessageListener()
860     * @see javax.jms.ServerSessionPool
861     * @see javax.jms.ServerSession
862     */
863    @Override
864    public void setMessageListener(MessageListener listener) throws JMSException {
865        // only check for closed if we set a new listener, as we allow to clear
866        // the listener, such as when an application is shutting down, and is
867        // no longer using a message listener on this session
868        if (listener != null) {
869            checkClosed();
870        }
871        this.messageListener = listener;
872
873        if (listener != null) {
874            executor.setDispatchedBySessionPool(true);
875        }
876    }
877
878    /**
879     * Optional operation, intended to be used only by Application Servers, not
880     * by ordinary JMS clients.
881     *
882     * @see javax.jms.ServerSession
883     */
884    @Override
885    public void run() {
886        MessageDispatch messageDispatch;
887        while ((messageDispatch = executor.dequeueNoWait()) != null) {
888            final MessageDispatch md = messageDispatch;
889            final ActiveMQMessage message = (ActiveMQMessage)md.getMessage();
890
891            MessageAck earlyAck = null;
892            if (message.isExpired()) {
893                earlyAck = new MessageAck(md, MessageAck.EXPIRED_ACK_TYPE, 1);
894                earlyAck.setFirstMessageId(message.getMessageId());
895            } else if (connection.isDuplicate(ActiveMQSession.this, message)) {
896                LOG.debug("{} got duplicate: {}", this, message.getMessageId());
897                earlyAck = new MessageAck(md, MessageAck.POSION_ACK_TYPE, 1);
898                earlyAck.setFirstMessageId(md.getMessage().getMessageId());
899                earlyAck.setPoisonCause(new Throwable("Duplicate delivery to " + this));
900            }
901            if (earlyAck != null) {
902                try {
903                    asyncSendPacket(earlyAck);
904                } catch (Throwable t) {
905                    LOG.error("error dispatching ack: {} ", earlyAck, t);
906                    connection.onClientInternalException(t);
907                } finally {
908                    continue;
909                }
910            }
911
912            if (isClientAcknowledge()||isIndividualAcknowledge()) {
913                message.setAcknowledgeCallback(new Callback() {
914                    @Override
915                    public void execute() throws Exception {
916                    }
917                });
918            }
919
920            if (deliveryListener != null) {
921                deliveryListener.beforeDelivery(this, message);
922            }
923
924            md.setDeliverySequenceId(getNextDeliveryId());
925            lastDeliveredSequenceId = message.getMessageId().getBrokerSequenceId();
926
927            final MessageAck ack = new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, 1);
928
929            final AtomicBoolean afterDeliveryError = new AtomicBoolean(false);
930            /*
931            * The redelivery guard is to allow the endpoint lifecycle to complete before the messsage is dispatched.
932            * We dont want the after deliver being called after the redeliver as it may cause some weird stuff.
933            * */
934            synchronized (redeliveryGuard) {
935                try {
936                    ack.setFirstMessageId(md.getMessage().getMessageId());
937                    doStartTransaction();
938                    ack.setTransactionId(getTransactionContext().getTransactionId());
939                    if (ack.getTransactionId() != null) {
940                        getTransactionContext().addSynchronization(new Synchronization() {
941
942                            final int clearRequestCount = (clearRequestsCounter.get() == Integer.MAX_VALUE ? clearRequestsCounter.incrementAndGet() : clearRequestsCounter.get());
943
944                            @Override
945                            public void beforeEnd() throws Exception {
946                                // validate our consumer so we don't push stale acks that get ignored
947                                if (ack.getTransactionId().isXATransaction() && !connection.hasDispatcher(ack.getConsumerId())) {
948                                    LOG.debug("forcing rollback - {} consumer no longer active on {}", ack, connection);
949                                    throw new TransactionRolledBackException("consumer " + ack.getConsumerId() + " no longer active on " + connection);
950                                }
951                                LOG.trace("beforeEnd ack {}", ack);
952                                sendAck(ack);
953                            }
954
955                            @Override
956                            public void afterRollback() throws Exception {
957                                LOG.trace("rollback {}", ack, new Throwable("here"));
958                                // ensure we don't filter this as a duplicate
959                                connection.rollbackDuplicate(ActiveMQSession.this, md.getMessage());
960
961                                // don't redeliver if we have been interrupted b/c the broker will redeliver on reconnect
962                                if (clearRequestsCounter.get() > clearRequestCount) {
963                                    LOG.debug("No redelivery of {} on rollback of {} due to failover of {}", md, ack.getTransactionId(), connection.getTransport());
964                                    return;
965                                }
966
967                                // validate our consumer so we don't push stale acks that get ignored or redeliver what will be redispatched
968                                if (ack.getTransactionId().isXATransaction() && !connection.hasDispatcher(ack.getConsumerId())) {
969                                    LOG.debug("No local redelivery of {} on rollback of {} because consumer is no longer active on {}", md, ack.getTransactionId(), connection.getTransport());
970                                    return;
971                                }
972
973                                RedeliveryPolicy redeliveryPolicy = connection.getRedeliveryPolicy();
974                                int redeliveryCounter = md.getMessage().getRedeliveryCounter();
975                                if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES
976                                        && redeliveryCounter >= redeliveryPolicy.getMaximumRedeliveries()) {
977                                    // We need to NACK the messages so that they get
978                                    // sent to the
979                                    // DLQ.
980                                    // Acknowledge the last message.
981                                    MessageAck ack = new MessageAck(md, MessageAck.POSION_ACK_TYPE, 1);
982                                    ack.setFirstMessageId(md.getMessage().getMessageId());
983                                    ack.setPoisonCause(new Throwable("Exceeded ra redelivery policy limit:" + redeliveryPolicy));
984                                    asyncSendPacket(ack);
985
986                                } else {
987
988                                    MessageAck ack = new MessageAck(md, MessageAck.REDELIVERED_ACK_TYPE, 1);
989                                    ack.setFirstMessageId(md.getMessage().getMessageId());
990                                    asyncSendPacket(ack);
991
992                                    // Figure out how long we should wait to resend
993                                    // this message.
994                                    long redeliveryDelay = redeliveryPolicy.getInitialRedeliveryDelay();
995                                    for (int i = 0; i < redeliveryCounter; i++) {
996                                        redeliveryDelay = redeliveryPolicy.getNextRedeliveryDelay(redeliveryDelay);
997                                    }
998
999                                    /*
1000                                    * If we are a non blocking delivery then we need to stop the executor to avoid more
1001                                    * messages being delivered, once the message is redelivered we can restart it.
1002                                    * */
1003                                    if (!connection.isNonBlockingRedelivery()) {
1004                                        LOG.debug("Blocking session until re-delivery...");
1005                                        executor.stop();
1006                                    }
1007
1008                                    connection.getScheduler().executeAfterDelay(new Runnable() {
1009
1010                                        @Override
1011                                        public void run() {
1012                                            /*
1013                                            * wait for the first delivery to be complete, i.e. after delivery has been called.
1014                                            * */
1015                                            synchronized (redeliveryGuard) {
1016                                                /*
1017                                                * If its non blocking then we can just dispatch in a new session.
1018                                                * */
1019                                                if (connection.isNonBlockingRedelivery()) {
1020                                                    ((ActiveMQDispatcher) md.getConsumer()).dispatch(md);
1021                                                } else {
1022                                                    /*
1023                                                    * If there has been an error thrown during afterDelivery then the
1024                                                    * endpoint will be marked as dead so redelivery will fail (and eventually
1025                                                    * the session marked as stale), in this case we can only call dispatch
1026                                                    * which will create a new session with a new endpoint.
1027                                                    * */
1028                                                    if (afterDeliveryError.get()) {
1029                                                        ((ActiveMQDispatcher) md.getConsumer()).dispatch(md);
1030                                                    } else {
1031                                                        executor.executeFirst(md);
1032                                                        executor.start();
1033                                                    }
1034                                                }
1035                                            }
1036                                        }
1037                                    }, redeliveryDelay);
1038                                }
1039                                md.getMessage().onMessageRolledBack();
1040                            }
1041                        });
1042                    }
1043
1044                    LOG.trace("{} onMessage({})", this, message.getMessageId());
1045                    messageListener.onMessage(message);
1046
1047                } catch (Throwable e) {
1048                    LOG.error("error dispatching message: ", e);
1049
1050                    // A problem while invoking the MessageListener does not
1051                    // in general indicate a problem with the connection to the broker, i.e.
1052                    // it will usually be sufficient to let the afterDelivery() method either
1053                    // commit or roll back in order to deal with the exception.
1054                    // However, we notify any registered client internal exception listener
1055                    // of the problem.
1056                    connection.onClientInternalException(e);
1057                } finally {
1058                    if (ack.getTransactionId() == null) {
1059                        try {
1060                            asyncSendPacket(ack);
1061                        } catch (Throwable e) {
1062                            connection.onClientInternalException(e);
1063                        }
1064                    }
1065                }
1066
1067                if (deliveryListener != null) {
1068                    try {
1069                        deliveryListener.afterDelivery(this, message);
1070                    } catch (Throwable t) {
1071                        LOG.debug("Unable to call after delivery", t);
1072                        afterDeliveryError.set(true);
1073                        throw new RuntimeException(t);
1074                    }
1075                }
1076            }
1077            /*
1078            * this can be outside the try/catch as if an exception is thrown then this session will be marked as stale anyway.
1079            * It also needs to be outside the redelivery guard.
1080            * */
1081            try {
1082                executor.waitForQueueRestart();
1083            } catch (InterruptedException ex) {
1084                connection.onClientInternalException(ex);
1085            }
1086        }
1087    }
1088
1089    /**
1090     * Creates a <CODE>MessageProducer</CODE> to send messages to the
1091     * specified destination.
1092     * <P>
1093     * A client uses a <CODE>MessageProducer</CODE> object to send messages to
1094     * a destination. Since <CODE>Queue </CODE> and <CODE>Topic</CODE> both
1095     * inherit from <CODE>Destination</CODE>, they can be used in the
1096     * destination parameter to create a <CODE>MessageProducer</CODE> object.
1097     *
1098     * @param destination the <CODE>Destination</CODE> to send to, or null if
1099     *                this is a producer which does not have a specified
1100     *                destination.
1101     * @return the MessageProducer
1102     * @throws JMSException if the session fails to create a MessageProducer due
1103     *                 to some internal error.
1104     * @throws InvalidDestinationException if an invalid destination is
1105     *                 specified.
1106     * @since 1.1
1107     */
1108    @Override
1109    public MessageProducer createProducer(Destination destination) throws JMSException {
1110        checkClosed();
1111        if (destination instanceof CustomDestination) {
1112            CustomDestination customDestination = (CustomDestination)destination;
1113            return customDestination.createProducer(this);
1114        }
1115        int timeSendOut = connection.getSendTimeout();
1116        return new ActiveMQMessageProducer(this, getNextProducerId(), ActiveMQMessageTransformation.transformDestination(destination),timeSendOut);
1117    }
1118
1119    /**
1120     * Creates a <CODE>MessageConsumer</CODE> for the specified destination.
1121     * Since <CODE>Queue</CODE> and <CODE> Topic</CODE> both inherit from
1122     * <CODE>Destination</CODE>, they can be used in the destination
1123     * parameter to create a <CODE>MessageConsumer</CODE>.
1124     *
1125     * @param destination the <CODE>Destination</CODE> to access.
1126     * @return the MessageConsumer
1127     * @throws JMSException if the session fails to create a consumer due to
1128     *                 some internal error.
1129     * @throws InvalidDestinationException if an invalid destination is
1130     *                 specified.
1131     * @since 1.1
1132     */
1133    @Override
1134    public MessageConsumer createConsumer(Destination destination) throws JMSException {
1135        return createConsumer(destination, (String) null);
1136    }
1137
1138    /**
1139     * Creates a <CODE>MessageConsumer</CODE> for the specified destination,
1140     * using a message selector. Since <CODE> Queue</CODE> and
1141     * <CODE>Topic</CODE> both inherit from <CODE>Destination</CODE>, they
1142     * can be used in the destination parameter to create a
1143     * <CODE>MessageConsumer</CODE>.
1144     * <P>
1145     * A client uses a <CODE>MessageConsumer</CODE> object to receive messages
1146     * that have been sent to a destination.
1147     *
1148     * @param destination the <CODE>Destination</CODE> to access
1149     * @param messageSelector only messages with properties matching the message
1150     *                selector expression are delivered. A value of null or an
1151     *                empty string indicates that there is no message selector
1152     *                for the message consumer.
1153     * @return the MessageConsumer
1154     * @throws JMSException if the session fails to create a MessageConsumer due
1155     *                 to some internal error.
1156     * @throws InvalidDestinationException if an invalid destination is
1157     *                 specified.
1158     * @throws InvalidSelectorException if the message selector is invalid.
1159     * @since 1.1
1160     */
1161    @Override
1162    public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException {
1163        return createConsumer(destination, messageSelector, false);
1164    }
1165
1166    /**
1167     * Creates a <CODE>MessageConsumer</CODE> for the specified destination.
1168     * Since <CODE>Queue</CODE> and <CODE> Topic</CODE> both inherit from
1169     * <CODE>Destination</CODE>, they can be used in the destination
1170     * parameter to create a <CODE>MessageConsumer</CODE>.
1171     *
1172     * @param destination the <CODE>Destination</CODE> to access.
1173     * @param messageListener the listener to use for async consumption of messages
1174     * @return the MessageConsumer
1175     * @throws JMSException if the session fails to create a consumer due to
1176     *                 some internal error.
1177     * @throws InvalidDestinationException if an invalid destination is
1178     *                 specified.
1179     * @since 1.1
1180     */
1181    public MessageConsumer createConsumer(Destination destination, MessageListener messageListener) throws JMSException {
1182        return createConsumer(destination, null, messageListener);
1183    }
1184
1185    /**
1186     * Creates a <CODE>MessageConsumer</CODE> for the specified destination,
1187     * using a message selector. Since <CODE> Queue</CODE> and
1188     * <CODE>Topic</CODE> both inherit from <CODE>Destination</CODE>, they
1189     * can be used in the destination parameter to create a
1190     * <CODE>MessageConsumer</CODE>.
1191     * <P>
1192     * A client uses a <CODE>MessageConsumer</CODE> object to receive messages
1193     * that have been sent to a destination.
1194     *
1195     * @param destination the <CODE>Destination</CODE> to access
1196     * @param messageSelector only messages with properties matching the message
1197     *                selector expression are delivered. A value of null or an
1198     *                empty string indicates that there is no message selector
1199     *                for the message consumer.
1200     * @param messageListener the listener to use for async consumption of messages
1201     * @return the MessageConsumer
1202     * @throws JMSException if the session fails to create a MessageConsumer due
1203     *                 to some internal error.
1204     * @throws InvalidDestinationException if an invalid destination is
1205     *                 specified.
1206     * @throws InvalidSelectorException if the message selector is invalid.
1207     * @since 1.1
1208     */
1209    public MessageConsumer createConsumer(Destination destination, String messageSelector, MessageListener messageListener) throws JMSException {
1210        return createConsumer(destination, messageSelector, false, messageListener);
1211    }
1212
1213    /**
1214     * Creates <CODE>MessageConsumer</CODE> for the specified destination,
1215     * using a message selector. This method can specify whether messages
1216     * published by its own connection should be delivered to it, if the
1217     * destination is a topic.
1218     * <P>
1219     * Since <CODE>Queue</CODE> and <CODE>Topic</CODE> both inherit from
1220     * <CODE>Destination</CODE>, they can be used in the destination
1221     * parameter to create a <CODE>MessageConsumer</CODE>.
1222     * <P>
1223     * A client uses a <CODE>MessageConsumer</CODE> object to receive messages
1224     * that have been published to a destination.
1225     * <P>
1226     * In some cases, a connection may both publish and subscribe to a topic.
1227     * The consumer <CODE>NoLocal</CODE> attribute allows a consumer to
1228     * inhibit the delivery of messages published by its own connection. The
1229     * default value for this attribute is False. The <CODE>noLocal</CODE>
1230     * value must be supported by destinations that are topics.
1231     *
1232     * @param destination the <CODE>Destination</CODE> to access
1233     * @param messageSelector only messages with properties matching the message
1234     *                selector expression are delivered. A value of null or an
1235     *                empty string indicates that there is no message selector
1236     *                for the message consumer.
1237     * @param noLocal - if true, and the destination is a topic, inhibits the
1238     *                delivery of messages published by its own connection. The
1239     *                behavior for <CODE>NoLocal</CODE> is not specified if
1240     *                the destination is a queue.
1241     * @return the MessageConsumer
1242     * @throws JMSException if the session fails to create a MessageConsumer due
1243     *                 to some internal error.
1244     * @throws InvalidDestinationException if an invalid destination is
1245     *                 specified.
1246     * @throws InvalidSelectorException if the message selector is invalid.
1247     * @since 1.1
1248     */
1249    @Override
1250    public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean noLocal) throws JMSException {
1251        return createConsumer(destination, messageSelector, noLocal, null);
1252    }
1253
1254    /**
1255     * Creates <CODE>MessageConsumer</CODE> for the specified destination,
1256     * using a message selector. This method can specify whether messages
1257     * published by its own connection should be delivered to it, if the
1258     * destination is a topic.
1259     * <P>
1260     * Since <CODE>Queue</CODE> and <CODE>Topic</CODE> both inherit from
1261     * <CODE>Destination</CODE>, they can be used in the destination
1262     * parameter to create a <CODE>MessageConsumer</CODE>.
1263     * <P>
1264     * A client uses a <CODE>MessageConsumer</CODE> object to receive messages
1265     * that have been published to a destination.
1266     * <P>
1267     * In some cases, a connection may both publish and subscribe to a topic.
1268     * The consumer <CODE>NoLocal</CODE> attribute allows a consumer to
1269     * inhibit the delivery of messages published by its own connection. The
1270     * default value for this attribute is False. The <CODE>noLocal</CODE>
1271     * value must be supported by destinations that are topics.
1272     *
1273     * @param destination the <CODE>Destination</CODE> to access
1274     * @param messageSelector only messages with properties matching the message
1275     *                selector expression are delivered. A value of null or an
1276     *                empty string indicates that there is no message selector
1277     *                for the message consumer.
1278     * @param noLocal - if true, and the destination is a topic, inhibits the
1279     *                delivery of messages published by its own connection. The
1280     *                behavior for <CODE>NoLocal</CODE> is not specified if
1281     *                the destination is a queue.
1282     * @param messageListener the listener to use for async consumption of messages
1283     * @return the MessageConsumer
1284     * @throws JMSException if the session fails to create a MessageConsumer due
1285     *                 to some internal error.
1286     * @throws InvalidDestinationException if an invalid destination is
1287     *                 specified.
1288     * @throws InvalidSelectorException if the message selector is invalid.
1289     * @since 1.1
1290     */
1291    public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean noLocal, MessageListener messageListener) throws JMSException {
1292        checkClosed();
1293
1294        if (destination instanceof CustomDestination) {
1295            CustomDestination customDestination = (CustomDestination)destination;
1296            return customDestination.createConsumer(this, messageSelector, noLocal);
1297        }
1298
1299        ActiveMQPrefetchPolicy prefetchPolicy = connection.getPrefetchPolicy();
1300        int prefetch = 0;
1301        if (destination instanceof Topic) {
1302            prefetch = prefetchPolicy.getTopicPrefetch();
1303        } else {
1304            prefetch = prefetchPolicy.getQueuePrefetch();
1305        }
1306        ActiveMQDestination activemqDestination = ActiveMQMessageTransformation.transformDestination(destination);
1307        return new ActiveMQMessageConsumer(this, getNextConsumerId(), activemqDestination, null, messageSelector,
1308                prefetch, prefetchPolicy.getMaximumPendingMessageLimit(), noLocal, false, isAsyncDispatch(), messageListener);
1309    }
1310
1311    /**
1312     * Creates a queue identity given a <CODE>Queue</CODE> name.
1313     * <P>
1314     * This facility is provided for the rare cases where clients need to
1315     * dynamically manipulate queue identity. It allows the creation of a queue
1316     * identity with a provider-specific name. Clients that depend on this
1317     * ability are not portable.
1318     * <P>
1319     * Note that this method is not for creating the physical queue. The
1320     * physical creation of queues is an administrative task and is not to be
1321     * initiated by the JMS API. The one exception is the creation of temporary
1322     * queues, which is accomplished with the <CODE>createTemporaryQueue</CODE>
1323     * method.
1324     *
1325     * @param queueName the name of this <CODE>Queue</CODE>
1326     * @return a <CODE>Queue</CODE> with the given name
1327     * @throws JMSException if the session fails to create a queue due to some
1328     *                 internal error.
1329     * @since 1.1
1330     */
1331    @Override
1332    public Queue createQueue(String queueName) throws JMSException {
1333        checkClosed();
1334        if (queueName.startsWith(ActiveMQDestination.TEMP_DESTINATION_NAME_PREFIX)) {
1335            return new ActiveMQTempQueue(queueName);
1336        }
1337        return new ActiveMQQueue(queueName);
1338    }
1339
1340    /**
1341     * Creates a topic identity given a <CODE>Topic</CODE> name.
1342     * <P>
1343     * This facility is provided for the rare cases where clients need to
1344     * dynamically manipulate topic identity. This allows the creation of a
1345     * topic identity with a provider-specific name. Clients that depend on this
1346     * ability are not portable.
1347     * <P>
1348     * Note that this method is not for creating the physical topic. The
1349     * physical creation of topics is an administrative task and is not to be
1350     * initiated by the JMS API. The one exception is the creation of temporary
1351     * topics, which is accomplished with the <CODE>createTemporaryTopic</CODE>
1352     * method.
1353     *
1354     * @param topicName the name of this <CODE>Topic</CODE>
1355     * @return a <CODE>Topic</CODE> with the given name
1356     * @throws JMSException if the session fails to create a topic due to some
1357     *                 internal error.
1358     * @since 1.1
1359     */
1360    @Override
1361    public Topic createTopic(String topicName) throws JMSException {
1362        checkClosed();
1363        if (topicName.startsWith(ActiveMQDestination.TEMP_DESTINATION_NAME_PREFIX)) {
1364            return new ActiveMQTempTopic(topicName);
1365        }
1366        return new ActiveMQTopic(topicName);
1367    }
1368
1369    /**
1370     * Creates a <CODE>QueueBrowser</CODE> object to peek at the messages on
1371     * the specified queue.
1372     *
1373     * @param queue the <CODE>queue</CODE> to access
1374     * @exception InvalidDestinationException if an invalid destination is
1375     *                    specified
1376     * @since 1.1
1377     */
1378    /**
1379     * Creates a durable subscriber to the specified topic.
1380     * <P>
1381     * If a client needs to receive all the messages published on a topic,
1382     * including the ones published while the subscriber is inactive, it uses a
1383     * durable <CODE>TopicSubscriber</CODE>. The JMS provider retains a
1384     * record of this durable subscription and insures that all messages from
1385     * the topic's publishers are retained until they are acknowledged by this
1386     * durable subscriber or they have expired.
1387     * <P>
1388     * Sessions with durable subscribers must always provide the same client
1389     * identifier. In addition, each client must specify a name that uniquely
1390     * identifies (within client identifier) each durable subscription it
1391     * creates. Only one session at a time can have a
1392     * <CODE>TopicSubscriber</CODE> for a particular durable subscription.
1393     * <P>
1394     * A client can change an existing durable subscription by creating a
1395     * durable <CODE>TopicSubscriber</CODE> with the same name and a new topic
1396     * and/or message selector. Changing a durable subscriber is equivalent to
1397     * unsubscribing (deleting) the old one and creating a new one.
1398     * <P>
1399     * In some cases, a connection may both publish and subscribe to a topic.
1400     * The subscriber <CODE>NoLocal</CODE> attribute allows a subscriber to
1401     * inhibit the delivery of messages published by its own connection. The
1402     * default value for this attribute is false.
1403     *
1404     * @param topic the non-temporary <CODE>Topic</CODE> to subscribe to
1405     * @param name the name used to identify this subscription
1406     * @return the TopicSubscriber
1407     * @throws JMSException if the session fails to create a subscriber due to
1408     *                 some internal error.
1409     * @throws InvalidDestinationException if an invalid topic is specified.
1410     * @since 1.1
1411     */
1412    @Override
1413    public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException {
1414        checkClosed();
1415        return createDurableSubscriber(topic, name, null, false);
1416    }
1417
1418    /**
1419     * Creates a durable subscriber to the specified topic, using a message
1420     * selector and specifying whether messages published by its own connection
1421     * should be delivered to it.
1422     * <P>
1423     * If a client needs to receive all the messages published on a topic,
1424     * including the ones published while the subscriber is inactive, it uses a
1425     * durable <CODE>TopicSubscriber</CODE>. The JMS provider retains a
1426     * record of this durable subscription and insures that all messages from
1427     * the topic's publishers are retained until they are acknowledged by this
1428     * durable subscriber or they have expired.
1429     * <P>
1430     * Sessions with durable subscribers must always provide the same client
1431     * identifier. In addition, each client must specify a name which uniquely
1432     * identifies (within client identifier) each durable subscription it
1433     * creates. Only one session at a time can have a
1434     * <CODE>TopicSubscriber</CODE> for a particular durable subscription. An
1435     * inactive durable subscriber is one that exists but does not currently
1436     * have a message consumer associated with it.
1437     * <P>
1438     * A client can change an existing durable subscription by creating a
1439     * durable <CODE>TopicSubscriber</CODE> with the same name and a new topic
1440     * and/or message selector. Changing a durable subscriber is equivalent to
1441     * unsubscribing (deleting) the old one and creating a new one.
1442     *
1443     * @param topic the non-temporary <CODE>Topic</CODE> to subscribe to
1444     * @param name the name used to identify this subscription
1445     * @param messageSelector only messages with properties matching the message
1446     *                selector expression are delivered. A value of null or an
1447     *                empty string indicates that there is no message selector
1448     *                for the message consumer.
1449     * @param noLocal if set, inhibits the delivery of messages published by its
1450     *                own connection
1451     * @return the Queue Browser
1452     * @throws JMSException if the session fails to create a subscriber due to
1453     *                 some internal error.
1454     * @throws InvalidDestinationException if an invalid topic is specified.
1455     * @throws InvalidSelectorException if the message selector is invalid.
1456     * @since 1.1
1457     */
1458    @Override
1459    public TopicSubscriber createDurableSubscriber(Topic topic, String name, String messageSelector, boolean noLocal) throws JMSException {
1460        checkClosed();
1461
1462        if (topic == null) {
1463            throw new InvalidDestinationException("Topic cannot be null");
1464        }
1465
1466        if (topic instanceof CustomDestination) {
1467            CustomDestination customDestination = (CustomDestination)topic;
1468            return customDestination.createDurableSubscriber(this, name, messageSelector, noLocal);
1469        }
1470
1471        connection.checkClientIDWasManuallySpecified();
1472        ActiveMQPrefetchPolicy prefetchPolicy = this.connection.getPrefetchPolicy();
1473        int prefetch = isAutoAcknowledge() && connection.isOptimizedMessageDispatch() ? prefetchPolicy.getOptimizeDurableTopicPrefetch() : prefetchPolicy.getDurableTopicPrefetch();
1474        int maxPrendingLimit = prefetchPolicy.getMaximumPendingMessageLimit();
1475        return new ActiveMQTopicSubscriber(this, getNextConsumerId(), ActiveMQMessageTransformation.transformDestination(topic), name, messageSelector, prefetch, maxPrendingLimit,
1476                                           noLocal, false, asyncDispatch);
1477    }
1478
1479    /**
1480     * Creates a <CODE>QueueBrowser</CODE> object to peek at the messages on
1481     * the specified queue.
1482     *
1483     * @param queue the <CODE>queue</CODE> to access
1484     * @return the Queue Browser
1485     * @throws JMSException if the session fails to create a browser due to some
1486     *                 internal error.
1487     * @throws InvalidDestinationException if an invalid destination is
1488     *                 specified
1489     * @since 1.1
1490     */
1491    @Override
1492    public QueueBrowser createBrowser(Queue queue) throws JMSException {
1493        checkClosed();
1494        return createBrowser(queue, null);
1495    }
1496
1497    /**
1498     * Creates a <CODE>QueueBrowser</CODE> object to peek at the messages on
1499     * the specified queue using a message selector.
1500     *
1501     * @param queue the <CODE>queue</CODE> to access
1502     * @param messageSelector only messages with properties matching the message
1503     *                selector expression are delivered. A value of null or an
1504     *                empty string indicates that there is no message selector
1505     *                for the message consumer.
1506     * @return the Queue Browser
1507     * @throws JMSException if the session fails to create a browser due to some
1508     *                 internal error.
1509     * @throws InvalidDestinationException if an invalid destination is
1510     *                 specified
1511     * @throws InvalidSelectorException if the message selector is invalid.
1512     * @since 1.1
1513     */
1514    @Override
1515    public QueueBrowser createBrowser(Queue queue, String messageSelector) throws JMSException {
1516        checkClosed();
1517        return new ActiveMQQueueBrowser(this, getNextConsumerId(), ActiveMQMessageTransformation.transformDestination(queue), messageSelector, asyncDispatch);
1518    }
1519
1520    /**
1521     * Creates a <CODE>TemporaryQueue</CODE> object. Its lifetime will be that
1522     * of the <CODE>Connection</CODE> unless it is deleted earlier.
1523     *
1524     * @return a temporary queue identity
1525     * @throws JMSException if the session fails to create a temporary queue due
1526     *                 to some internal error.
1527     * @since 1.1
1528     */
1529    @Override
1530    public TemporaryQueue createTemporaryQueue() throws JMSException {
1531        checkClosed();
1532        return (TemporaryQueue)connection.createTempDestination(false);
1533    }
1534
1535    /**
1536     * Creates a <CODE>TemporaryTopic</CODE> object. Its lifetime will be that
1537     * of the <CODE>Connection</CODE> unless it is deleted earlier.
1538     *
1539     * @return a temporary topic identity
1540     * @throws JMSException if the session fails to create a temporary topic due
1541     *                 to some internal error.
1542     * @since 1.1
1543     */
1544    @Override
1545    public TemporaryTopic createTemporaryTopic() throws JMSException {
1546        checkClosed();
1547        return (TemporaryTopic)connection.createTempDestination(true);
1548    }
1549
1550    /**
1551     * Creates a <CODE>QueueReceiver</CODE> object to receive messages from
1552     * the specified queue.
1553     *
1554     * @param queue the <CODE>Queue</CODE> to access
1555     * @return a new QueueBrowser instance.
1556     * @throws JMSException if the session fails to create a receiver due to
1557     *                 some internal error.
1558     * @throws JMSException
1559     * @throws InvalidDestinationException if an invalid queue is specified.
1560     */
1561    @Override
1562    public QueueReceiver createReceiver(Queue queue) throws JMSException {
1563        checkClosed();
1564        return createReceiver(queue, null);
1565    }
1566
1567    /**
1568     * Creates a <CODE>QueueReceiver</CODE> object to receive messages from
1569     * the specified queue using a message selector.
1570     *
1571     * @param queue the <CODE>Queue</CODE> to access
1572     * @param messageSelector only messages with properties matching the message
1573     *                selector expression are delivered. A value of null or an
1574     *                empty string indicates that there is no message selector
1575     *                for the message consumer.
1576     * @return QueueReceiver
1577     * @throws JMSException if the session fails to create a receiver due to
1578     *                 some internal error.
1579     * @throws InvalidDestinationException if an invalid queue is specified.
1580     * @throws InvalidSelectorException if the message selector is invalid.
1581     */
1582    @Override
1583    public QueueReceiver createReceiver(Queue queue, String messageSelector) throws JMSException {
1584        checkClosed();
1585
1586        if (queue instanceof CustomDestination) {
1587            CustomDestination customDestination = (CustomDestination)queue;
1588            return customDestination.createReceiver(this, messageSelector);
1589        }
1590
1591        ActiveMQPrefetchPolicy prefetchPolicy = this.connection.getPrefetchPolicy();
1592        return new ActiveMQQueueReceiver(this, getNextConsumerId(), ActiveMQMessageTransformation.transformDestination(queue), messageSelector, prefetchPolicy.getQueuePrefetch(),
1593                                         prefetchPolicy.getMaximumPendingMessageLimit(), asyncDispatch);
1594    }
1595
1596    /**
1597     * Creates a <CODE>QueueSender</CODE> object to send messages to the
1598     * specified queue.
1599     *
1600     * @param queue the <CODE>Queue</CODE> to access, or null if this is an
1601     *                unidentified producer
1602     * @return QueueSender
1603     * @throws JMSException if the session fails to create a sender due to some
1604     *                 internal error.
1605     * @throws InvalidDestinationException if an invalid queue is specified.
1606     */
1607    @Override
1608    public QueueSender createSender(Queue queue) throws JMSException {
1609        checkClosed();
1610        if (queue instanceof CustomDestination) {
1611            CustomDestination customDestination = (CustomDestination)queue;
1612            return customDestination.createSender(this);
1613        }
1614        int timeSendOut = connection.getSendTimeout();
1615        return new ActiveMQQueueSender(this, ActiveMQMessageTransformation.transformDestination(queue),timeSendOut);
1616    }
1617
1618    /**
1619     * Creates a nondurable subscriber to the specified topic. <p/>
1620     * <P>
1621     * A client uses a <CODE>TopicSubscriber</CODE> object to receive messages
1622     * that have been published to a topic. <p/>
1623     * <P>
1624     * Regular <CODE>TopicSubscriber</CODE> objects are not durable. They
1625     * receive only messages that are published while they are active. <p/>
1626     * <P>
1627     * In some cases, a connection may both publish and subscribe to a topic.
1628     * The subscriber <CODE>NoLocal</CODE> attribute allows a subscriber to
1629     * inhibit the delivery of messages published by its own connection. The
1630     * default value for this attribute is false.
1631     *
1632     * @param topic the <CODE>Topic</CODE> to subscribe to
1633     * @return TopicSubscriber
1634     * @throws JMSException if the session fails to create a subscriber due to
1635     *                 some internal error.
1636     * @throws InvalidDestinationException if an invalid topic is specified.
1637     */
1638    @Override
1639    public TopicSubscriber createSubscriber(Topic topic) throws JMSException {
1640        checkClosed();
1641        return createSubscriber(topic, null, false);
1642    }
1643
1644    /**
1645     * Creates a nondurable subscriber to the specified topic, using a message
1646     * selector or specifying whether messages published by its own connection
1647     * should be delivered to it. <p/>
1648     * <P>
1649     * A client uses a <CODE>TopicSubscriber</CODE> object to receive messages
1650     * that have been published to a topic. <p/>
1651     * <P>
1652     * Regular <CODE>TopicSubscriber</CODE> objects are not durable. They
1653     * receive only messages that are published while they are active. <p/>
1654     * <P>
1655     * Messages filtered out by a subscriber's message selector will never be
1656     * delivered to the subscriber. From the subscriber's perspective, they do
1657     * not exist. <p/>
1658     * <P>
1659     * In some cases, a connection may both publish and subscribe to a topic.
1660     * The subscriber <CODE>NoLocal</CODE> attribute allows a subscriber to
1661     * inhibit the delivery of messages published by its own connection. The
1662     * default value for this attribute is false.
1663     *
1664     * @param topic the <CODE>Topic</CODE> to subscribe to
1665     * @param messageSelector only messages with properties matching the message
1666     *                selector expression are delivered. A value of null or an
1667     *                empty string indicates that there is no message selector
1668     *                for the message consumer.
1669     * @param noLocal if set, inhibits the delivery of messages published by its
1670     *                own connection
1671     * @return TopicSubscriber
1672     * @throws JMSException if the session fails to create a subscriber due to
1673     *                 some internal error.
1674     * @throws InvalidDestinationException if an invalid topic is specified.
1675     * @throws InvalidSelectorException if the message selector is invalid.
1676     */
1677    @Override
1678    public TopicSubscriber createSubscriber(Topic topic, String messageSelector, boolean noLocal) throws JMSException {
1679        checkClosed();
1680
1681        if (topic instanceof CustomDestination) {
1682            CustomDestination customDestination = (CustomDestination)topic;
1683            return customDestination.createSubscriber(this, messageSelector, noLocal);
1684        }
1685
1686        ActiveMQPrefetchPolicy prefetchPolicy = this.connection.getPrefetchPolicy();
1687        return new ActiveMQTopicSubscriber(this, getNextConsumerId(), ActiveMQMessageTransformation.transformDestination(topic), null, messageSelector, prefetchPolicy
1688            .getTopicPrefetch(), prefetchPolicy.getMaximumPendingMessageLimit(), noLocal, false, asyncDispatch);
1689    }
1690
1691    /**
1692     * Creates a publisher for the specified topic. <p/>
1693     * <P>
1694     * A client uses a <CODE>TopicPublisher</CODE> object to publish messages
1695     * on a topic. Each time a client creates a <CODE>TopicPublisher</CODE> on
1696     * a topic, it defines a new sequence of messages that have no ordering
1697     * relationship with the messages it has previously sent.
1698     *
1699     * @param topic the <CODE>Topic</CODE> to publish to, or null if this is
1700     *                an unidentified producer
1701     * @return TopicPublisher
1702     * @throws JMSException if the session fails to create a publisher due to
1703     *                 some internal error.
1704     * @throws InvalidDestinationException if an invalid topic is specified.
1705     */
1706    @Override
1707    public TopicPublisher createPublisher(Topic topic) throws JMSException {
1708        checkClosed();
1709
1710        if (topic instanceof CustomDestination) {
1711            CustomDestination customDestination = (CustomDestination)topic;
1712            return customDestination.createPublisher(this);
1713        }
1714        int timeSendOut = connection.getSendTimeout();
1715        return new ActiveMQTopicPublisher(this, ActiveMQMessageTransformation.transformDestination(topic),timeSendOut);
1716    }
1717
1718    /**
1719     * Unsubscribes a durable subscription that has been created by a client.
1720     * <P>
1721     * This method deletes the state being maintained on behalf of the
1722     * subscriber by its provider.
1723     * <P>
1724     * It is erroneous for a client to delete a durable subscription while there
1725     * is an active <CODE>MessageConsumer </CODE> or
1726     * <CODE>TopicSubscriber</CODE> for the subscription, or while a consumed
1727     * message is part of a pending transaction or has not been acknowledged in
1728     * the session.
1729     *
1730     * @param name the name used to identify this subscription
1731     * @throws JMSException if the session fails to unsubscribe to the durable
1732     *                 subscription due to some internal error.
1733     * @throws InvalidDestinationException if an invalid subscription name is
1734     *                 specified.
1735     * @since 1.1
1736     */
1737    @Override
1738    public void unsubscribe(String name) throws JMSException {
1739        checkClosed();
1740        connection.unsubscribe(name);
1741    }
1742
1743    @Override
1744    public void dispatch(MessageDispatch messageDispatch) {
1745        try {
1746            executor.execute(messageDispatch);
1747        } catch (InterruptedException e) {
1748            Thread.currentThread().interrupt();
1749            connection.onClientInternalException(e);
1750        }
1751    }
1752
1753    /**
1754     * Acknowledges all consumed messages of the session of this consumed
1755     * message.
1756     * <P>
1757     * All consumed JMS messages support the <CODE>acknowledge</CODE> method
1758     * for use when a client has specified that its JMS session's consumed
1759     * messages are to be explicitly acknowledged. By invoking
1760     * <CODE>acknowledge</CODE> on a consumed message, a client acknowledges
1761     * all messages consumed by the session that the message was delivered to.
1762     * <P>
1763     * Calls to <CODE>acknowledge</CODE> are ignored for both transacted
1764     * sessions and sessions specified to use implicit acknowledgement modes.
1765     * <P>
1766     * A client may individually acknowledge each message as it is consumed, or
1767     * it may choose to acknowledge messages as an application-defined group
1768     * (which is done by calling acknowledge on the last received message of the
1769     * group, thereby acknowledging all messages consumed by the session.)
1770     * <P>
1771     * Messages that have been received but not acknowledged may be redelivered.
1772     *
1773     * @throws JMSException if the JMS provider fails to acknowledge the
1774     *                 messages due to some internal error.
1775     * @throws javax.jms.IllegalStateException if this method is called on a
1776     *                 closed session.
1777     * @see javax.jms.Session#CLIENT_ACKNOWLEDGE
1778     */
1779    public void acknowledge() throws JMSException {
1780        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
1781            ActiveMQMessageConsumer c = iter.next();
1782            c.acknowledge();
1783        }
1784    }
1785
1786    /**
1787     * Add a message consumer.
1788     *
1789     * @param consumer - message consumer.
1790     * @throws JMSException
1791     */
1792    protected void addConsumer(ActiveMQMessageConsumer consumer) throws JMSException {
1793        this.consumers.add(consumer);
1794        if (consumer.isDurableSubscriber()) {
1795            stats.onCreateDurableSubscriber();
1796        }
1797        this.connection.addDispatcher(consumer.getConsumerId(), this);
1798    }
1799
1800    /**
1801     * Remove the message consumer.
1802     *
1803     * @param consumer - consumer to be removed.
1804     * @throws JMSException
1805     */
1806    protected void removeConsumer(ActiveMQMessageConsumer consumer) {
1807        this.connection.removeDispatcher(consumer.getConsumerId());
1808        if (consumer.isDurableSubscriber()) {
1809            stats.onRemoveDurableSubscriber();
1810        }
1811        this.consumers.remove(consumer);
1812        this.connection.removeDispatcher(consumer);
1813    }
1814
1815    /**
1816     * Adds a message producer.
1817     *
1818     * @param producer - message producer to be added.
1819     * @throws JMSException
1820     */
1821    protected void addProducer(ActiveMQMessageProducer producer) throws JMSException {
1822        this.producers.add(producer);
1823        this.connection.addProducer(producer.getProducerInfo().getProducerId(), producer);
1824    }
1825
1826    /**
1827     * Removes a message producer.
1828     *
1829     * @param producer - message producer to be removed.
1830     * @throws JMSException
1831     */
1832    protected void removeProducer(ActiveMQMessageProducer producer) {
1833        this.connection.removeProducer(producer.getProducerInfo().getProducerId());
1834        this.producers.remove(producer);
1835    }
1836
1837    /**
1838     * Start this Session.
1839     *
1840     * @throws JMSException
1841     */
1842    protected void start() throws JMSException {
1843        started.set(true);
1844        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
1845            ActiveMQMessageConsumer c = iter.next();
1846            c.start();
1847        }
1848        executor.start();
1849    }
1850
1851    /**
1852     * Stops this session.
1853     *
1854     * @throws JMSException
1855     */
1856    protected void stop() throws JMSException {
1857
1858        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
1859            ActiveMQMessageConsumer c = iter.next();
1860            c.stop();
1861        }
1862
1863        started.set(false);
1864        executor.stop();
1865    }
1866
1867    /**
1868     * Returns the session id.
1869     *
1870     * @return value - session id.
1871     */
1872    protected SessionId getSessionId() {
1873        return info.getSessionId();
1874    }
1875
1876    /**
1877     * @return a unique ConsumerId instance.
1878     */
1879    protected ConsumerId getNextConsumerId() {
1880        return new ConsumerId(info.getSessionId(), consumerIdGenerator.getNextSequenceId());
1881    }
1882
1883    /**
1884     * @return a unique ProducerId instance.
1885     */
1886    protected ProducerId getNextProducerId() {
1887        return new ProducerId(info.getSessionId(), producerIdGenerator.getNextSequenceId());
1888    }
1889
1890    /**
1891     * Sends the message for dispatch by the broker.
1892     *
1893     * @param producer - message producer.
1894     * @param destination - message destination.
1895     * @param message - message to be sent.
1896     * @param deliveryMode - JMS message delivery mode.
1897     * @param priority - message priority.
1898     * @param timeToLive - message expiration.
1899     * @param producerWindow
1900     * @param onComplete
1901     * @throws JMSException
1902     */
1903    protected void send(ActiveMQMessageProducer producer, ActiveMQDestination destination, Message message, int deliveryMode, int priority, long timeToLive,
1904                        MemoryUsage producerWindow, int sendTimeout, AsyncCallback onComplete) throws JMSException {
1905
1906        checkClosed();
1907        if (destination.isTemporary() && connection.isDeleted(destination)) {
1908            throw new InvalidDestinationException("Cannot publish to a deleted Destination: " + destination);
1909        }
1910        synchronized (sendMutex) {
1911            // tell the Broker we are about to start a new transaction
1912            doStartTransaction();
1913            TransactionId txid = transactionContext.getTransactionId();
1914            long sequenceNumber = producer.getMessageSequence();
1915
1916            //Set the "JMS" header fields on the original message, see 1.1 spec section 3.4.11
1917            message.setJMSDeliveryMode(deliveryMode);
1918            long expiration = 0L;
1919            if (!producer.getDisableMessageTimestamp()) {
1920                long timeStamp = System.currentTimeMillis();
1921                message.setJMSTimestamp(timeStamp);
1922                if (timeToLive > 0) {
1923                    expiration = timeToLive + timeStamp;
1924                }
1925            }
1926            message.setJMSExpiration(expiration);
1927            message.setJMSPriority(priority);
1928            message.setJMSRedelivered(false);
1929
1930            // transform to our own message format here
1931            ActiveMQMessage msg = ActiveMQMessageTransformation.transformMessage(message, connection);
1932            msg.setDestination(destination);
1933            msg.setMessageId(new MessageId(producer.getProducerInfo().getProducerId(), sequenceNumber));
1934
1935            // Set the message id.
1936            if (msg != message) {
1937                message.setJMSMessageID(msg.getMessageId().toString());
1938                // Make sure the JMS destination is set on the foreign messages too.
1939                message.setJMSDestination(destination);
1940            }
1941            //clear the brokerPath in case we are re-sending this message
1942            msg.setBrokerPath(null);
1943
1944            msg.setTransactionId(txid);
1945            if (connection.isCopyMessageOnSend()) {
1946                msg = (ActiveMQMessage)msg.copy();
1947            }
1948            msg.setConnection(connection);
1949            msg.onSend();
1950            msg.setProducerId(msg.getMessageId().getProducerId());
1951            if (LOG.isTraceEnabled()) {
1952                LOG.trace(getSessionId() + " sending message: " + msg);
1953            }
1954            if (onComplete==null && sendTimeout <= 0 && !msg.isResponseRequired() && !connection.isAlwaysSyncSend() && (!msg.isPersistent() || connection.isUseAsyncSend() || txid != null)) {
1955                this.connection.asyncSendPacket(msg);
1956                if (producerWindow != null) {
1957                    // Since we defer lots of the marshaling till we hit the
1958                    // wire, this might not
1959                    // provide and accurate size. We may change over to doing
1960                    // more aggressive marshaling,
1961                    // to get more accurate sizes.. this is more important once
1962                    // users start using producer window
1963                    // flow control.
1964                    int size = msg.getSize();
1965                    producerWindow.increaseUsage(size);
1966                }
1967            } else {
1968                if (sendTimeout > 0 && onComplete==null) {
1969                    this.connection.syncSendPacket(msg,sendTimeout);
1970                }else {
1971                    this.connection.syncSendPacket(msg, onComplete);
1972                }
1973            }
1974
1975        }
1976    }
1977
1978    /**
1979     * Send TransactionInfo to indicate transaction has started
1980     *
1981     * @throws JMSException if some internal error occurs
1982     */
1983    protected void doStartTransaction() throws JMSException {
1984        if (getTransacted() && !transactionContext.isInXATransaction()) {
1985            transactionContext.begin();
1986        }
1987    }
1988
1989    /**
1990     * Checks whether the session has unconsumed messages.
1991     *
1992     * @return true - if there are unconsumed messages.
1993     */
1994    public boolean hasUncomsumedMessages() {
1995        return executor.hasUncomsumedMessages();
1996    }
1997
1998    /**
1999     * Checks whether the session uses transactions.
2000     *
2001     * @return true - if the session uses transactions.
2002     */
2003    public boolean isTransacted() {
2004        return this.acknowledgementMode == Session.SESSION_TRANSACTED || (transactionContext.isInXATransaction());
2005    }
2006
2007    /**
2008     * Checks whether the session used client acknowledgment.
2009     *
2010     * @return true - if the session uses client acknowledgment.
2011     */
2012    protected boolean isClientAcknowledge() {
2013        return this.acknowledgementMode == Session.CLIENT_ACKNOWLEDGE;
2014    }
2015
2016    /**
2017     * Checks whether the session used auto acknowledgment.
2018     *
2019     * @return true - if the session uses client acknowledgment.
2020     */
2021    public boolean isAutoAcknowledge() {
2022        return acknowledgementMode == Session.AUTO_ACKNOWLEDGE;
2023    }
2024
2025    /**
2026     * Checks whether the session used dup ok acknowledgment.
2027     *
2028     * @return true - if the session uses client acknowledgment.
2029     */
2030    public boolean isDupsOkAcknowledge() {
2031        return acknowledgementMode == Session.DUPS_OK_ACKNOWLEDGE;
2032    }
2033
2034    public boolean isIndividualAcknowledge(){
2035        return acknowledgementMode == ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE;
2036    }
2037
2038    /**
2039     * Returns the message delivery listener.
2040     *
2041     * @return deliveryListener - message delivery listener.
2042     */
2043    public DeliveryListener getDeliveryListener() {
2044        return deliveryListener;
2045    }
2046
2047    /**
2048     * Sets the message delivery listener.
2049     *
2050     * @param deliveryListener - message delivery listener.
2051     */
2052    public void setDeliveryListener(DeliveryListener deliveryListener) {
2053        this.deliveryListener = deliveryListener;
2054    }
2055
2056    /**
2057     * Returns the SessionInfo bean.
2058     *
2059     * @return info - SessionInfo bean.
2060     * @throws JMSException
2061     */
2062    protected SessionInfo getSessionInfo() throws JMSException {
2063        SessionInfo info = new SessionInfo(connection.getConnectionInfo(), getSessionId().getValue());
2064        return info;
2065    }
2066
2067    /**
2068     * Send the asynchronous command.
2069     *
2070     * @param command - command to be executed.
2071     * @throws JMSException
2072     */
2073    public void asyncSendPacket(Command command) throws JMSException {
2074        connection.asyncSendPacket(command);
2075    }
2076
2077    /**
2078     * Send the synchronous command.
2079     *
2080     * @param command - command to be executed.
2081     * @return Response
2082     * @throws JMSException
2083     */
2084    public Response syncSendPacket(Command command) throws JMSException {
2085        return connection.syncSendPacket(command);
2086    }
2087
2088    public long getNextDeliveryId() {
2089        return deliveryIdGenerator.getNextSequenceId();
2090    }
2091
2092    public void redispatch(ActiveMQDispatcher dispatcher, MessageDispatchChannel unconsumedMessages) throws JMSException {
2093
2094        List<MessageDispatch> c = unconsumedMessages.removeAll();
2095        for (MessageDispatch md : c) {
2096            this.connection.rollbackDuplicate(dispatcher, md.getMessage());
2097        }
2098        Collections.reverse(c);
2099
2100        for (Iterator<MessageDispatch> iter = c.iterator(); iter.hasNext();) {
2101            MessageDispatch md = iter.next();
2102            executor.executeFirst(md);
2103        }
2104
2105    }
2106
2107    public boolean isRunning() {
2108        return started.get();
2109    }
2110
2111    public boolean isAsyncDispatch() {
2112        return asyncDispatch;
2113    }
2114
2115    public void setAsyncDispatch(boolean asyncDispatch) {
2116        this.asyncDispatch = asyncDispatch;
2117    }
2118
2119    /**
2120     * @return Returns the sessionAsyncDispatch.
2121     */
2122    public boolean isSessionAsyncDispatch() {
2123        return sessionAsyncDispatch;
2124    }
2125
2126    /**
2127     * @param sessionAsyncDispatch The sessionAsyncDispatch to set.
2128     */
2129    public void setSessionAsyncDispatch(boolean sessionAsyncDispatch) {
2130        this.sessionAsyncDispatch = sessionAsyncDispatch;
2131    }
2132
2133    public MessageTransformer getTransformer() {
2134        return transformer;
2135    }
2136
2137    public ActiveMQConnection getConnection() {
2138        return connection;
2139    }
2140
2141    /**
2142     * Sets the transformer used to transform messages before they are sent on
2143     * to the JMS bus or when they are received from the bus but before they are
2144     * delivered to the JMS client
2145     */
2146    public void setTransformer(MessageTransformer transformer) {
2147        this.transformer = transformer;
2148    }
2149
2150    public BlobTransferPolicy getBlobTransferPolicy() {
2151        return blobTransferPolicy;
2152    }
2153
2154    /**
2155     * Sets the policy used to describe how out-of-band BLOBs (Binary Large
2156     * OBjects) are transferred from producers to brokers to consumers
2157     */
2158    public void setBlobTransferPolicy(BlobTransferPolicy blobTransferPolicy) {
2159        this.blobTransferPolicy = blobTransferPolicy;
2160    }
2161
2162    public List<MessageDispatch> getUnconsumedMessages() {
2163        return executor.getUnconsumedMessages();
2164    }
2165
2166    @Override
2167    public String toString() {
2168        return "ActiveMQSession {id=" + info.getSessionId() + ",started=" + started.get() + "} " + sendMutex;
2169    }
2170
2171    public void checkMessageListener() throws JMSException {
2172        if (messageListener != null) {
2173            throw new IllegalStateException("Cannot synchronously receive a message when a MessageListener is set");
2174        }
2175        for (Iterator<ActiveMQMessageConsumer> i = consumers.iterator(); i.hasNext();) {
2176            ActiveMQMessageConsumer consumer = i.next();
2177            if (consumer.hasMessageListener()) {
2178                throw new IllegalStateException("Cannot synchronously receive a message when a MessageListener is set");
2179            }
2180        }
2181    }
2182
2183    protected void setOptimizeAcknowledge(boolean value) {
2184        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
2185            ActiveMQMessageConsumer c = iter.next();
2186            c.setOptimizeAcknowledge(value);
2187        }
2188    }
2189
2190    protected void setPrefetchSize(ConsumerId id, int prefetch) {
2191        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
2192            ActiveMQMessageConsumer c = iter.next();
2193            if (c.getConsumerId().equals(id)) {
2194                c.setPrefetchSize(prefetch);
2195                break;
2196            }
2197        }
2198    }
2199
2200    protected void close(ConsumerId id) {
2201        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
2202            ActiveMQMessageConsumer c = iter.next();
2203            if (c.getConsumerId().equals(id)) {
2204                try {
2205                    c.close();
2206                } catch (JMSException e) {
2207                    LOG.warn("Exception closing consumer", e);
2208                }
2209                LOG.warn("Closed consumer on Command, " + id);
2210                break;
2211            }
2212        }
2213    }
2214
2215    public boolean isInUse(ActiveMQTempDestination destination) {
2216        for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
2217            ActiveMQMessageConsumer c = iter.next();
2218            if (c.isInUse(destination)) {
2219                return true;
2220            }
2221        }
2222        return false;
2223    }
2224
2225    /**
2226     * highest sequence id of the last message delivered by this session.
2227     * Passed to the broker in the close command, maintained by dispose()
2228     * @return lastDeliveredSequenceId
2229     */
2230    public long getLastDeliveredSequenceId() {
2231        return lastDeliveredSequenceId;
2232    }
2233
2234    protected void sendAck(MessageAck ack) throws JMSException {
2235        sendAck(ack,false);
2236    }
2237
2238    protected void sendAck(MessageAck ack, boolean lazy) throws JMSException {
2239        if (lazy || connection.isSendAcksAsync() || getTransacted()) {
2240            asyncSendPacket(ack);
2241        } else {
2242            syncSendPacket(ack);
2243        }
2244    }
2245
2246    protected Scheduler getScheduler() throws JMSException {
2247        return this.connection.getScheduler();
2248    }
2249
2250    protected ThreadPoolExecutor getConnectionExecutor() {
2251        return this.connectionExecutor;
2252    }
2253}