001    /**
002     * Copyright 2004-2012 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.common.threads;
017    
018    import java.util.List;
019    
020    import org.kuali.common.threads.listener.ProgressEvent;
021    
022    /**
023     * Thread for iterating over the portion of a list determined by offset and length. An ElementHandler is invoked for
024     * each element
025     *
026     * @param <T>
027     */
028    public class ListIteratorThread<T> implements Runnable {
029    
030        // The context for the iteration
031        ListIteratorContext<T> context;
032    
033        public ListIteratorThread() {
034            this(null);
035        }
036    
037        public ListIteratorThread(ListIteratorContext<T> context) {
038            super();
039            this.context = context;
040        }
041    
042        
043        public void run() {
044            // Extract some local variables for convenience
045            int offset = context.getOffset();
046            int length = context.getLength();
047            List<T> list = context.getList();
048            ElementHandler<T> handler = context.getElementHandler();
049    
050            for (int i = offset; i < offset + length; i++) {
051                // Something has gone wrong, shutdown immediately
052                if (context.getThreadHandler().isStopThreads()) {
053                    break;
054                }
055    
056                // Pull out an element
057                T element = list.get(i);
058    
059                // Let the ElementHandler do something with it
060                handler.handleElement(context, i, element);
061    
062                // Create a progress event each time an element gets handled
063                ProgressEvent<T> event = new ProgressEvent<T>();
064                event.setElement(element);
065                event.setIndex(i);
066    
067                // Fire the notifier
068                context.getNotifier().notify(event);
069            }
070        }
071    
072        public ListIteratorContext<T> getContext() {
073            return context;
074        }
075    
076        public void setContext(ListIteratorContext<T> context) {
077            this.context = context;
078        }
079    
080    }