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.IOException;
020import java.util.ArrayList;
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.Iterator;
024import java.util.LinkedList;
025import java.util.List;
026import java.util.Map;
027import java.util.Map.Entry;
028import java.util.concurrent.ExecutorService;
029import java.util.concurrent.Executors;
030import java.util.concurrent.atomic.AtomicBoolean;
031import java.util.concurrent.atomic.AtomicInteger;
032import java.util.concurrent.atomic.AtomicReference;
033
034import javax.jms.IllegalStateException;
035import javax.jms.InvalidDestinationException;
036import javax.jms.JMSException;
037import javax.jms.Message;
038import javax.jms.MessageConsumer;
039import javax.jms.MessageListener;
040import javax.jms.TransactionRolledBackException;
041
042import org.apache.activemq.blob.BlobDownloader;
043import org.apache.activemq.command.ActiveMQBlobMessage;
044import org.apache.activemq.command.ActiveMQDestination;
045import org.apache.activemq.command.ActiveMQMessage;
046import org.apache.activemq.command.ActiveMQObjectMessage;
047import org.apache.activemq.command.ActiveMQTempDestination;
048import org.apache.activemq.command.CommandTypes;
049import org.apache.activemq.command.ConsumerId;
050import org.apache.activemq.command.ConsumerInfo;
051import org.apache.activemq.command.MessageAck;
052import org.apache.activemq.command.MessageDispatch;
053import org.apache.activemq.command.MessageId;
054import org.apache.activemq.command.MessagePull;
055import org.apache.activemq.command.RemoveInfo;
056import org.apache.activemq.command.TransactionId;
057import org.apache.activemq.management.JMSConsumerStatsImpl;
058import org.apache.activemq.management.StatsCapable;
059import org.apache.activemq.management.StatsImpl;
060import org.apache.activemq.selector.SelectorParser;
061import org.apache.activemq.transaction.Synchronization;
062import org.apache.activemq.util.Callback;
063import org.apache.activemq.util.IntrospectionSupport;
064import org.apache.activemq.util.JMSExceptionSupport;
065import org.apache.activemq.util.ThreadPoolUtils;
066import org.slf4j.Logger;
067import org.slf4j.LoggerFactory;
068
069/**
070 * A client uses a <CODE>MessageConsumer</CODE> object to receive messages
071 * from a destination. A <CODE> MessageConsumer</CODE> object is created by
072 * passing a <CODE>Destination</CODE> object to a message-consumer creation
073 * method supplied by a session.
074 * <P>
075 * <CODE>MessageConsumer</CODE> is the parent interface for all message
076 * consumers.
077 * <P>
078 * A message consumer can be created with a message selector. A message selector
079 * allows the client to restrict the messages delivered to the message consumer
080 * to those that match the selector.
081 * <P>
082 * A client may either synchronously receive a message consumer's messages or
083 * have the consumer asynchronously deliver them as they arrive.
084 * <P>
085 * For synchronous receipt, a client can request the next message from a message
086 * consumer using one of its <CODE> receive</CODE> methods. There are several
087 * variations of <CODE>receive</CODE> that allow a client to poll or wait for
088 * the next message.
089 * <P>
090 * For asynchronous delivery, a client can register a
091 * <CODE>MessageListener</CODE> object with a message consumer. As messages
092 * arrive at the message consumer, it delivers them by calling the
093 * <CODE>MessageListener</CODE>'s<CODE>
094 * onMessage</CODE> method.
095 * <P>
096 * It is a client programming error for a <CODE>MessageListener</CODE> to
097 * throw an exception.
098 *
099 *
100 * @see javax.jms.MessageConsumer
101 * @see javax.jms.QueueReceiver
102 * @see javax.jms.TopicSubscriber
103 * @see javax.jms.Session
104 */
105public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsCapable, ActiveMQDispatcher {
106
107    @SuppressWarnings("serial")
108    class PreviouslyDeliveredMap<K, V> extends HashMap<K, V> {
109        final TransactionId transactionId;
110        public PreviouslyDeliveredMap(TransactionId transactionId) {
111            this.transactionId = transactionId;
112        }
113    }
114
115    private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageConsumer.class);
116    protected final ActiveMQSession session;
117    protected final ConsumerInfo info;
118
119    // These are the messages waiting to be delivered to the client
120    protected final MessageDispatchChannel unconsumedMessages;
121
122    // The are the messages that were delivered to the consumer but that have
123    // not been acknowledged. It's kept in reverse order since we
124    // Always walk list in reverse order.
125    protected final LinkedList<MessageDispatch> deliveredMessages = new LinkedList<MessageDispatch>();
126    // track duplicate deliveries in a transaction such that the tx integrity can be validated
127    private PreviouslyDeliveredMap<MessageId, Boolean> previouslyDeliveredMessages;
128    private int deliveredCounter;
129    private int additionalWindowSize;
130    private long redeliveryDelay;
131    private int ackCounter;
132    private int dispatchedCount;
133    private final AtomicReference<MessageListener> messageListener = new AtomicReference<MessageListener>();
134    private final JMSConsumerStatsImpl stats;
135
136    private final String selector;
137    private boolean synchronizationRegistered;
138    private final AtomicBoolean started = new AtomicBoolean(false);
139
140    private MessageAvailableListener availableListener;
141
142    private RedeliveryPolicy redeliveryPolicy;
143    private boolean optimizeAcknowledge;
144    private final AtomicBoolean deliveryingAcknowledgements = new AtomicBoolean();
145    private ExecutorService executorService;
146    private MessageTransformer transformer;
147    private boolean clearDeliveredList;
148    AtomicInteger inProgressClearRequiredFlag = new AtomicInteger(0);
149
150    private MessageAck pendingAck;
151    private long lastDeliveredSequenceId = -1;
152
153    private IOException failureError;
154
155    private long optimizeAckTimestamp = System.currentTimeMillis();
156    private long optimizeAcknowledgeTimeOut = 0;
157    private long optimizedAckScheduledAckInterval = 0;
158    private Runnable optimizedAckTask;
159    private long failoverRedeliveryWaitPeriod = 0;
160    private boolean transactedIndividualAck = false;
161    private boolean nonBlockingRedelivery = false;
162    private boolean consumerExpiryCheckEnabled = true;
163
164    /**
165     * Create a MessageConsumer
166     *
167     * @param session
168     * @param dest
169     * @param name
170     * @param selector
171     * @param prefetch
172     * @param maximumPendingMessageCount
173     * @param noLocal
174     * @param browser
175     * @param dispatchAsync
176     * @param messageListener
177     * @throws JMSException
178     */
179    public ActiveMQMessageConsumer(ActiveMQSession session, ConsumerId consumerId, ActiveMQDestination dest,
180            String name, String selector, int prefetch,
181            int maximumPendingMessageCount, boolean noLocal, boolean browser,
182            boolean dispatchAsync, MessageListener messageListener) throws JMSException {
183        if (dest == null) {
184            throw new InvalidDestinationException("Don't understand null destinations");
185        } else if (dest.getPhysicalName() == null) {
186            throw new InvalidDestinationException("The destination object was not given a physical name.");
187        } else if (dest.isTemporary()) {
188            String physicalName = dest.getPhysicalName();
189
190            if (physicalName == null) {
191                throw new IllegalArgumentException("Physical name of Destination should be valid: " + dest);
192            }
193
194            String connectionID = session.connection.getConnectionInfo().getConnectionId().getValue();
195
196            if (physicalName.indexOf(connectionID) < 0) {
197                throw new InvalidDestinationException("Cannot use a Temporary destination from another Connection");
198            }
199
200            if (session.connection.isDeleted(dest)) {
201                throw new InvalidDestinationException("Cannot use a Temporary destination that has been deleted");
202            }
203            if (prefetch < 0) {
204                throw new JMSException("Cannot have a prefetch size less than zero");
205            }
206        }
207        if (session.connection.isMessagePrioritySupported()) {
208            this.unconsumedMessages = new SimplePriorityMessageDispatchChannel();
209        }else {
210            this.unconsumedMessages = new FifoMessageDispatchChannel();
211        }
212
213        this.session = session;
214        this.redeliveryPolicy = session.connection.getRedeliveryPolicyMap().getEntryFor(dest);
215        if (this.redeliveryPolicy == null) {
216            this.redeliveryPolicy = new RedeliveryPolicy();
217        }
218        setTransformer(session.getTransformer());
219
220        this.info = new ConsumerInfo(consumerId);
221        this.info.setExclusive(this.session.connection.isExclusiveConsumer());
222        this.info.setClientId(this.session.connection.getClientID());
223        this.info.setSubscriptionName(name);
224        this.info.setPrefetchSize(prefetch);
225        this.info.setCurrentPrefetchSize(prefetch);
226        this.info.setMaximumPendingMessageLimit(maximumPendingMessageCount);
227        this.info.setNoLocal(noLocal);
228        this.info.setDispatchAsync(dispatchAsync);
229        this.info.setRetroactive(this.session.connection.isUseRetroactiveConsumer());
230        this.info.setSelector(null);
231
232        // Allows the options on the destination to configure the consumerInfo
233        if (dest.getOptions() != null) {
234            Map<String, Object> options = IntrospectionSupport.extractProperties(
235                new HashMap<String, Object>(dest.getOptions()), "consumer.");
236            IntrospectionSupport.setProperties(this.info, options);
237            if (options.size() > 0) {
238                String msg = "There are " + options.size()
239                    + " consumer options that couldn't be set on the consumer."
240                    + " Check the options are spelled correctly."
241                    + " Unknown parameters=[" + options + "]."
242                    + " This consumer cannot be started.";
243                LOG.warn(msg);
244                throw new ConfigurationException(msg);
245            }
246        }
247
248        this.info.setDestination(dest);
249        this.info.setBrowser(browser);
250        if (selector != null && selector.trim().length() != 0) {
251            // Validate the selector
252            SelectorParser.parse(selector);
253            this.info.setSelector(selector);
254            this.selector = selector;
255        } else if (info.getSelector() != null) {
256            // Validate the selector
257            SelectorParser.parse(this.info.getSelector());
258            this.selector = this.info.getSelector();
259        } else {
260            this.selector = null;
261        }
262
263        this.stats = new JMSConsumerStatsImpl(session.getSessionStats(), dest);
264        this.optimizeAcknowledge = session.connection.isOptimizeAcknowledge() && session.isAutoAcknowledge()
265                                   && !info.isBrowser();
266        if (this.optimizeAcknowledge) {
267            this.optimizeAcknowledgeTimeOut = session.connection.getOptimizeAcknowledgeTimeOut();
268            setOptimizedAckScheduledAckInterval(session.connection.getOptimizedAckScheduledAckInterval());
269        }
270
271        this.info.setOptimizedAcknowledge(this.optimizeAcknowledge);
272        this.failoverRedeliveryWaitPeriod = session.connection.getConsumerFailoverRedeliveryWaitPeriod();
273        this.nonBlockingRedelivery = session.connection.isNonBlockingRedelivery();
274        this.transactedIndividualAck = session.connection.isTransactedIndividualAck()
275                        || this.nonBlockingRedelivery
276                        || session.connection.isMessagePrioritySupported();
277        this.consumerExpiryCheckEnabled = session.connection.isConsumerExpiryCheckEnabled();
278        if (messageListener != null) {
279            setMessageListener(messageListener);
280        }
281        try {
282            this.session.addConsumer(this);
283            this.session.syncSendPacket(info);
284        } catch (JMSException e) {
285            this.session.removeConsumer(this);
286            throw e;
287        }
288
289        if (session.connection.isStarted()) {
290            start();
291        }
292    }
293
294    private boolean isAutoAcknowledgeEach() {
295        return session.isAutoAcknowledge() || ( session.isDupsOkAcknowledge() && getDestination().isQueue() );
296    }
297
298    private boolean isAutoAcknowledgeBatch() {
299        return session.isDupsOkAcknowledge() && !getDestination().isQueue() ;
300    }
301
302    @Override
303    public StatsImpl getStats() {
304        return stats;
305    }
306
307    public JMSConsumerStatsImpl getConsumerStats() {
308        return stats;
309    }
310
311    public RedeliveryPolicy getRedeliveryPolicy() {
312        return redeliveryPolicy;
313    }
314
315    /**
316     * Sets the redelivery policy used when messages are redelivered
317     */
318    public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) {
319        this.redeliveryPolicy = redeliveryPolicy;
320    }
321
322    public MessageTransformer getTransformer() {
323        return transformer;
324    }
325
326    /**
327     * Sets the transformer used to transform messages before they are sent on
328     * to the JMS bus
329     */
330    public void setTransformer(MessageTransformer transformer) {
331        this.transformer = transformer;
332    }
333
334    /**
335     * @return Returns the value.
336     */
337    public ConsumerId getConsumerId() {
338        return info.getConsumerId();
339    }
340
341    /**
342     * @return the consumer name - used for durable consumers
343     */
344    public String getConsumerName() {
345        return this.info.getSubscriptionName();
346    }
347
348    /**
349     * @return true if this consumer does not accept locally produced messages
350     */
351    protected boolean isNoLocal() {
352        return info.isNoLocal();
353    }
354
355    /**
356     * Retrieve is a browser
357     *
358     * @return true if a browser
359     */
360    protected boolean isBrowser() {
361        return info.isBrowser();
362    }
363
364    /**
365     * @return ActiveMQDestination
366     */
367    protected ActiveMQDestination getDestination() {
368        return info.getDestination();
369    }
370
371    /**
372     * @return Returns the prefetchNumber.
373     */
374    public int getPrefetchNumber() {
375        return info.getPrefetchSize();
376    }
377
378    /**
379     * @return true if this is a durable topic subscriber
380     */
381    public boolean isDurableSubscriber() {
382        return info.getSubscriptionName() != null && info.getDestination().isTopic();
383    }
384
385    /**
386     * Gets this message consumer's message selector expression.
387     *
388     * @return this message consumer's message selector, or null if no message
389     *         selector exists for the message consumer (that is, if the message
390     *         selector was not set or was set to null or the empty string)
391     * @throws JMSException if the JMS provider fails to receive the next
392     *                 message due to some internal error.
393     */
394    @Override
395    public String getMessageSelector() throws JMSException {
396        checkClosed();
397        return selector;
398    }
399
400    /**
401     * Gets the message consumer's <CODE>MessageListener</CODE>.
402     *
403     * @return the listener for the message consumer, or null if no listener is
404     *         set
405     * @throws JMSException if the JMS provider fails to get the message
406     *                 listener due to some internal error.
407     * @see javax.jms.MessageConsumer#setMessageListener(javax.jms.MessageListener)
408     */
409    @Override
410    public MessageListener getMessageListener() throws JMSException {
411        checkClosed();
412        return this.messageListener.get();
413    }
414
415    /**
416     * Sets the message consumer's <CODE>MessageListener</CODE>.
417     * <P>
418     * Setting the message listener to null is the equivalent of unsetting the
419     * message listener for the message consumer.
420     * <P>
421     * The effect of calling <CODE>MessageConsumer.setMessageListener</CODE>
422     * while messages are being consumed by an existing listener or the consumer
423     * is being used to consume messages synchronously is undefined.
424     *
425     * @param listener the listener to which the messages are to be delivered
426     * @throws JMSException if the JMS provider fails to receive the next
427     *                 message due to some internal error.
428     * @see javax.jms.MessageConsumer#getMessageListener
429     */
430    @Override
431    public void setMessageListener(MessageListener listener) throws JMSException {
432        checkClosed();
433        if (info.getPrefetchSize() == 0) {
434            throw new JMSException("Illegal prefetch size of zero. This setting is not supported for asynchronous consumers please set a value of at least 1");
435        }
436        if (listener != null) {
437            boolean wasRunning = session.isRunning();
438            if (wasRunning) {
439                session.stop();
440            }
441
442            this.messageListener.set(listener);
443            session.redispatch(this, unconsumedMessages);
444
445            if (wasRunning) {
446                session.start();
447            }
448        } else {
449            this.messageListener.set(null);
450        }
451    }
452
453    @Override
454    public MessageAvailableListener getAvailableListener() {
455        return availableListener;
456    }
457
458    /**
459     * Sets the listener used to notify synchronous consumers that there is a
460     * message available so that the {@link MessageConsumer#receiveNoWait()} can
461     * be called.
462     */
463    @Override
464    public void setAvailableListener(MessageAvailableListener availableListener) {
465        this.availableListener = availableListener;
466    }
467
468    /**
469     * Used to get an enqueued message from the unconsumedMessages list. The
470     * amount of time this method blocks is based on the timeout value. - if
471     * timeout==-1 then it blocks until a message is received. - if timeout==0
472     * then it it tries to not block at all, it returns a message if it is
473     * available - if timeout>0 then it blocks up to timeout amount of time.
474     * Expired messages will consumed by this method.
475     *
476     * @throws JMSException
477     * @return null if we timeout or if the consumer is closed.
478     */
479    private MessageDispatch dequeue(long timeout) throws JMSException {
480        try {
481            long deadline = 0;
482            if (timeout > 0) {
483                deadline = System.currentTimeMillis() + timeout;
484            }
485            while (true) {
486                MessageDispatch md = unconsumedMessages.dequeue(timeout);
487                if (md == null) {
488                    if (timeout > 0 && !unconsumedMessages.isClosed()) {
489                        timeout = Math.max(deadline - System.currentTimeMillis(), 0);
490                    } else {
491                        if (failureError != null) {
492                            throw JMSExceptionSupport.create(failureError);
493                        } else {
494                            return null;
495                        }
496                    }
497                } else if (md.getMessage() == null) {
498                    return null;
499                } else if (consumeExpiredMessage(md)) {
500                    LOG.debug("{} received expired message: {}", getConsumerId(), md);
501                    beforeMessageIsConsumed(md);
502                    afterMessageIsConsumed(md, true);
503                    if (timeout > 0) {
504                        timeout = Math.max(deadline - System.currentTimeMillis(), 0);
505                    }
506                    sendPullCommand(timeout);
507                } else if (redeliveryExceeded(md)) {
508                    LOG.debug("{} received with excessive redelivered: {}", getConsumerId(), md);
509                    posionAck(md, "dispatch to " + getConsumerId() + " exceeds redelivery policy limit:" + redeliveryPolicy);
510                    if (timeout > 0) {
511                        timeout = Math.max(deadline - System.currentTimeMillis(), 0);
512                    }
513                    sendPullCommand(timeout);
514                } else {
515                    if (LOG.isTraceEnabled()) {
516                        LOG.trace(getConsumerId() + " received message: " + md);
517                    }
518                    return md;
519                }
520            }
521        } catch (InterruptedException e) {
522            Thread.currentThread().interrupt();
523            throw JMSExceptionSupport.create(e);
524        }
525    }
526
527    private boolean consumeExpiredMessage(MessageDispatch dispatch) {
528        return isConsumerExpiryCheckEnabled() && dispatch.getMessage().isExpired();
529    }
530
531    private void posionAck(MessageDispatch md, String cause) throws JMSException {
532        MessageAck posionAck = new MessageAck(md, MessageAck.POSION_ACK_TYPE, 1);
533        posionAck.setFirstMessageId(md.getMessage().getMessageId());
534        posionAck.setPoisonCause(new Throwable(cause));
535        session.sendAck(posionAck);
536    }
537
538    private boolean redeliveryExceeded(MessageDispatch md) {
539        try {
540            return session.getTransacted()
541                    && redeliveryPolicy != null
542                    && redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES
543                    && md.getRedeliveryCounter() > redeliveryPolicy.getMaximumRedeliveries()
544                    // redeliveryCounter > x expected after resend via brokerRedeliveryPlugin
545                    && md.getMessage().getProperty("redeliveryDelay") == null;
546        } catch (Exception ignored) {
547            return false;
548        }
549    }
550
551    /**
552     * Receives the next message produced for this message consumer.
553     * <P>
554     * This call blocks indefinitely until a message is produced or until this
555     * message consumer is closed.
556     * <P>
557     * If this <CODE>receive</CODE> is done within a transaction, the consumer
558     * retains the message until the transaction commits.
559     *
560     * @return the next message produced for this message consumer, or null if
561     *         this message consumer is concurrently closed
562     */
563    @Override
564    public Message receive() throws JMSException {
565        checkClosed();
566        checkMessageListener();
567
568        sendPullCommand(0);
569        MessageDispatch md = dequeue(-1);
570        if (md == null) {
571            return null;
572        }
573
574        beforeMessageIsConsumed(md);
575        afterMessageIsConsumed(md, false);
576
577        return createActiveMQMessage(md);
578    }
579
580    /**
581     * @param md
582     *      the MessageDispatch that arrived from the Broker.
583     *
584     * @return an ActiveMQMessage initialized from the Message in the dispatch.
585     */
586    private ActiveMQMessage createActiveMQMessage(final MessageDispatch md) throws JMSException {
587        ActiveMQMessage m = (ActiveMQMessage)md.getMessage().copy();
588        if (m.getDataStructureType()==CommandTypes.ACTIVEMQ_BLOB_MESSAGE) {
589            ((ActiveMQBlobMessage)m).setBlobDownloader(new BlobDownloader(session.getBlobTransferPolicy()));
590        }
591        if (m.getDataStructureType() == CommandTypes.ACTIVEMQ_OBJECT_MESSAGE) {
592            ((ActiveMQObjectMessage)m).setTrustAllPackages(session.getConnection().isTrustAllPackages());
593            ((ActiveMQObjectMessage)m).setTrustedPackages(session.getConnection().getTrustedPackages());
594        }
595        if (transformer != null) {
596            Message transformedMessage = transformer.consumerTransform(session, this, m);
597            if (transformedMessage != null) {
598                m = ActiveMQMessageTransformation.transformMessage(transformedMessage, session.connection);
599            }
600        }
601        if (session.isClientAcknowledge()) {
602            m.setAcknowledgeCallback(new Callback() {
603                @Override
604                public void execute() throws Exception {
605                    session.checkClosed();
606                    session.acknowledge();
607                }
608            });
609        } else if (session.isIndividualAcknowledge()) {
610            m.setAcknowledgeCallback(new Callback() {
611                @Override
612                public void execute() throws Exception {
613                    session.checkClosed();
614                    acknowledge(md);
615                }
616            });
617        }
618        return m;
619    }
620
621    /**
622     * Receives the next message that arrives within the specified timeout
623     * interval.
624     * <P>
625     * This call blocks until a message arrives, the timeout expires, or this
626     * message consumer is closed. A <CODE>timeout</CODE> of zero never
627     * expires, and the call blocks indefinitely.
628     *
629     * @param timeout the timeout value (in milliseconds), a time out of zero
630     *                never expires.
631     * @return the next message produced for this message consumer, or null if
632     *         the timeout expires or this message consumer is concurrently
633     *         closed
634     */
635    @Override
636    public Message receive(long timeout) throws JMSException {
637        checkClosed();
638        checkMessageListener();
639        if (timeout == 0) {
640            return this.receive();
641        }
642
643        sendPullCommand(timeout);
644        while (timeout > 0) {
645
646            MessageDispatch md;
647            if (info.getPrefetchSize() == 0) {
648                md = dequeue(-1); // We let the broker let us know when we timeout.
649            } else {
650                md = dequeue(timeout);
651            }
652
653            if (md == null) {
654                return null;
655            }
656
657            beforeMessageIsConsumed(md);
658            afterMessageIsConsumed(md, false);
659            return createActiveMQMessage(md);
660        }
661        return null;
662    }
663
664    /**
665     * Receives the next message if one is immediately available.
666     *
667     * @return the next message produced for this message consumer, or null if
668     *         one is not available
669     * @throws JMSException if the JMS provider fails to receive the next
670     *                 message due to some internal error.
671     */
672    @Override
673    public Message receiveNoWait() throws JMSException {
674        checkClosed();
675        checkMessageListener();
676        sendPullCommand(-1);
677
678        MessageDispatch md;
679        if (info.getPrefetchSize() == 0) {
680            md = dequeue(-1); // We let the broker let us know when we
681            // timeout.
682        } else {
683            md = dequeue(0);
684        }
685
686        if (md == null) {
687            return null;
688        }
689
690        beforeMessageIsConsumed(md);
691        afterMessageIsConsumed(md, false);
692        return createActiveMQMessage(md);
693    }
694
695    /**
696     * Closes the message consumer.
697     * <P>
698     * Since a provider may allocate some resources on behalf of a <CODE>
699     * MessageConsumer</CODE>
700     * outside the Java virtual machine, clients should close them when they are
701     * not needed. Relying on garbage collection to eventually reclaim these
702     * resources may not be timely enough.
703     * <P>
704     * This call blocks until a <CODE>receive</CODE> or message listener in
705     * progress has completed. A blocked message consumer <CODE>receive </CODE>
706     * call returns null when this message consumer is closed.
707     *
708     * @throws JMSException if the JMS provider fails to close the consumer due
709     *                 to some internal error.
710     */
711    @Override
712    public void close() throws JMSException {
713        if (!unconsumedMessages.isClosed()) {
714            if (!deliveredMessages.isEmpty() && session.getTransactionContext().isInTransaction()) {
715                session.getTransactionContext().addSynchronization(new Synchronization() {
716                    @Override
717                    public void afterCommit() throws Exception {
718                        doClose();
719                    }
720
721                    @Override
722                    public void afterRollback() throws Exception {
723                        doClose();
724                    }
725                });
726            } else {
727                doClose();
728            }
729        }
730    }
731
732    void doClose() throws JMSException {
733        dispose();
734        RemoveInfo removeCommand = info.createRemoveCommand();
735        LOG.debug("remove: {}, lastDeliveredSequenceId: {}", getConsumerId(), lastDeliveredSequenceId);
736        removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId);
737        this.session.asyncSendPacket(removeCommand);
738    }
739
740    void inProgressClearRequired() {
741        inProgressClearRequiredFlag.incrementAndGet();
742        // deal with delivered messages async to avoid lock contention with in progress acks
743        clearDeliveredList = true;
744        // force a rollback if we will be acking in a transaction after/during failover
745        // bc acks are async they may not get there reliably on reconnect and the consumer
746        // may not be aware of the reconnect in a timely fashion if in onMessage
747        if (!deliveredMessages.isEmpty() && session.getTransactionContext().isInTransaction()) {
748            session.getTransactionContext().setRollbackOnly(true);
749        }
750    }
751
752    void clearMessagesInProgress() {
753        if (inProgressClearRequiredFlag.get() > 0) {
754            synchronized (unconsumedMessages.getMutex()) {
755                if (inProgressClearRequiredFlag.get() > 0) {
756                    LOG.debug("{} clearing unconsumed list ({}) on transport interrupt", getConsumerId(), unconsumedMessages.size());
757                    // ensure unconsumed are rolledback up front as they may get redelivered to another consumer
758                    List<MessageDispatch> list = unconsumedMessages.removeAll();
759                    if (!this.info.isBrowser()) {
760                        for (MessageDispatch old : list) {
761                            session.connection.rollbackDuplicate(this, old.getMessage());
762                        }
763                    }
764                    // allow dispatch on this connection to resume
765                    session.connection.transportInterruptionProcessingComplete();
766                    inProgressClearRequiredFlag.decrementAndGet();
767
768                    // Wake up any blockers and allow them to recheck state.
769                    unconsumedMessages.getMutex().notifyAll();
770                }
771            }
772        }
773        clearDeliveredList();
774    }
775
776    void deliverAcks() {
777        MessageAck ack = null;
778        if (deliveryingAcknowledgements.compareAndSet(false, true)) {
779            synchronized(deliveredMessages) {
780                if (isAutoAcknowledgeEach()) {
781                    ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
782                    if (ack != null) {
783                        deliveredMessages.clear();
784                        ackCounter = 0;
785                    } else {
786                        ack = pendingAck;
787                        pendingAck = null;
788                    }
789                } else if (pendingAck != null && pendingAck.isStandardAck()) {
790                    ack = pendingAck;
791                    pendingAck = null;
792                }
793            }
794            if (ack != null) {
795                final MessageAck ackToSend = ack;
796
797                if (executorService == null) {
798                    executorService = Executors.newSingleThreadExecutor();
799                }
800                executorService.submit(new Runnable() {
801                    @Override
802                    public void run() {
803                        try {
804                            session.sendAck(ackToSend,true);
805                        } catch (JMSException e) {
806                            LOG.error(getConsumerId() + " failed to delivered acknowledgements", e);
807                        } finally {
808                            deliveryingAcknowledgements.set(false);
809                        }
810                    }
811                });
812            } else {
813                deliveryingAcknowledgements.set(false);
814            }
815        }
816    }
817
818    public void dispose() throws JMSException {
819        if (!unconsumedMessages.isClosed()) {
820
821            // Do we have any acks we need to send out before closing?
822            // Ack any delivered messages now.
823            if (!session.getTransacted()) {
824                deliverAcks();
825                if (isAutoAcknowledgeBatch()) {
826                    acknowledge();
827                }
828            }
829            if (executorService != null) {
830                ThreadPoolUtils.shutdownGraceful(executorService, 60000L);
831                executorService = null;
832            }
833            if (optimizedAckTask != null) {
834                this.session.connection.getScheduler().cancel(optimizedAckTask);
835                optimizedAckTask = null;
836            }
837
838            if (session.isClientAcknowledge() || session.isIndividualAcknowledge()) {
839                if (!this.info.isBrowser()) {
840                    // rollback duplicates that aren't acknowledged
841                    List<MessageDispatch> tmp = null;
842                    synchronized (this.deliveredMessages) {
843                        tmp = new ArrayList<MessageDispatch>(this.deliveredMessages);
844                    }
845                    for (MessageDispatch old : tmp) {
846                        this.session.connection.rollbackDuplicate(this, old.getMessage());
847                    }
848                    tmp.clear();
849                }
850            }
851            if (!session.isTransacted()) {
852                synchronized(deliveredMessages) {
853                    deliveredMessages.clear();
854                }
855            }
856            unconsumedMessages.close();
857            this.session.removeConsumer(this);
858            List<MessageDispatch> list = unconsumedMessages.removeAll();
859            if (!this.info.isBrowser()) {
860                for (MessageDispatch old : list) {
861                    // ensure we don't filter this as a duplicate
862                    if (old.getMessage() != null) {
863                        LOG.debug("on close, rollback duplicate: {}", old.getMessage().getMessageId());
864                    }
865                    session.connection.rollbackDuplicate(this, old.getMessage());
866                }
867            }
868        }
869    }
870
871    /**
872     * @throws IllegalStateException
873     */
874    protected void checkClosed() throws IllegalStateException {
875        if (unconsumedMessages.isClosed()) {
876            throw new IllegalStateException("The Consumer is closed");
877        }
878    }
879
880    /**
881     * If we have a zero prefetch specified then send a pull command to the
882     * broker to pull a message we are about to receive
883     */
884    protected void sendPullCommand(long timeout) throws JMSException {
885        clearDeliveredList();
886        if (info.getCurrentPrefetchSize() == 0 && unconsumedMessages.isEmpty()) {
887            MessagePull messagePull = new MessagePull();
888            messagePull.configure(info);
889            messagePull.setTimeout(timeout);
890            session.asyncSendPacket(messagePull);
891        }
892    }
893
894    protected void checkMessageListener() throws JMSException {
895        session.checkMessageListener();
896    }
897
898    protected void setOptimizeAcknowledge(boolean value) {
899        if (optimizeAcknowledge && !value) {
900            deliverAcks();
901        }
902        optimizeAcknowledge = value;
903    }
904
905    protected void setPrefetchSize(int prefetch) {
906        deliverAcks();
907        this.info.setCurrentPrefetchSize(prefetch);
908    }
909
910    private void beforeMessageIsConsumed(MessageDispatch md) throws JMSException {
911        md.setDeliverySequenceId(session.getNextDeliveryId());
912        lastDeliveredSequenceId = md.getMessage().getMessageId().getBrokerSequenceId();
913        if (!isAutoAcknowledgeBatch()) {
914            synchronized(deliveredMessages) {
915                deliveredMessages.addFirst(md);
916            }
917            if (session.getTransacted()) {
918                if (transactedIndividualAck) {
919                    immediateIndividualTransactedAck(md);
920                } else {
921                    ackLater(md, MessageAck.DELIVERED_ACK_TYPE);
922                }
923            }
924        }
925    }
926
927    private void immediateIndividualTransactedAck(MessageDispatch md) throws JMSException {
928        // acks accumulate on the broker pending transaction completion to indicate
929        // delivery status
930        registerSync();
931        MessageAck ack = new MessageAck(md, MessageAck.INDIVIDUAL_ACK_TYPE, 1);
932        ack.setTransactionId(session.getTransactionContext().getTransactionId());
933        session.sendAck(ack);
934    }
935
936    private void afterMessageIsConsumed(MessageDispatch md, boolean messageExpired) throws JMSException {
937        if (unconsumedMessages.isClosed()) {
938            return;
939        }
940        if (messageExpired) {
941            acknowledge(md, MessageAck.EXPIRED_ACK_TYPE);
942            stats.getExpiredMessageCount().increment();
943        } else {
944            stats.onMessage();
945            if (session.getTransacted()) {
946                // Do nothing.
947            } else if (isAutoAcknowledgeEach()) {
948                if (deliveryingAcknowledgements.compareAndSet(false, true)) {
949                    synchronized (deliveredMessages) {
950                        if (!deliveredMessages.isEmpty()) {
951                            if (optimizeAcknowledge) {
952                                ackCounter++;
953
954                                // AMQ-3956 evaluate both expired and normal msgs as
955                                // otherwise consumer may get stalled
956                                if (ackCounter + deliveredCounter >= (info.getPrefetchSize() * .65) || (optimizeAcknowledgeTimeOut > 0 && System.currentTimeMillis() >= (optimizeAckTimestamp + optimizeAcknowledgeTimeOut))) {
957                                    MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
958                                    if (ack != null) {
959                                        deliveredMessages.clear();
960                                        ackCounter = 0;
961                                        session.sendAck(ack);
962                                        optimizeAckTimestamp = System.currentTimeMillis();
963                                    }
964                                    // AMQ-3956 - as further optimization send
965                                    // ack for expired msgs when there are any.
966                                    // This resets the deliveredCounter to 0 so that
967                                    // we won't sent standard acks with every msg just
968                                    // because the deliveredCounter just below
969                                    // 0.5 * prefetch as used in ackLater()
970                                    if (pendingAck != null && deliveredCounter > 0) {
971                                        session.sendAck(pendingAck);
972                                        pendingAck = null;
973                                        deliveredCounter = 0;
974                                    }
975                                }
976                            } else {
977                                MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
978                                if (ack!=null) {
979                                    deliveredMessages.clear();
980                                    session.sendAck(ack);
981                                }
982                            }
983                        }
984                    }
985                    deliveryingAcknowledgements.set(false);
986                }
987            } else if (isAutoAcknowledgeBatch()) {
988                ackLater(md, MessageAck.STANDARD_ACK_TYPE);
989            } else if (session.isClientAcknowledge()||session.isIndividualAcknowledge()) {
990                boolean messageUnackedByConsumer = false;
991                synchronized (deliveredMessages) {
992                    messageUnackedByConsumer = deliveredMessages.contains(md);
993                }
994                if (messageUnackedByConsumer) {
995                    ackLater(md, MessageAck.DELIVERED_ACK_TYPE);
996                }
997            }
998            else {
999                throw new IllegalStateException("Invalid session state.");
1000            }
1001        }
1002    }
1003
1004    /**
1005     * Creates a MessageAck for all messages contained in deliveredMessages.
1006     * Caller should hold the lock for deliveredMessages.
1007     *
1008     * @param type Ack-Type (i.e. MessageAck.STANDARD_ACK_TYPE)
1009     * @return <code>null</code> if nothing to ack.
1010     */
1011    private MessageAck makeAckForAllDeliveredMessages(byte type) {
1012        synchronized (deliveredMessages) {
1013            if (deliveredMessages.isEmpty()) {
1014                return null;
1015            }
1016
1017            MessageDispatch md = deliveredMessages.getFirst();
1018            MessageAck ack = new MessageAck(md, type, deliveredMessages.size());
1019            ack.setFirstMessageId(deliveredMessages.getLast().getMessage().getMessageId());
1020            return ack;
1021        }
1022    }
1023
1024    private void ackLater(MessageDispatch md, byte ackType) throws JMSException {
1025
1026        // Don't acknowledge now, but we may need to let the broker know the
1027        // consumer got the message to expand the pre-fetch window
1028        if (session.getTransacted()) {
1029            registerSync();
1030        }
1031
1032        deliveredCounter++;
1033
1034        synchronized(deliveredMessages) {
1035            MessageAck oldPendingAck = pendingAck;
1036            pendingAck = new MessageAck(md, ackType, deliveredCounter);
1037            pendingAck.setTransactionId(session.getTransactionContext().getTransactionId());
1038            if( oldPendingAck==null ) {
1039                pendingAck.setFirstMessageId(pendingAck.getLastMessageId());
1040            } else if ( oldPendingAck.getAckType() == pendingAck.getAckType() ) {
1041                pendingAck.setFirstMessageId(oldPendingAck.getFirstMessageId());
1042            } else {
1043                // old pending ack being superseded by ack of another type, if is is not a delivered
1044                // ack and hence important, send it now so it is not lost.
1045                if (!oldPendingAck.isDeliveredAck()) {
1046                    LOG.debug("Sending old pending ack {}, new pending: {}", oldPendingAck, pendingAck);
1047                    session.sendAck(oldPendingAck);
1048                } else {
1049                    LOG.debug("dropping old pending ack {}, new pending: {}", oldPendingAck, pendingAck);
1050                }
1051            }
1052            // AMQ-3956 evaluate both expired and normal msgs as
1053            // otherwise consumer may get stalled
1054            if ((0.5 * info.getPrefetchSize()) <= (deliveredCounter + ackCounter - additionalWindowSize)) {
1055                LOG.debug("ackLater: sending: {}", pendingAck);
1056                session.sendAck(pendingAck);
1057                pendingAck=null;
1058                deliveredCounter = 0;
1059                additionalWindowSize = 0;
1060            }
1061        }
1062    }
1063
1064    private void registerSync() throws JMSException {
1065        session.doStartTransaction();
1066        if (!synchronizationRegistered) {
1067            synchronizationRegistered = true;
1068            session.getTransactionContext().addSynchronization(new Synchronization() {
1069                @Override
1070                public void beforeEnd() throws Exception {
1071                    if (transactedIndividualAck) {
1072                        clearDeliveredList();
1073                        waitForRedeliveries();
1074                        synchronized(deliveredMessages) {
1075                            rollbackOnFailedRecoveryRedelivery();
1076                        }
1077                    } else {
1078                        acknowledge();
1079                    }
1080                    synchronizationRegistered = false;
1081                }
1082
1083                @Override
1084                public void afterCommit() throws Exception {
1085                    commit();
1086                    synchronizationRegistered = false;
1087                }
1088
1089                @Override
1090                public void afterRollback() throws Exception {
1091                    rollback();
1092                    synchronizationRegistered = false;
1093                }
1094            });
1095        }
1096    }
1097
1098    /**
1099     * Acknowledge all the messages that have been delivered to the client up to
1100     * this point.
1101     *
1102     * @throws JMSException
1103     */
1104    public void acknowledge() throws JMSException {
1105        clearDeliveredList();
1106        waitForRedeliveries();
1107        synchronized(deliveredMessages) {
1108            // Acknowledge all messages so far.
1109            MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
1110            if (ack == null) {
1111                return; // no msgs
1112            }
1113
1114            if (session.getTransacted()) {
1115                rollbackOnFailedRecoveryRedelivery();
1116                session.doStartTransaction();
1117                ack.setTransactionId(session.getTransactionContext().getTransactionId());
1118            }
1119
1120            pendingAck = null;
1121            session.sendAck(ack);
1122
1123            // Adjust the counters
1124            deliveredCounter = Math.max(0, deliveredCounter - deliveredMessages.size());
1125            additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size());
1126
1127            if (!session.getTransacted()) {
1128                deliveredMessages.clear();
1129            }
1130        }
1131    }
1132
1133    private void waitForRedeliveries() {
1134        if (failoverRedeliveryWaitPeriod > 0 && previouslyDeliveredMessages != null) {
1135            long expiry = System.currentTimeMillis() + failoverRedeliveryWaitPeriod;
1136            int numberNotReplayed;
1137            do {
1138                numberNotReplayed = 0;
1139                synchronized(deliveredMessages) {
1140                    if (previouslyDeliveredMessages != null) {
1141                        for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
1142                            if (!entry.getValue()) {
1143                                numberNotReplayed++;
1144                            }
1145                        }
1146                    }
1147                }
1148                if (numberNotReplayed > 0) {
1149                    LOG.info("waiting for redelivery of {} in transaction: {}, to consumer: {}",
1150                             numberNotReplayed, this.getConsumerId(), previouslyDeliveredMessages.transactionId);
1151                    try {
1152                        Thread.sleep(Math.max(500, failoverRedeliveryWaitPeriod/4));
1153                    } catch (InterruptedException outOfhere) {
1154                        break;
1155                    }
1156                }
1157            } while (numberNotReplayed > 0 && expiry < System.currentTimeMillis());
1158        }
1159    }
1160
1161    /*
1162     * called with deliveredMessages locked
1163     */
1164    private void rollbackOnFailedRecoveryRedelivery() throws JMSException {
1165        if (previouslyDeliveredMessages != null) {
1166            // if any previously delivered messages was not re-delivered, transaction is invalid and must rollback
1167            // as messages have been dispatched else where.
1168            int numberNotReplayed = 0;
1169            for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
1170                if (!entry.getValue()) {
1171                    numberNotReplayed++;
1172                    LOG.debug("previously delivered message has not been replayed in transaction: {}, messageId: {}",
1173                              previouslyDeliveredMessages.transactionId, entry.getKey());
1174                }
1175            }
1176            if (numberNotReplayed > 0) {
1177                String message = "rolling back transaction ("
1178                    + previouslyDeliveredMessages.transactionId + ") post failover recovery. " + numberNotReplayed
1179                    + " previously delivered message(s) not replayed to consumer: " + this.getConsumerId();
1180                LOG.warn(message);
1181                throw new TransactionRolledBackException(message);
1182            }
1183        }
1184    }
1185
1186    void acknowledge(MessageDispatch md) throws JMSException {
1187        acknowledge(md, MessageAck.INDIVIDUAL_ACK_TYPE);
1188    }
1189
1190    void acknowledge(MessageDispatch md, byte ackType) throws JMSException {
1191        MessageAck ack = new MessageAck(md, ackType, 1);
1192        if (ack.isExpiredAck()) {
1193            ack.setFirstMessageId(ack.getLastMessageId());
1194        }
1195        session.sendAck(ack);
1196        synchronized(deliveredMessages){
1197            deliveredMessages.remove(md);
1198        }
1199    }
1200
1201    public void commit() throws JMSException {
1202        synchronized (deliveredMessages) {
1203            deliveredMessages.clear();
1204            clearPreviouslyDelivered();
1205        }
1206        redeliveryDelay = 0;
1207    }
1208
1209    public void rollback() throws JMSException {
1210        clearDeliveredList();
1211        synchronized (unconsumedMessages.getMutex()) {
1212            if (optimizeAcknowledge) {
1213                // remove messages read but not acked at the broker yet through
1214                // optimizeAcknowledge
1215                if (!this.info.isBrowser()) {
1216                    synchronized(deliveredMessages) {
1217                        for (int i = 0; (i < deliveredMessages.size()) && (i < ackCounter); i++) {
1218                            // ensure we don't filter this as a duplicate
1219                            MessageDispatch md = deliveredMessages.removeLast();
1220                            session.connection.rollbackDuplicate(this, md.getMessage());
1221                        }
1222                    }
1223                }
1224            }
1225            synchronized(deliveredMessages) {
1226                rollbackPreviouslyDeliveredAndNotRedelivered();
1227                if (deliveredMessages.isEmpty()) {
1228                    return;
1229                }
1230
1231                // use initial delay for first redelivery
1232                MessageDispatch lastMd = deliveredMessages.getFirst();
1233                final int currentRedeliveryCount = lastMd.getMessage().getRedeliveryCounter();
1234                if (currentRedeliveryCount > 0) {
1235                    redeliveryDelay = redeliveryPolicy.getNextRedeliveryDelay(redeliveryDelay);
1236                } else {
1237                    redeliveryDelay = redeliveryPolicy.getInitialRedeliveryDelay();
1238                }
1239                MessageId firstMsgId = deliveredMessages.getLast().getMessage().getMessageId();
1240
1241                for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) {
1242                    MessageDispatch md = iter.next();
1243                    md.getMessage().onMessageRolledBack();
1244                    // ensure we don't filter this as a duplicate
1245                    session.connection.rollbackDuplicate(this, md.getMessage());
1246                }
1247
1248                if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES
1249                    && lastMd.getMessage().getRedeliveryCounter() > redeliveryPolicy.getMaximumRedeliveries()) {
1250                    // We need to NACK the messages so that they get sent to the
1251                    // DLQ.
1252                    // Acknowledge the last message.
1253
1254                    MessageAck ack = new MessageAck(lastMd, MessageAck.POSION_ACK_TYPE, deliveredMessages.size());
1255                    ack.setFirstMessageId(firstMsgId);
1256                    ack.setPoisonCause(new Throwable("Exceeded redelivery policy limit:" + redeliveryPolicy
1257                            + ", cause:" + lastMd.getRollbackCause(), lastMd.getRollbackCause()));
1258                    session.sendAck(ack,true);
1259                    // Adjust the window size.
1260                    additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size());
1261                    redeliveryDelay = 0;
1262
1263                    deliveredCounter -= deliveredMessages.size();
1264                    deliveredMessages.clear();
1265
1266                } else {
1267
1268                    // only redelivery_ack after first delivery
1269                    if (currentRedeliveryCount > 0) {
1270                        MessageAck ack = new MessageAck(lastMd, MessageAck.REDELIVERED_ACK_TYPE, deliveredMessages.size());
1271                        ack.setFirstMessageId(firstMsgId);
1272                        session.sendAck(ack,true);
1273                    }
1274
1275                    // stop the delivery of messages.
1276                    if (nonBlockingRedelivery) {
1277                        if (!unconsumedMessages.isClosed()) {
1278
1279                            final LinkedList<MessageDispatch> pendingRedeliveries =
1280                                new LinkedList<MessageDispatch>(deliveredMessages);
1281
1282                            Collections.reverse(pendingRedeliveries);
1283
1284                            deliveredCounter -= deliveredMessages.size();
1285                            deliveredMessages.clear();
1286
1287                            // Start up the delivery again a little later.
1288                            session.getScheduler().executeAfterDelay(new Runnable() {
1289                                @Override
1290                                public void run() {
1291                                    try {
1292                                        if (!unconsumedMessages.isClosed()) {
1293                                            for(MessageDispatch dispatch : pendingRedeliveries) {
1294                                                session.dispatch(dispatch);
1295                                            }
1296                                        }
1297                                    } catch (Exception e) {
1298                                        session.connection.onAsyncException(e);
1299                                    }
1300                                }
1301                            }, redeliveryDelay);
1302                        }
1303
1304                    } else {
1305                        unconsumedMessages.stop();
1306
1307                        for (MessageDispatch md : deliveredMessages) {
1308                            unconsumedMessages.enqueueFirst(md);
1309                        }
1310
1311                        deliveredCounter -= deliveredMessages.size();
1312                        deliveredMessages.clear();
1313
1314                        if (redeliveryDelay > 0 && !unconsumedMessages.isClosed()) {
1315                            // Start up the delivery again a little later.
1316                            session.getScheduler().executeAfterDelay(new Runnable() {
1317                                @Override
1318                                public void run() {
1319                                    try {
1320                                        if (started.get()) {
1321                                            start();
1322                                        }
1323                                    } catch (JMSException e) {
1324                                        session.connection.onAsyncException(e);
1325                                    }
1326                                }
1327                            }, redeliveryDelay);
1328                        } else {
1329                            start();
1330                        }
1331                    }
1332                }
1333            }
1334        }
1335        if (messageListener.get() != null) {
1336            session.redispatch(this, unconsumedMessages);
1337        }
1338    }
1339
1340    /*
1341     * called with unconsumedMessages && deliveredMessages locked
1342     * remove any message not re-delivered as they can't be replayed to this
1343     * consumer on rollback
1344     */
1345    private void rollbackPreviouslyDeliveredAndNotRedelivered() {
1346        if (previouslyDeliveredMessages != null) {
1347            for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
1348                if (!entry.getValue()) {
1349                    LOG.trace("rollback non redelivered: {}" + entry.getKey());
1350                    removeFromDeliveredMessages(entry.getKey());
1351                }
1352            }
1353            clearPreviouslyDelivered();
1354        }
1355    }
1356
1357    /*
1358     * called with deliveredMessages locked
1359     */
1360    private void removeFromDeliveredMessages(MessageId key) {
1361        Iterator<MessageDispatch> iterator = deliveredMessages.iterator();
1362        while (iterator.hasNext()) {
1363            MessageDispatch candidate = iterator.next();
1364            if (key.equals(candidate.getMessage().getMessageId())) {
1365                session.connection.rollbackDuplicate(this, candidate.getMessage());
1366                iterator.remove();
1367                break;
1368            }
1369        }
1370    }
1371
1372    /*
1373     * called with deliveredMessages locked
1374     */
1375    private void clearPreviouslyDelivered() {
1376        if (previouslyDeliveredMessages != null) {
1377            previouslyDeliveredMessages.clear();
1378            previouslyDeliveredMessages = null;
1379        }
1380    }
1381
1382    @Override
1383    public void dispatch(MessageDispatch md) {
1384        MessageListener listener = this.messageListener.get();
1385        try {
1386            clearMessagesInProgress();
1387            clearDeliveredList();
1388            synchronized (unconsumedMessages.getMutex()) {
1389                if (!unconsumedMessages.isClosed()) {
1390                    if (this.info.isBrowser() || !session.connection.isDuplicate(this, md.getMessage())) {
1391                        if (listener != null && unconsumedMessages.isRunning()) {
1392                            if (redeliveryExceeded(md)) {
1393                                posionAck(md, "dispatch to " + getConsumerId() + " exceeds redelivery policy limit:" + redeliveryPolicy);
1394                                return;
1395                            }
1396                            ActiveMQMessage message = createActiveMQMessage(md);
1397                            beforeMessageIsConsumed(md);
1398                            try {
1399                                boolean expired = isConsumerExpiryCheckEnabled() && message.isExpired();
1400                                if (!expired) {
1401                                    listener.onMessage(message);
1402                                }
1403                                afterMessageIsConsumed(md, expired);
1404                            } catch (RuntimeException e) {
1405                                LOG.error("{} Exception while processing message: {}", getConsumerId(), md.getMessage().getMessageId(), e);
1406                                md.setRollbackCause(e);
1407                                if (isAutoAcknowledgeBatch() || isAutoAcknowledgeEach() || session.isIndividualAcknowledge()) {
1408                                    // schedual redelivery and possible dlq processing
1409                                    rollback();
1410                                } else {
1411                                    // Transacted or Client ack: Deliver the next message.
1412                                    afterMessageIsConsumed(md, false);
1413                                }
1414                            }
1415                        } else {
1416                            if (!unconsumedMessages.isRunning()) {
1417                                // delayed redelivery, ensure it can be re delivered
1418                                session.connection.rollbackDuplicate(this, md.getMessage());
1419                            }
1420
1421                            if (md.getMessage() == null) {
1422                                // End of browse or pull request timeout.
1423                                unconsumedMessages.enqueue(md);
1424                            } else {
1425                                if (!consumeExpiredMessage(md)) {
1426                                    unconsumedMessages.enqueue(md);
1427                                    if (availableListener != null) {
1428                                        availableListener.onMessageAvailable(this);
1429                                    }
1430                                } else {
1431                                    beforeMessageIsConsumed(md);
1432                                    afterMessageIsConsumed(md, true);
1433
1434                                    // Pull consumer needs to check if pull timed out and send
1435                                    // a new pull command if not.
1436                                    if (info.getCurrentPrefetchSize() == 0) {
1437                                        unconsumedMessages.enqueue(null);
1438                                    }
1439                                }
1440                            }
1441                        }
1442                    } else {
1443                        // deal with duplicate delivery
1444                        ConsumerId consumerWithPendingTransaction;
1445                        if (redeliveryExpectedInCurrentTransaction(md, true)) {
1446                            LOG.debug("{} tracking transacted redelivery {}", getConsumerId(), md.getMessage());
1447                            if (transactedIndividualAck) {
1448                                immediateIndividualTransactedAck(md);
1449                            } else {
1450                                session.sendAck(new MessageAck(md, MessageAck.DELIVERED_ACK_TYPE, 1));
1451                            }
1452                        } else if ((consumerWithPendingTransaction = redeliveryPendingInCompetingTransaction(md)) != null) {
1453                            LOG.warn("{} delivering duplicate {}, pending transaction completion on {} will rollback", getConsumerId(), md.getMessage(), consumerWithPendingTransaction);
1454                            session.getConnection().rollbackDuplicate(this, md.getMessage());
1455                            dispatch(md);
1456                        } else {
1457                            LOG.warn("{} suppressing duplicate delivery on connection, poison acking: {}", getConsumerId(), md);
1458                            posionAck(md, "Suppressing duplicate delivery on connection, consumer " + getConsumerId());
1459                        }
1460                    }
1461                }
1462            }
1463            if (++dispatchedCount % 1000 == 0) {
1464                dispatchedCount = 0;
1465                Thread.yield();
1466            }
1467        } catch (Exception e) {
1468            session.connection.onClientInternalException(e);
1469        }
1470    }
1471
1472    private boolean redeliveryExpectedInCurrentTransaction(MessageDispatch md, boolean markReceipt) {
1473        if (session.isTransacted()) {
1474            synchronized (deliveredMessages) {
1475                if (previouslyDeliveredMessages != null) {
1476                    if (previouslyDeliveredMessages.containsKey(md.getMessage().getMessageId())) {
1477                        if (markReceipt) {
1478                            previouslyDeliveredMessages.put(md.getMessage().getMessageId(), true);
1479                        }
1480                        return true;
1481                    }
1482                }
1483            }
1484        }
1485        return false;
1486    }
1487
1488    private ConsumerId redeliveryPendingInCompetingTransaction(MessageDispatch md) {
1489        for (ActiveMQSession activeMQSession: session.connection.getSessions()) {
1490            for (ActiveMQMessageConsumer activeMQMessageConsumer : activeMQSession.consumers) {
1491                if (activeMQMessageConsumer.redeliveryExpectedInCurrentTransaction(md, false)) {
1492                    return activeMQMessageConsumer.getConsumerId();
1493                }
1494            }
1495        }
1496        return null;
1497    }
1498
1499    // async (on next call) clear or track delivered as they may be flagged as duplicates if they arrive again
1500    private void clearDeliveredList() {
1501        if (clearDeliveredList) {
1502            synchronized (deliveredMessages) {
1503                if (clearDeliveredList) {
1504                    if (!deliveredMessages.isEmpty()) {
1505                        if (session.isTransacted()) {
1506
1507                            if (previouslyDeliveredMessages == null) {
1508                                previouslyDeliveredMessages = new PreviouslyDeliveredMap<MessageId, Boolean>(session.getTransactionContext().getTransactionId());
1509                            }
1510                            for (MessageDispatch delivered : deliveredMessages) {
1511                                previouslyDeliveredMessages.put(delivered.getMessage().getMessageId(), false);
1512                            }
1513                            LOG.debug("{} tracking existing transacted {} delivered list ({}) on transport interrupt",
1514                                      getConsumerId(), previouslyDeliveredMessages.transactionId, deliveredMessages.size());
1515                        } else {
1516                            if (session.isClientAcknowledge()) {
1517                                LOG.debug("{} rolling back delivered list ({}) on transport interrupt", getConsumerId(), deliveredMessages.size());
1518                                // allow redelivery
1519                                if (!this.info.isBrowser()) {
1520                                    for (MessageDispatch md: deliveredMessages) {
1521                                        this.session.connection.rollbackDuplicate(this, md.getMessage());
1522                                    }
1523                                }
1524                            }
1525                            LOG.debug("{} clearing delivered list ({}) on transport interrupt", getConsumerId(), deliveredMessages.size());
1526                            deliveredMessages.clear();
1527                            pendingAck = null;
1528                        }
1529                    }
1530                    clearDeliveredList = false;
1531                }
1532            }
1533        }
1534    }
1535
1536    public int getMessageSize() {
1537        return unconsumedMessages.size();
1538    }
1539
1540    public void start() throws JMSException {
1541        if (unconsumedMessages.isClosed()) {
1542            return;
1543        }
1544        started.set(true);
1545        unconsumedMessages.start();
1546        session.executor.wakeup();
1547    }
1548
1549    public void stop() {
1550        started.set(false);
1551        unconsumedMessages.stop();
1552    }
1553
1554    @Override
1555    public String toString() {
1556        return "ActiveMQMessageConsumer { value=" + info.getConsumerId() + ", started=" + started.get()
1557               + " }";
1558    }
1559
1560    /**
1561     * Delivers a message to the message listener.
1562     *
1563     * @return true if another execution is needed.
1564     *
1565     * @throws JMSException
1566     */
1567    public boolean iterate() {
1568        MessageListener listener = this.messageListener.get();
1569        if (listener != null) {
1570            MessageDispatch md = unconsumedMessages.dequeueNoWait();
1571            if (md != null) {
1572                dispatch(md);
1573                return true;
1574            }
1575        }
1576        return false;
1577    }
1578
1579    public boolean isInUse(ActiveMQTempDestination destination) {
1580        return info.getDestination().equals(destination);
1581    }
1582
1583    public long getLastDeliveredSequenceId() {
1584        return lastDeliveredSequenceId;
1585    }
1586
1587    public IOException getFailureError() {
1588        return failureError;
1589    }
1590
1591    public void setFailureError(IOException failureError) {
1592        this.failureError = failureError;
1593    }
1594
1595    /**
1596     * @return the optimizedAckScheduledAckInterval
1597     */
1598    public long getOptimizedAckScheduledAckInterval() {
1599        return optimizedAckScheduledAckInterval;
1600    }
1601
1602    /**
1603     * @param optimizedAckScheduledAckInterval the optimizedAckScheduledAckInterval to set
1604     */
1605    public void setOptimizedAckScheduledAckInterval(long optimizedAckScheduledAckInterval) throws JMSException {
1606        this.optimizedAckScheduledAckInterval = optimizedAckScheduledAckInterval;
1607
1608        if (this.optimizedAckTask != null) {
1609            try {
1610                this.session.connection.getScheduler().cancel(optimizedAckTask);
1611            } catch (JMSException e) {
1612                LOG.debug("Caught exception while cancelling old optimized ack task", e);
1613                throw e;
1614            }
1615            this.optimizedAckTask = null;
1616        }
1617
1618        // Should we periodically send out all outstanding acks.
1619        if (this.optimizeAcknowledge && this.optimizedAckScheduledAckInterval > 0) {
1620            this.optimizedAckTask = new Runnable() {
1621
1622                @Override
1623                public void run() {
1624                    try {
1625                        if (optimizeAcknowledge && !unconsumedMessages.isClosed()) {
1626                            LOG.info("Consumer:{} is performing scheduled delivery of outstanding optimized Acks", info.getConsumerId());
1627                            deliverAcks();
1628                        }
1629                    } catch (Exception e) {
1630                        LOG.debug("Optimized Ack Task caught exception during ack", e);
1631                    }
1632                }
1633            };
1634
1635            try {
1636                this.session.connection.getScheduler().executePeriodically(optimizedAckTask, optimizedAckScheduledAckInterval);
1637            } catch (JMSException e) {
1638                LOG.debug("Caught exception while scheduling new optimized ack task", e);
1639                throw e;
1640            }
1641        }
1642    }
1643
1644    public boolean hasMessageListener() {
1645        return messageListener.get() != null;
1646    }
1647
1648    public boolean isConsumerExpiryCheckEnabled() {
1649        return consumerExpiryCheckEnabled;
1650    }
1651
1652    public void setConsumerExpiryCheckEnabled(boolean consumerExpiryCheckEnabled) {
1653        this.consumerExpiryCheckEnabled = consumerExpiryCheckEnabled;
1654    }
1655}