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