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.broker.region;
018
019import java.io.IOException;
020import java.util.List;
021
022import javax.jms.ResourceAllocationException;
023
024import org.apache.activemq.advisory.AdvisorySupport;
025import org.apache.activemq.broker.Broker;
026import org.apache.activemq.broker.BrokerService;
027import org.apache.activemq.broker.ConnectionContext;
028import org.apache.activemq.broker.ProducerBrokerExchange;
029import org.apache.activemq.broker.region.policy.DeadLetterStrategy;
030import org.apache.activemq.broker.region.policy.SlowConsumerStrategy;
031import org.apache.activemq.command.ActiveMQDestination;
032import org.apache.activemq.command.ActiveMQTopic;
033import org.apache.activemq.command.Message;
034import org.apache.activemq.command.MessageAck;
035import org.apache.activemq.command.MessageDispatchNotification;
036import org.apache.activemq.command.ProducerInfo;
037import org.apache.activemq.filter.NonCachedMessageEvaluationContext;
038import org.apache.activemq.security.SecurityContext;
039import org.apache.activemq.state.ProducerState;
040import org.apache.activemq.store.MessageStore;
041import org.apache.activemq.thread.Scheduler;
042import org.apache.activemq.usage.MemoryUsage;
043import org.apache.activemq.usage.SystemUsage;
044import org.apache.activemq.usage.Usage;
045import org.slf4j.Logger;
046
047/**
048 *
049 */
050public abstract class BaseDestination implements Destination {
051    /**
052     * The maximum number of messages to page in to the destination from
053     * persistent storage
054     */
055    public static final int MAX_PAGE_SIZE = 200;
056    public static final int MAX_BROWSE_PAGE_SIZE = MAX_PAGE_SIZE * 2;
057    public static final long EXPIRE_MESSAGE_PERIOD = 30 * 1000;
058    public static final long DEFAULT_INACTIVE_TIMEOUT_BEFORE_GC = 60 * 1000;
059    public static final int MAX_PRODUCERS_TO_AUDIT = 64;
060    public static final int MAX_AUDIT_DEPTH = 10000;
061
062    protected final ActiveMQDestination destination;
063    protected final Broker broker;
064    protected final MessageStore store;
065    protected SystemUsage systemUsage;
066    protected MemoryUsage memoryUsage;
067    private boolean producerFlowControl = true;
068    private boolean alwaysRetroactive = false;
069    protected boolean warnOnProducerFlowControl = true;
070    protected long blockedProducerWarningInterval = DEFAULT_BLOCKED_PRODUCER_WARNING_INTERVAL;
071
072    private int maxProducersToAudit = 1024;
073    private int maxAuditDepth = 2048;
074    private boolean enableAudit = true;
075    private int maxPageSize = MAX_PAGE_SIZE;
076    private int maxBrowsePageSize = MAX_BROWSE_PAGE_SIZE;
077    private boolean useCache = true;
078    private int minimumMessageSize = 1024;
079    private boolean lazyDispatch = false;
080    private boolean advisoryForSlowConsumers;
081    private boolean advisoryForFastProducers;
082    private boolean advisoryForDiscardingMessages;
083    private boolean advisoryWhenFull;
084    private boolean advisoryForDelivery;
085    private boolean advisoryForConsumed;
086    private boolean sendAdvisoryIfNoConsumers;
087    private boolean includeBodyForAdvisory;
088    protected final DestinationStatistics destinationStatistics = new DestinationStatistics();
089    protected final BrokerService brokerService;
090    protected final Broker regionBroker;
091    protected DeadLetterStrategy deadLetterStrategy = DEFAULT_DEAD_LETTER_STRATEGY;
092    protected long expireMessagesPeriod = EXPIRE_MESSAGE_PERIOD;
093    private int maxExpirePageSize = MAX_BROWSE_PAGE_SIZE;
094    protected int cursorMemoryHighWaterMark = 70;
095    protected int storeUsageHighWaterMark = 100;
096    private SlowConsumerStrategy slowConsumerStrategy;
097    private boolean prioritizedMessages;
098    private long inactiveTimeoutBeforeGC = DEFAULT_INACTIVE_TIMEOUT_BEFORE_GC;
099    private boolean gcIfInactive;
100    private boolean gcWithNetworkConsumers;
101    private long lastActiveTime=0l;
102    private boolean reduceMemoryFootprint = false;
103    protected final Scheduler scheduler;
104    private boolean disposed = false;
105    private boolean doOptimzeMessageStorage = true;
106    /*
107     * percentage of in-flight messages above which optimize message store is disabled
108     */
109    private int optimizeMessageStoreInFlightLimit = 10;
110    private boolean persistJMSRedelivered;
111
112    /**
113     * @param brokerService
114     * @param store
115     * @param destination
116     * @param parentStats
117     * @throws Exception
118     */
119    public BaseDestination(BrokerService brokerService, MessageStore store, ActiveMQDestination destination, DestinationStatistics parentStats) throws Exception {
120        this.brokerService = brokerService;
121        this.broker = brokerService.getBroker();
122        this.store = store;
123        this.destination = destination;
124        // let's copy the enabled property from the parent DestinationStatistics
125        this.destinationStatistics.setEnabled(parentStats.isEnabled());
126        this.destinationStatistics.setParent(parentStats);
127        this.systemUsage = new SystemUsage(brokerService.getProducerSystemUsage(), destination.toString());
128        this.memoryUsage = this.systemUsage.getMemoryUsage();
129        this.memoryUsage.setUsagePortion(1.0f);
130        this.regionBroker = brokerService.getRegionBroker();
131        this.scheduler = brokerService.getBroker().getScheduler();
132    }
133
134    /**
135     * initialize the destination
136     *
137     * @throws Exception
138     */
139    public void initialize() throws Exception {
140        // Let the store know what usage manager we are using so that he can
141        // flush messages to disk when usage gets high.
142        if (store != null) {
143            store.setMemoryUsage(this.memoryUsage);
144        }
145    }
146
147    /**
148     * @return the producerFlowControl
149     */
150    @Override
151    public boolean isProducerFlowControl() {
152        return producerFlowControl;
153    }
154
155    /**
156     * @param producerFlowControl the producerFlowControl to set
157     */
158    @Override
159    public void setProducerFlowControl(boolean producerFlowControl) {
160        this.producerFlowControl = producerFlowControl;
161    }
162
163    @Override
164    public boolean isAlwaysRetroactive() {
165        return alwaysRetroactive;
166    }
167
168    @Override
169    public void setAlwaysRetroactive(boolean alwaysRetroactive) {
170        this.alwaysRetroactive = alwaysRetroactive;
171    }
172
173    /**
174     * Set's the interval at which warnings about producers being blocked by
175     * resource usage will be triggered. Values of 0 or less will disable
176     * warnings
177     *
178     * @param blockedProducerWarningInterval the interval at which warning about
179     *            blocked producers will be triggered.
180     */
181    @Override
182    public void setBlockedProducerWarningInterval(long blockedProducerWarningInterval) {
183        this.blockedProducerWarningInterval = blockedProducerWarningInterval;
184    }
185
186    /**
187     *
188     * @return the interval at which warning about blocked producers will be
189     *         triggered.
190     */
191    @Override
192    public long getBlockedProducerWarningInterval() {
193        return blockedProducerWarningInterval;
194    }
195
196    /**
197     * @return the maxProducersToAudit
198     */
199    @Override
200    public int getMaxProducersToAudit() {
201        return maxProducersToAudit;
202    }
203
204    /**
205     * @param maxProducersToAudit the maxProducersToAudit to set
206     */
207    @Override
208    public void setMaxProducersToAudit(int maxProducersToAudit) {
209        this.maxProducersToAudit = maxProducersToAudit;
210    }
211
212    /**
213     * @return the maxAuditDepth
214     */
215    @Override
216    public int getMaxAuditDepth() {
217        return maxAuditDepth;
218    }
219
220    /**
221     * @param maxAuditDepth the maxAuditDepth to set
222     */
223    @Override
224    public void setMaxAuditDepth(int maxAuditDepth) {
225        this.maxAuditDepth = maxAuditDepth;
226    }
227
228    /**
229     * @return the enableAudit
230     */
231    @Override
232    public boolean isEnableAudit() {
233        return enableAudit;
234    }
235
236    /**
237     * @param enableAudit the enableAudit to set
238     */
239    @Override
240    public void setEnableAudit(boolean enableAudit) {
241        this.enableAudit = enableAudit;
242    }
243
244    @Override
245    public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
246        destinationStatistics.getProducers().increment();
247        this.lastActiveTime=0l;
248    }
249
250    @Override
251    public void removeProducer(ConnectionContext context, ProducerInfo info) throws Exception {
252        destinationStatistics.getProducers().decrement();
253    }
254
255    @Override
256    public void addSubscription(ConnectionContext context, Subscription sub) throws Exception{
257        destinationStatistics.getConsumers().increment();
258        this.lastActiveTime=0l;
259    }
260
261    @Override
262    public void removeSubscription(ConnectionContext context, Subscription sub, long lastDeliveredSequenceId) throws Exception{
263        destinationStatistics.getConsumers().decrement();
264    }
265
266
267    @Override
268    public final MemoryUsage getMemoryUsage() {
269        return memoryUsage;
270    }
271
272    @Override
273    public void setMemoryUsage(MemoryUsage memoryUsage) {
274        this.memoryUsage = memoryUsage;
275    }
276
277    @Override
278    public DestinationStatistics getDestinationStatistics() {
279        return destinationStatistics;
280    }
281
282    @Override
283    public ActiveMQDestination getActiveMQDestination() {
284        return destination;
285    }
286
287    @Override
288    public final String getName() {
289        return getActiveMQDestination().getPhysicalName();
290    }
291
292    @Override
293    public final MessageStore getMessageStore() {
294        return store;
295    }
296
297    @Override
298    public boolean isActive() {
299        boolean isActive = destinationStatistics.getConsumers().getCount() != 0 ||
300                           destinationStatistics.getProducers().getCount() != 0;
301        if (isActive && isGcWithNetworkConsumers() && destinationStatistics.getConsumers().getCount() != 0) {
302            isActive = hasRegularConsumers(getConsumers());
303        }
304        return isActive;
305    }
306
307    @Override
308    public int getMaxPageSize() {
309        return maxPageSize;
310    }
311
312    @Override
313    public void setMaxPageSize(int maxPageSize) {
314        this.maxPageSize = maxPageSize;
315    }
316
317    @Override
318    public int getMaxBrowsePageSize() {
319        return this.maxBrowsePageSize > 0 ? this.maxBrowsePageSize : getMaxPageSize();
320    }
321
322    @Override
323    public void setMaxBrowsePageSize(int maxPageSize) {
324        this.maxBrowsePageSize = maxPageSize;
325    }
326
327    public int getMaxExpirePageSize() {
328        return this.maxExpirePageSize;
329    }
330
331    public void setMaxExpirePageSize(int maxPageSize) {
332        this.maxExpirePageSize = maxPageSize;
333    }
334
335    public void setExpireMessagesPeriod(long expireMessagesPeriod) {
336        this.expireMessagesPeriod = expireMessagesPeriod;
337    }
338
339    public long getExpireMessagesPeriod() {
340        return expireMessagesPeriod;
341    }
342
343    @Override
344    public boolean isUseCache() {
345        return useCache;
346    }
347
348    @Override
349    public void setUseCache(boolean useCache) {
350        this.useCache = useCache;
351    }
352
353    @Override
354    public int getMinimumMessageSize() {
355        return minimumMessageSize;
356    }
357
358    @Override
359    public void setMinimumMessageSize(int minimumMessageSize) {
360        this.minimumMessageSize = minimumMessageSize;
361    }
362
363    @Override
364    public boolean isLazyDispatch() {
365        return lazyDispatch;
366    }
367
368    @Override
369    public void setLazyDispatch(boolean lazyDispatch) {
370        this.lazyDispatch = lazyDispatch;
371    }
372
373    protected long getDestinationSequenceId() {
374        return regionBroker.getBrokerSequenceId();
375    }
376
377    /**
378     * @return the advisoryForSlowConsumers
379     */
380    public boolean isAdvisoryForSlowConsumers() {
381        return advisoryForSlowConsumers;
382    }
383
384    /**
385     * @param advisoryForSlowConsumers the advisoryForSlowConsumers to set
386     */
387    public void setAdvisoryForSlowConsumers(boolean advisoryForSlowConsumers) {
388        this.advisoryForSlowConsumers = advisoryForSlowConsumers;
389    }
390
391    /**
392     * @return the advisoryForDiscardingMessages
393     */
394    public boolean isAdvisoryForDiscardingMessages() {
395        return advisoryForDiscardingMessages;
396    }
397
398    /**
399     * @param advisoryForDiscardingMessages the advisoryForDiscardingMessages to
400     *            set
401     */
402    public void setAdvisoryForDiscardingMessages(boolean advisoryForDiscardingMessages) {
403        this.advisoryForDiscardingMessages = advisoryForDiscardingMessages;
404    }
405
406    /**
407     * @return the advisoryWhenFull
408     */
409    public boolean isAdvisoryWhenFull() {
410        return advisoryWhenFull;
411    }
412
413    /**
414     * @param advisoryWhenFull the advisoryWhenFull to set
415     */
416    public void setAdvisoryWhenFull(boolean advisoryWhenFull) {
417        this.advisoryWhenFull = advisoryWhenFull;
418    }
419
420    /**
421     * @return the advisoryForDelivery
422     */
423    public boolean isAdvisoryForDelivery() {
424        return advisoryForDelivery;
425    }
426
427    /**
428     * @param advisoryForDelivery the advisoryForDelivery to set
429     */
430    public void setAdvisoryForDelivery(boolean advisoryForDelivery) {
431        this.advisoryForDelivery = advisoryForDelivery;
432    }
433
434    /**
435     * @return the advisoryForConsumed
436     */
437    public boolean isAdvisoryForConsumed() {
438        return advisoryForConsumed;
439    }
440
441    /**
442     * @param advisoryForConsumed the advisoryForConsumed to set
443     */
444    public void setAdvisoryForConsumed(boolean advisoryForConsumed) {
445        this.advisoryForConsumed = advisoryForConsumed;
446    }
447
448    /**
449     * @return the advisdoryForFastProducers
450     */
451    public boolean isAdvisoryForFastProducers() {
452        return advisoryForFastProducers;
453    }
454
455    /**
456     * @param advisoryForFastProducers the advisdoryForFastProducers to set
457     */
458    public void setAdvisoryForFastProducers(boolean advisoryForFastProducers) {
459        this.advisoryForFastProducers = advisoryForFastProducers;
460    }
461
462    public boolean isSendAdvisoryIfNoConsumers() {
463        return sendAdvisoryIfNoConsumers;
464    }
465
466    public void setSendAdvisoryIfNoConsumers(boolean sendAdvisoryIfNoConsumers) {
467        this.sendAdvisoryIfNoConsumers = sendAdvisoryIfNoConsumers;
468    }
469
470    public boolean isIncludeBodyForAdvisory() {
471        return includeBodyForAdvisory;
472    }
473
474    public void setIncludeBodyForAdvisory(boolean includeBodyForAdvisory) {
475        this.includeBodyForAdvisory = includeBodyForAdvisory;
476    }
477
478    /**
479     * @return the dead letter strategy
480     */
481    @Override
482    public DeadLetterStrategy getDeadLetterStrategy() {
483        return deadLetterStrategy;
484    }
485
486    /**
487     * set the dead letter strategy
488     *
489     * @param deadLetterStrategy
490     */
491    public void setDeadLetterStrategy(DeadLetterStrategy deadLetterStrategy) {
492        this.deadLetterStrategy = deadLetterStrategy;
493    }
494
495    @Override
496    public int getCursorMemoryHighWaterMark() {
497        return this.cursorMemoryHighWaterMark;
498    }
499
500    @Override
501    public void setCursorMemoryHighWaterMark(int cursorMemoryHighWaterMark) {
502        this.cursorMemoryHighWaterMark = cursorMemoryHighWaterMark;
503    }
504
505    /**
506     * called when message is consumed
507     *
508     * @param context
509     * @param messageReference
510     */
511    @Override
512    public void messageConsumed(ConnectionContext context, MessageReference messageReference) {
513        if (advisoryForConsumed) {
514            broker.messageConsumed(context, messageReference);
515        }
516    }
517
518    /**
519     * Called when message is delivered to the broker
520     *
521     * @param context
522     * @param messageReference
523     */
524    @Override
525    public void messageDelivered(ConnectionContext context, MessageReference messageReference) {
526        if (advisoryForDelivery) {
527            broker.messageDelivered(context, messageReference);
528        }
529    }
530
531    /**
532     * Called when a message is discarded - e.g. running low on memory This will
533     * happen only if the policy is enabled - e.g. non durable topics
534     *
535     * @param context
536     * @param messageReference
537     */
538    @Override
539    public void messageDiscarded(ConnectionContext context, Subscription sub, MessageReference messageReference) {
540        if (advisoryForDiscardingMessages) {
541            broker.messageDiscarded(context, sub, messageReference);
542        }
543    }
544
545    /**
546     * Called when there is a slow consumer
547     *
548     * @param context
549     * @param subs
550     */
551    @Override
552    public void slowConsumer(ConnectionContext context, Subscription subs) {
553        if (advisoryForSlowConsumers) {
554            broker.slowConsumer(context, this, subs);
555        }
556        if (slowConsumerStrategy != null) {
557            slowConsumerStrategy.slowConsumer(context, subs);
558        }
559    }
560
561    /**
562     * Called to notify a producer is too fast
563     *
564     * @param context
565     * @param producerInfo
566     */
567    @Override
568    public void fastProducer(ConnectionContext context, ProducerInfo producerInfo) {
569        if (advisoryForFastProducers) {
570            broker.fastProducer(context, producerInfo, getActiveMQDestination());
571        }
572    }
573
574    /**
575     * Called when a Usage reaches a limit
576     *
577     * @param context
578     * @param usage
579     */
580    @Override
581    public void isFull(ConnectionContext context, Usage<?> usage) {
582        if (advisoryWhenFull) {
583            broker.isFull(context, this, usage);
584        }
585    }
586
587    @Override
588    public void dispose(ConnectionContext context) throws IOException {
589        if (this.store != null) {
590            this.store.removeAllMessages(context);
591            this.store.dispose(context);
592        }
593        this.destinationStatistics.setParent(null);
594        this.memoryUsage.stop();
595        this.disposed = true;
596    }
597
598    @Override
599    public boolean isDisposed() {
600        return this.disposed;
601    }
602
603    /**
604     * Provides a hook to allow messages with no consumer to be processed in
605     * some way - such as to send to a dead letter queue or something..
606     */
607    protected void onMessageWithNoConsumers(ConnectionContext context, Message msg) throws Exception {
608        if (!msg.isPersistent()) {
609            if (isSendAdvisoryIfNoConsumers()) {
610                // allow messages with no consumers to be dispatched to a dead
611                // letter queue
612                if (destination.isQueue() || !AdvisorySupport.isAdvisoryTopic(destination)) {
613
614                    Message message = msg.copy();
615                    // The original destination and transaction id do not get
616                    // filled when the message is first sent,
617                    // it is only populated if the message is routed to another
618                    // destination like the DLQ
619                    if (message.getOriginalDestination() != null) {
620                        message.setOriginalDestination(message.getDestination());
621                    }
622                    if (message.getOriginalTransactionId() != null) {
623                        message.setOriginalTransactionId(message.getTransactionId());
624                    }
625
626                    ActiveMQTopic advisoryTopic;
627                    if (destination.isQueue()) {
628                        advisoryTopic = AdvisorySupport.getNoQueueConsumersAdvisoryTopic(destination);
629                    } else {
630                        advisoryTopic = AdvisorySupport.getNoTopicConsumersAdvisoryTopic(destination);
631                    }
632                    message.setDestination(advisoryTopic);
633                    message.setTransactionId(null);
634
635                    // Disable flow control for this since since we don't want
636                    // to block.
637                    boolean originalFlowControl = context.isProducerFlowControl();
638                    try {
639                        context.setProducerFlowControl(false);
640                        ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
641                        producerExchange.setMutable(false);
642                        producerExchange.setConnectionContext(context);
643                        producerExchange.setProducerState(new ProducerState(new ProducerInfo()));
644                        context.getBroker().send(producerExchange, message);
645                    } finally {
646                        context.setProducerFlowControl(originalFlowControl);
647                    }
648
649                }
650            }
651        }
652    }
653
654    @Override
655    public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception {
656    }
657
658    public final int getStoreUsageHighWaterMark() {
659        return this.storeUsageHighWaterMark;
660    }
661
662    public void setStoreUsageHighWaterMark(int storeUsageHighWaterMark) {
663        this.storeUsageHighWaterMark = storeUsageHighWaterMark;
664    }
665
666    protected final void waitForSpace(ConnectionContext context,ProducerBrokerExchange producerBrokerExchange, Usage<?> usage, String warning) throws IOException, InterruptedException, ResourceAllocationException {
667        waitForSpace(context, producerBrokerExchange, usage, 100, warning);
668    }
669
670    protected final void waitForSpace(ConnectionContext context, ProducerBrokerExchange producerBrokerExchange, Usage<?> usage, int highWaterMark, String warning) throws IOException, InterruptedException, ResourceAllocationException {
671        if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) {
672            getLog().debug("sendFailIfNoSpace, forcing exception on send, usage: {}: {}", usage, warning);
673            throw new ResourceAllocationException(warning);
674        }
675        if (!context.isNetworkConnection() && systemUsage.getSendFailIfNoSpaceAfterTimeout() != 0) {
676            if (!usage.waitForSpace(systemUsage.getSendFailIfNoSpaceAfterTimeout(), highWaterMark)) {
677                getLog().debug("sendFailIfNoSpaceAfterTimeout expired, forcing exception on send, usage: {}: {}", usage, warning);
678                throw new ResourceAllocationException(warning);
679            }
680        } else {
681            long start = System.currentTimeMillis();
682            long nextWarn = start;
683            producerBrokerExchange.blockingOnFlowControl(true);
684            destinationStatistics.getBlockedSends().increment();
685            while (!usage.waitForSpace(1000, highWaterMark)) {
686                if (context.getStopping().get()) {
687                    throw new IOException("Connection closed, send aborted.");
688                }
689
690                long now = System.currentTimeMillis();
691                if (now >= nextWarn) {
692                    getLog().info("{}: {} (blocking for: {}s)", new Object[]{ usage, warning, new Long(((now - start) / 1000))});
693                    nextWarn = now + blockedProducerWarningInterval;
694                }
695            }
696            long finish = System.currentTimeMillis();
697            long totalTimeBlocked = finish - start;
698            destinationStatistics.getBlockedTime().addTime(totalTimeBlocked);
699            producerBrokerExchange.incrementTimeBlocked(this,totalTimeBlocked);
700            producerBrokerExchange.blockingOnFlowControl(false);
701        }
702    }
703
704    protected abstract Logger getLog();
705
706    public void setSlowConsumerStrategy(SlowConsumerStrategy slowConsumerStrategy) {
707        this.slowConsumerStrategy = slowConsumerStrategy;
708    }
709
710    @Override
711    public SlowConsumerStrategy getSlowConsumerStrategy() {
712        return this.slowConsumerStrategy;
713    }
714
715
716    @Override
717    public boolean isPrioritizedMessages() {
718        return this.prioritizedMessages;
719    }
720
721    public void setPrioritizedMessages(boolean prioritizedMessages) {
722        this.prioritizedMessages = prioritizedMessages;
723        if (store != null) {
724            store.setPrioritizedMessages(prioritizedMessages);
725        }
726    }
727
728    /**
729     * @return the inactiveTimeoutBeforeGC
730     */
731    @Override
732    public long getInactiveTimeoutBeforeGC() {
733        return this.inactiveTimeoutBeforeGC;
734    }
735
736    /**
737     * @param inactiveTimeoutBeforeGC the inactiveTimeoutBeforeGC to set
738     */
739    public void setInactiveTimeoutBeforeGC(long inactiveTimeoutBeforeGC) {
740        this.inactiveTimeoutBeforeGC = inactiveTimeoutBeforeGC;
741    }
742
743    /**
744     * @return the gcIfInactive
745     */
746    public boolean isGcIfInactive() {
747        return this.gcIfInactive;
748    }
749
750    /**
751     * @param gcIfInactive the gcIfInactive to set
752     */
753    public void setGcIfInactive(boolean gcIfInactive) {
754        this.gcIfInactive = gcIfInactive;
755    }
756
757    /**
758     * Indicate if it is ok to gc destinations that have only network consumers
759     * @param gcWithNetworkConsumers
760     */
761    public void setGcWithNetworkConsumers(boolean gcWithNetworkConsumers) {
762        this.gcWithNetworkConsumers = gcWithNetworkConsumers;
763    }
764
765    public boolean isGcWithNetworkConsumers() {
766        return gcWithNetworkConsumers;
767    }
768
769    @Override
770    public void markForGC(long timeStamp) {
771        if (isGcIfInactive() && this.lastActiveTime == 0 && isActive() == false
772                && destinationStatistics.messages.getCount() == 0 && getInactiveTimeoutBeforeGC() > 0l) {
773            this.lastActiveTime = timeStamp;
774        }
775    }
776
777    @Override
778    public boolean canGC() {
779        boolean result = false;
780        if (isGcIfInactive()&& this.lastActiveTime != 0l) {
781            if ((System.currentTimeMillis() - this.lastActiveTime) >= getInactiveTimeoutBeforeGC()) {
782                result = true;
783            }
784        }
785        return result;
786    }
787
788    public void setReduceMemoryFootprint(boolean reduceMemoryFootprint) {
789        this.reduceMemoryFootprint = reduceMemoryFootprint;
790    }
791
792    public boolean isReduceMemoryFootprint() {
793        return this.reduceMemoryFootprint;
794    }
795
796    @Override
797    public boolean isDoOptimzeMessageStorage() {
798        return doOptimzeMessageStorage;
799    }
800
801    @Override
802    public void setDoOptimzeMessageStorage(boolean doOptimzeMessageStorage) {
803        this.doOptimzeMessageStorage = doOptimzeMessageStorage;
804    }
805
806    public int getOptimizeMessageStoreInFlightLimit() {
807        return optimizeMessageStoreInFlightLimit;
808    }
809
810    public void setOptimizeMessageStoreInFlightLimit(int optimizeMessageStoreInFlightLimit) {
811        this.optimizeMessageStoreInFlightLimit = optimizeMessageStoreInFlightLimit;
812    }
813
814
815    @Override
816    public abstract List<Subscription> getConsumers();
817
818    protected boolean hasRegularConsumers(List<Subscription> consumers) {
819        boolean hasRegularConsumers = false;
820        for (Subscription subscription: consumers) {
821            if (!subscription.getConsumerInfo().isNetworkSubscription()) {
822                hasRegularConsumers = true;
823                break;
824            }
825        }
826        return hasRegularConsumers;
827    }
828
829    public ConnectionContext createConnectionContext() {
830        ConnectionContext answer = new ConnectionContext(new NonCachedMessageEvaluationContext());
831        answer.setBroker(this.broker);
832        answer.getMessageEvaluationContext().setDestination(getActiveMQDestination());
833        answer.setSecurityContext(SecurityContext.BROKER_SECURITY_CONTEXT);
834        return answer;
835    }
836
837    protected MessageAck convertToNonRangedAck(MessageAck ack, MessageReference node) {
838        // the original ack may be a ranged ack, but we are trying to delete
839        // a specific
840        // message store here so we need to convert to a non ranged ack.
841        if (ack.getMessageCount() > 0) {
842            // Dup the ack
843            MessageAck a = new MessageAck();
844            ack.copy(a);
845            ack = a;
846            // Convert to non-ranged.
847            ack.setMessageCount(1);
848        }
849        // always use node messageId so we can access entry/data Location
850        ack.setFirstMessageId(node.getMessageId());
851        ack.setLastMessageId(node.getMessageId());
852        return ack;
853    }
854
855    protected boolean isDLQ() {
856        return destination.isDLQ();
857    }
858
859    @Override
860    public void duplicateFromStore(Message message, Subscription durableSub) {
861        ConnectionContext connectionContext = createConnectionContext();
862        getLog().warn("duplicate message from store {}, redirecting for dlq processing", message.getMessageId());
863        Throwable cause = new Throwable("duplicate from store for " + destination);
864        message.setRegionDestination(this);
865        broker.getRoot().sendToDeadLetterQueue(connectionContext, message, null, cause);
866        MessageAck messageAck = new MessageAck(message, MessageAck.POSION_ACK_TYPE, 1);
867        messageAck.setPoisonCause(cause);
868        try {
869            acknowledge(connectionContext, durableSub, messageAck, message);
870        } catch (IOException e) {
871            getLog().error("Failed to acknowledge duplicate message {} from {} with {}", message.getMessageId(), destination, messageAck);
872        }
873    }
874
875    public void setPersistJMSRedelivered(boolean persistJMSRedelivered) {
876        this.persistJMSRedelivered = persistJMSRedelivered;
877    }
878
879    public boolean isPersistJMSRedelivered() {
880        return persistJMSRedelivered;
881    }
882}