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.component.feed;
018    
019    import java.util.Date;
020    import java.util.List;
021    
022    import org.apache.camel.Exchange;
023    import org.apache.camel.Processor;
024    
025    /**
026     * Consumer to poll feeds and return each entry from the feed step by step.
027     *
028     */
029    public abstract class FeedEntryPollingConsumer extends FeedPollingConsumer {
030        protected int entryIndex;
031        protected EntryFilter entryFilter;
032        protected List list;
033    
034        public FeedEntryPollingConsumer(FeedEndpoint endpoint, Processor processor, boolean filter, Date lastUpdate) {
035            super(endpoint, processor);
036            if (filter) {
037                entryFilter = createEntryFilter(lastUpdate);
038            }
039        }
040    
041        public void poll() throws Exception {
042            Object feed = createFeed();
043            populateList(feed);   
044    
045            while (hasNextEntry()) {
046                Object entry = list.get(entryIndex--);
047    
048                boolean valid = true;
049                if (entryFilter != null) {
050                    valid = entryFilter.isValidEntry(endpoint, feed, entry);
051                }
052                if (valid) {
053                    Exchange exchange = endpoint.createExchange(feed, entry);
054                    getProcessor().process(exchange);
055                    // return and wait for the next poll to continue from last time (this consumer is stateful)
056                    return;
057                }
058            }
059    
060            // reset list to be able to poll again
061            resetList();
062        }
063    
064        protected abstract EntryFilter createEntryFilter(Date lastUpdate);
065        
066        protected abstract void resetList();
067    
068        protected abstract void populateList(Object feed) throws Exception; 
069        
070        private boolean hasNextEntry() {
071            return entryIndex >= 0;
072        }
073    }