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     */
017    package org.apache.camel.impl;
018    
019    import java.util.concurrent.ScheduledExecutorService;
020    
021    import org.apache.camel.BatchConsumer;
022    import org.apache.camel.Endpoint;
023    import org.apache.camel.Exchange;
024    import org.apache.camel.Processor;
025    import org.apache.camel.ShutdownRunningTask;
026    import org.apache.camel.spi.ShutdownAware;
027    import org.apache.camel.spi.UriParam;
028    import org.slf4j.Logger;
029    import org.slf4j.LoggerFactory;
030    
031    /**
032     * A useful base class for any consumer which is polling batch based
033     */
034    public abstract class ScheduledBatchPollingConsumer extends ScheduledPollConsumer implements BatchConsumer, ShutdownAware {
035        private static final Logger LOG = LoggerFactory.getLogger(ScheduledBatchPollingConsumer.class);
036        protected volatile ShutdownRunningTask shutdownRunningTask;
037        protected volatile int pendingExchanges;
038        @UriParam
039        protected int maxMessagesPerPoll;
040    
041        public ScheduledBatchPollingConsumer(Endpoint endpoint, Processor processor) {
042            super(endpoint, processor);
043        }
044    
045        public ScheduledBatchPollingConsumer(Endpoint endpoint, Processor processor, ScheduledExecutorService executor) {
046            super(endpoint, processor, executor);
047        }
048    
049        @Override
050        public boolean deferShutdown(ShutdownRunningTask shutdownRunningTask) {
051            // store a reference what to do in case when shutting down and we have pending messages
052            this.shutdownRunningTask = shutdownRunningTask;
053            // do not defer shutdown
054            return false;
055        }
056    
057        @Override
058        public int getPendingExchangesSize() {
059            int answer;
060            // only return the real pending size in case we are configured to complete all tasks
061            if (ShutdownRunningTask.CompleteAllTasks == shutdownRunningTask) {
062                answer = pendingExchanges;
063            } else {
064                answer = 0;
065            }
066    
067            if (answer == 0 && isPolling()) {
068                // force at least one pending exchange if we are polling as there is a little gap
069                // in the processBatch method and until an exchange gets enlisted as in-flight
070                // which happens later, so we need to signal back to the shutdown strategy that
071                // there is a pending exchange. When we are no longer polling, then we will return 0
072                LOG.trace("Currently polling so returning 1 as pending exchanges");
073                answer = 1;
074            }
075    
076            return answer;
077        }
078    
079        @Override
080        public void prepareShutdown(boolean forced) {
081            // reset task as the state of the task is not to be preserved
082            // which otherwise may cause isBatchAllowed() to return a wrong answer
083            this.shutdownRunningTask = null;
084        }
085    
086        @Override
087        public void setMaxMessagesPerPoll(int maxMessagesPerPoll) {
088            this.maxMessagesPerPoll = maxMessagesPerPoll;
089        }
090    
091        /**
092         * Gets the maximum number of messages as a limit to poll at each polling.
093         * <p/>
094         * Is default unlimited, but use 0 or negative number to disable it as unlimited.
095         *
096         * @return max messages to poll
097         */
098        public int getMaxMessagesPerPoll() {
099            return maxMessagesPerPoll;
100        }
101    
102        @Override
103        public boolean isBatchAllowed() {
104            // stop if we are not running
105            boolean answer = isRunAllowed();
106            if (!answer) {
107                return false;
108            }
109    
110            if (shutdownRunningTask == null) {
111                // we are not shutting down so continue to run
112                return true;
113            }
114    
115            // we are shutting down so only continue if we are configured to complete all tasks
116            return ShutdownRunningTask.CompleteAllTasks == shutdownRunningTask;
117        }
118    
119        @Override
120        protected void processEmptyMessage() throws Exception {
121            Exchange exchange = getEndpoint().createExchange();
122            // enrich exchange, so we send an empty message with the batch details
123            exchange.setProperty(Exchange.BATCH_INDEX, 0);
124            exchange.setProperty(Exchange.BATCH_SIZE, 1);
125            exchange.setProperty(Exchange.BATCH_COMPLETE, true);
126            log.debug("Sending empty message as there were no messages from polling: {}", this.getEndpoint());
127            getProcessor().process(exchange);
128        }
129    }