View Javadoc

1   /**
2    * Copyright 2010 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   */
15  
16  package org.kuali.student.common.ui.client.mvc;
17  
18  /**
19   * @author Kuali Student Team
20   */
21  import java.util.LinkedList;
22  
23  public class WorkQueue {
24      public static abstract class WorkItem {
25          private boolean canceled = false;
26  
27          public abstract void exec(final Callback<Boolean> onCompleteCallback);
28  
29          public boolean isCanceled() {
30              return this.canceled;
31          }
32  
33          protected void setCanceled(final boolean canceled) {
34              this.canceled = canceled;
35          }
36      }
37  
38      private boolean running = false;
39      private final LinkedList<WorkItem> queue = new LinkedList<WorkItem>();
40  
41      private final Callback<Boolean> onCompleteCallback = new Callback<Boolean>() {
42          @Override
43          public void exec(final Boolean value) {
44              processNext();
45          }
46      };
47  
48      public void clear() {
49          for (final WorkItem item : queue) {
50              item.setCanceled(true);
51          }
52          queue.clear();
53      }
54  
55      public boolean isRunning() {
56          return this.running;
57      }
58  
59      private void processNext() {
60          WorkItem item = null;
61          while (!queue.isEmpty() && (item = queue.removeFirst()) != null) {
62              if (item.isCanceled()) {
63                  item = null;
64              } else {
65                  break;
66              }
67          }
68          if (item == null) {
69              running = false;
70          } else {
71              item.exec(onCompleteCallback);
72          }
73      }
74  
75      public void submit(final WorkItem item) {
76          queue.add(item);
77          if (!running) {
78              running = true;
79              processNext();
80          }
81      }
82  }