001: package org.swingml.task;
002:
003: import java.util.*;
004:
005: import org.swingml.task.monitoring.*;
006:
007: /**
008: * @author CrossLogic
009: */
010: public class TaskExecutor {
011:
012: private static TaskExecutor instance;
013:
014: public static TaskExecutor getInstance() {
015: if (instance == null) {
016: instance = new TaskExecutor();
017: }
018:
019: return instance;
020: }
021:
022: private TaskExecutor() {
023: super ();
024: }
025:
026: /**
027: * This method is typically called from Swing, and will put a task into the
028: * queue of tasks to be processed by the long running operation thread. This
029: * method always queues the task to run without a modal dialog window. To
030: * use a modal dialog window, see queueTask(ITask, boolean).
031: *
032: * @param task
033: * @param showModalDialog
034: */
035: public Object runTask(ITask task) {
036: return runTask(task, false);
037: }
038:
039: /**
040: * This method is typically called from Swing, and will put a task into the
041: * queue of tasks to be processed by the long running operation thread. If
042: * the showModalDialog parameter is true, a modal window will open with a
043: * progress bar for the task. The window will close when the task completes,
044: * or if the user clicks the "hide" button.
045: *
046: * @param task
047: * @param showModalDialog
048: */
049: public Object runTask(ITask task, boolean showModalDialog) {
050: Object result = null;
051: if (task != null) {
052: // Find pre and post execute tasks and enqueue them all
053: List tasks = new ArrayList();
054:
055: // Add pre execute tasks
056: AbstractTask yellowTask = (AbstractTask) task;
057: List preExecutes = yellowTask.getPreExecuteTasks();
058: if (preExecutes != null && preExecutes.size() > 0) {
059: tasks.addAll(preExecutes);
060: }
061:
062: // Add the task itself
063: tasks.add(yellowTask);
064:
065: // Add post execute tasks
066: List postExecutes = yellowTask.getPostExecuteTasks();
067: if (postExecutes != null && postExecutes.size() > 0) {
068: tasks.addAll(postExecutes);
069: }
070:
071: // Queue them all to run
072: result = runTasks(tasks, showModalDialog);
073: }
074: return result;
075: }
076:
077: /**
078: * Queue the given tasks to be run.
079: *
080: * @param someTasks
081: * @param showModalDialog
082: */
083: private Object runTasks(List someTasks, boolean showModalDialog) {
084: Object finalResult = null;
085: if (someTasks != null && someTasks.size() > 0) {
086:
087: Iterator schmiterator = someTasks.iterator();
088: while (schmiterator.hasNext()) {
089: Object aTask = schmiterator.next();
090: if (aTask instanceof ITask) {
091: final ITask task = (ITask) aTask;
092:
093: // Show the dialog?
094: if (showModalDialog) {
095: TaskMonitorDialog.getInstance().prepare(task);
096: }
097: Object executeResult = task.execute();
098: finalResult = task.onComplete(executeResult);
099: }
100: }
101: }
102: return finalResult;
103: }
104: }
|