Search in sources :

Example 1 with SwingWorker

use of swingthreads.SwingWorker in project vcell by virtualcell.

the class ClientTaskDispatcher method dispatch.

/**
 * Insert the method's description here.
 * Creation date: (5/31/2004 5:37:06 PM)
 * @param tasks cbit.vcell.desktop.controls.ClientTask[]
 */
public static void dispatch(final Component requester, final Hashtable<String, Object> hash, final AsynchClientTask[] tasks, final ProgressDialog customDialog, final boolean bShowProgressPopup, final boolean bKnowProgress, final boolean cancelable, final ProgressDialogListener progressDialogListener, final boolean bInputBlocking) {
    // check tasks - swing non-blocking can be only at the end
    entryCounter++;
    if (entryCounter > 1) {
        System.out.println("Reentrant");
    }
    // }
    if (lg.isInfoEnabled()) {
        hash.put(STACK_TRACE_ARRAY, Thread.currentThread().getStackTrace());
    }
    if (bShowProgressPopup && requester == null) {
        System.out.println("ClientTaskDispatcher.dispatch(), requester is null, dialog has no parent, please try best to fix it!!!");
        Thread.dumpStack();
    }
    final List<AsynchClientTask> taskList = new ArrayList<AsynchClientTask>();
    for (int i = 0; i < tasks.length; i++) {
        if (tasks[i].getTaskType() == AsynchClientTask.TASKTYPE_SWING_NONBLOCKING && i < tasks.length - 1) {
            throw new RuntimeException("SWING_NONBLOCKING task only permitted as last task");
        }
        taskList.add(tasks[i]);
        if (lg.isDebugEnabled()) {
            lg.debug("added task name " + tasks[i].getTaskName());
        }
    }
    final String threadBaseName = "ClientTaskDispatcher " + (serial++) + ' ';
    // dispatch tasks to a new worker
    SwingWorker worker = new SwingWorker() {

        private AsynchProgressPopup pp = null;

        private Window windowParent = null;

        private Component focusOwner = null;

        public Object construct() {
            if (bShowProgressPopup) {
                if (customDialog == null) {
                    pp = new AsynchProgressPopup(requester, "WORKING...", "Initializing request", Thread.currentThread(), bInputBlocking, bKnowProgress, cancelable, progressDialogListener);
                } else {
                    pp = new AsynchProgressPopup(requester, customDialog, Thread.currentThread(), bInputBlocking, bKnowProgress, cancelable, progressDialogListener);
                }
                if (bInputBlocking) {
                    pp.startKeepOnTop();
                } else {
                    pp.start();
                }
            }
            if (requester != null) {
                windowParent = GuiUtils.getWindowForComponent(requester);
            }
            try {
                if (windowParent != null) {
                    focusOwner = FocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
                    SwingUtilities.invokeAndWait(new Runnable() {

                        public void run() {
                            ClientMDIManager.blockWindow(windowParent);
                            windowParent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        }
                    });
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < taskList.size(); i++) {
                // run all tasks
                // after abort, run only non-skippable tasks
                // also skip selected tasks specified by conditionalSkip tag
                final AsynchClientTask currentTask = taskList.get(i);
                try {
                    currentTask.setClientTaskStatusSupport(pp);
                    setSwingWorkerThreadName(this, threadBaseName + currentTask.getTaskName());
                    // System.out.println("DISPATCHING: "+currentTask.getTaskName()+" at "+ new Date(System.currentTimeMillis()));
                    if (pp != null) {
                        pp.setVisible(currentTask.showProgressPopup());
                        if (!bKnowProgress) {
                            // beginning of task
                            pp.setProgress(i * 100 / taskList.size());
                        }
                        pp.setMessage(currentTask.getTaskName());
                    }
                    boolean shouldRun = !hash.containsKey(HASH_DATA_ERROR);
                    if (hash.containsKey(TASK_ABORTED_BY_ERROR) && currentTask.skipIfAbort()) {
                        shouldRun = false;
                    }
                    if (hash.containsKey(TASKS_TO_BE_SKIPPED)) {
                        String[] toSkip = (String[]) hash.get(TASKS_TO_BE_SKIPPED);
                        if (BeanUtils.arrayContains(toSkip, currentTask.getClass().getName())) {
                            shouldRun = false;
                        }
                    }
                    if (pp != null && pp.isInterrupted()) {
                        recordException(UserCancelException.CANCEL_GENERIC, hash);
                    }
                    if (hash.containsKey(TASK_ABORTED_BY_USER)) {
                        UserCancelException exc = (UserCancelException) hash.get(TASK_ABORTED_BY_USER);
                        if (currentTask.skipIfCancel(exc)) {
                            shouldRun = false;
                        }
                    }
                    if (shouldRun) {
                        try {
                            if (currentTask.getTaskType() == AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
                                runTask(currentTask, hash, taskList);
                            } else if (currentTask.getTaskType() == AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
                                SwingUtilities.invokeAndWait(new Runnable() {

                                    public void run() {
                                        try {
                                            runTask(currentTask, hash, taskList);
                                        } catch (Throwable exc) {
                                            recordException(exc, hash);
                                        }
                                    }
                                });
                            } else if (currentTask.getTaskType() == AsynchClientTask.TASKTYPE_SWING_NONBLOCKING) {
                                SwingUtilities.invokeLater(new Runnable() {

                                    public void run() {
                                        try {
                                            runTask(currentTask, hash, taskList);
                                        } catch (Throwable exc) {
                                            recordException(exc, hash);
                                        }
                                    }
                                });
                            }
                        } catch (Throwable exc) {
                            recordException(exc, hash);
                        }
                    }
                // AsynchClientTask[] followupTasks = currentTask.getFollowupTasks();
                // if (followupTasks != null) {
                // for (int j = 0; j < followupTasks.length; j++) {
                // taskList.add(i+j+1, followupTasks[j]);
                // }
                // }
                } finally {
                    allTasks.remove(currentTask);
                }
            }
            return hash;
        }

        public void finished() {
            // System.out.println("DISPATCHING: finished() called at "+ new Date(System.currentTimeMillis()));
            entryCounter--;
            if (pp != null) {
                pp.stop();
            }
            if (hash.containsKey(TASK_ABORTED_BY_ERROR)) {
                // something went wrong
                StringBuffer allCausesErrorMessageSB = new StringBuffer();
                Throwable causeError = (Throwable) hash.get(TASK_ABORTED_BY_ERROR);
                do {
                    allCausesErrorMessageSB.append(causeError.getClass().getSimpleName() + "-" + (causeError.getMessage() == null || causeError.getMessage().length() == 0 ? "" : causeError.getMessage()));
                    allCausesErrorMessageSB.append("\n");
                } while ((causeError = causeError.getCause()) != null);
                if (requester == null) {
                    System.out.println("ClientTaskDispatcher.dispatch(), requester is null, dialog has no parent, please try best to fix it!!!");
                    Thread.dumpStack();
                }
                if (lg.isInfoEnabled()) {
                    Object obj = hash.get(STACK_TRACE_ARRAY);
                    StackTraceElement[] ste = BeanUtils.downcast(StackTraceElement[].class, obj);
                    if (ste != null) {
                        String stackTraceString = StringUtils.join(ste, '\n');
                        lg.info(stackTraceString, (Throwable) hash.get(TASK_ABORTED_BY_ERROR));
                    } else {
                        lg.info("Unexpected " + STACK_TRACE_ARRAY + " obj " + obj);
                    }
                }
                PopupGenerator.showErrorDialog(requester, allCausesErrorMessageSB.toString(), (Throwable) hash.get(TASK_ABORTED_BY_ERROR));
            } else if (hash.containsKey(TASK_ABORTED_BY_USER)) {
                // depending on where user canceled we might want to automatically start a new job
                dispatchFollowUp(hash);
            }
            FinalWindow fw = AsynchClientTask.fetch(hash, FINAL_WINDOW, FinalWindow.class, false);
            if (lg.isDebugEnabled() && fw != null) {
                lg.debug("FinalWindow retrieved from hash");
            }
            // focusOwner is legacy means of shifting focus -- FinalWindow is newer explicit invocatoin
            if (windowParent != null) {
                ClientMDIManager.unBlockWindow(windowParent);
                windowParent.setCursor(Cursor.getDefaultCursor());
                if (fw == null && focusOwner != null) {
                    fw = () -> {
                        windowParent.requestFocusInWindow();
                        focusOwner.requestFocusInWindow();
                    };
                    if (lg.isDebugEnabled()) {
                        lg.debug("FinalWindow built from " + windowParent.toString() + " and " + focusOwner.toString());
                    }
                }
            }
            if (fw != null) {
                if (lg.isDebugEnabled()) {
                    lg.debug("scheduling " + fw.getClass().getName() + ".run on " + fw.toString());
                    SwingUtilities.invokeLater(debugWrapper(fw));
                } else {
                    SwingUtilities.invokeLater(fw);
                }
            } else {
                lg.debug("no Final Window");
            }
        // BeanUtils.setCursorThroughout(frameParent, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        // System.out.println("DISPATCHING: done at "+ new Date(System.currentTimeMillis()));
        }
    };
    setSwingWorkerThreadName(worker, threadBaseName);
    allTasks.addAll(taskList);
    worker.start();
}
Also used : Window(java.awt.Window) ArrayList(java.util.ArrayList) UserCancelException(org.vcell.util.UserCancelException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SwingWorker(swingthreads.SwingWorker) EventObject(java.util.EventObject) AsynchProgressPopup(org.vcell.util.gui.AsynchProgressPopup) Component(java.awt.Component)

Aggregations

Component (java.awt.Component)1 Window (java.awt.Window)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ArrayList (java.util.ArrayList)1 EventObject (java.util.EventObject)1 UserCancelException (org.vcell.util.UserCancelException)1 AsynchProgressPopup (org.vcell.util.gui.AsynchProgressPopup)1 SwingWorker (swingthreads.SwingWorker)1