001    /**
002     * Copyright 2010 The Kuali Foundation Licensed under the
003     * Educational Community License, Version 2.0 (the "License"); you may
004     * not use this file except in compliance with the License. You may
005     * obtain a copy of the License at
006     *
007     * http://www.osedu.org/licenses/ECL-2.0
008     *
009     * Unless required by applicable law or agreed to in writing,
010     * software distributed under the License is distributed on an "AS IS"
011     * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
012     * or implied. See the License for the specific language governing
013     * permissions and limitations under the License.
014     */
015    
016    package org.kuali.student.common.ui.client.mvc;
017    
018    /**
019     * @author Kuali Student Team
020     */
021    import java.util.LinkedList;
022    
023    public class WorkQueue {
024        public static abstract class WorkItem {
025            private boolean canceled = false;
026    
027            public abstract void exec(final Callback<Boolean> onCompleteCallback);
028    
029            public boolean isCanceled() {
030                return this.canceled;
031            }
032    
033            protected void setCanceled(final boolean canceled) {
034                this.canceled = canceled;
035            }
036        }
037    
038        private boolean running = false;
039        private final LinkedList<WorkItem> queue = new LinkedList<WorkItem>();
040    
041        private final Callback<Boolean> onCompleteCallback = new Callback<Boolean>() {
042            @Override
043            public void exec(final Boolean value) {
044                processNext();
045            }
046        };
047    
048        public void clear() {
049            for (final WorkItem item : queue) {
050                item.setCanceled(true);
051            }
052            queue.clear();
053        }
054    
055        public boolean isRunning() {
056            return this.running;
057        }
058    
059        private void processNext() {
060            WorkItem item = null;
061            while (!queue.isEmpty() && (item = queue.removeFirst()) != null) {
062                if (item.isCanceled()) {
063                    item = null;
064                } else {
065                    break;
066                }
067            }
068            if (item == null) {
069                running = false;
070            } else {
071                item.exec(onCompleteCallback);
072            }
073        }
074    
075        public void submit(final WorkItem item) {
076            queue.add(item);
077            if (!running) {
078                running = true;
079                processNext();
080            }
081        }
082    }