Search in sources :

Example 36 with UserCancelException

use of org.vcell.util.UserCancelException in project vcell by virtualcell.

the class TopLevelWindowManager method createGeometry.

void createGeometry(final Geometry currentGeometry, final AsynchClientTask[] afterTasks, String selectDialogTitle, final String applyGeometryButtonText, DocumentWindowManager.GeometrySelectionInfo preSelect) {
    boolean bCancellable = false;
    try {
        final Hashtable<String, Object> hash = new Hashtable<String, Object>();
        Vector<AsynchClientTask> createGeomTaskV = new Vector<AsynchClientTask>();
        final DocumentWindowManager.GeometrySelectionInfo geometrySelectionInfo = (preSelect == null ? selectGeometry(currentGeometry != null && currentGeometry.getDimension() > 0, selectDialogTitle) : preSelect);
        hash.put(B_SHOW_OLD_GEOM_EDITOR, false);
        if (geometrySelectionInfo.getDocumentCreationInfo() != null) {
            if (ClientRequestManager.isImportGeometryType(geometrySelectionInfo.getDocumentCreationInfo())) {
                bCancellable = geometrySelectionInfo.getDocumentCreationInfo().getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ || geometrySelectionInfo.getDocumentCreationInfo().getOption() == VCDocument.GEOM_OPTION_BLENDER;
                // Create imported Geometry
                createGeomTaskV.addAll(Arrays.asList(((ClientRequestManager) getRequestManager()).createNewGeometryTasks(this, geometrySelectionInfo.getDocumentCreationInfo(), afterTasks, applyGeometryButtonText)));
            } else {
                // Create Analytic Geometry
                hash.put(B_SHOW_OLD_GEOM_EDITOR, true);
                createGeomTaskV.addAll(Arrays.asList(((ClientRequestManager) getRequestManager()).createNewDocument(this, geometrySelectionInfo.getDocumentCreationInfo())));
                createGeomTaskV.addAll(Arrays.asList(afterTasks));
            }
            hash.put("guiParent", (Component) getComponent());
            hash.put("requestManager", getRequestManager());
        } else {
            // Copy from WorkSpace
            createGeomTaskV.add(new AsynchClientTask("loading Geometry", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

                @Override
                public void run(Hashtable<String, Object> hashTable) throws Exception {
                    final Vector<AsynchClientTask> runtimeTasksV = new Vector<AsynchClientTask>();
                    VCDocument.DocumentCreationInfo workspaceDocCreateInfo = null;
                    if (currentGeometry.getGeometrySpec().getNumAnalyticOrCSGSubVolumes() > 0 && currentGeometry.getGeometrySpec().getImage() == null) {
                        workspaceDocCreateInfo = new VCDocument.DocumentCreationInfo(VCDocumentType.GEOMETRY_DOC, VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC);
                    } else if (currentGeometry.getGeometrySpec().getImage() != null && currentGeometry.getGeometrySpec().getNumAnalyticOrCSGSubVolumes() == 0) {
                        workspaceDocCreateInfo = new VCDocument.DocumentCreationInfo(VCDocumentType.GEOMETRY_DOC, VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE);
                    } else {
                        throw new Exception("Unexpected image configuration for workspace geometry.");
                    }
                    runtimeTasksV.addAll(Arrays.asList(((ClientRequestManager) getRequestManager()).createNewGeometryTasks(TopLevelWindowManager.this, workspaceDocCreateInfo, afterTasks, applyGeometryButtonText)));
                    hashTable.put("guiParent", (Component) getComponent());
                    hashTable.put("requestManager", getRequestManager());
                    hashTable.put(ClientRequestManager.GEOM_FROM_WORKSPACE, currentGeometry);
                    new Thread(new Runnable() {

                        public void run() {
                            ClientTaskDispatcher.dispatch(getComponent(), hash, runtimeTasksV.toArray(new AsynchClientTask[0]), false, false, null, true);
                        }
                    }).start();
                }
            });
        }
        ClientTaskDispatcher.dispatch(getComponent(), hash, createGeomTaskV.toArray(new AsynchClientTask[0]), false, bCancellable, null, true);
    } catch (UserCancelException e1) {
        return;
    } catch (Exception e1) {
        e1.printStackTrace();
        DialogUtils.showErrorDialog(getComponent(), e1.getMessage(), e1);
    }
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) VCDocument(org.vcell.util.document.VCDocument) Hashtable(java.util.Hashtable) UserCancelException(org.vcell.util.UserCancelException) DataAccessException(org.vcell.util.DataAccessException) UserCancelException(org.vcell.util.UserCancelException) Component(java.awt.Component) Vector(java.util.Vector) GeometrySelectionInfo(cbit.vcell.client.DocumentWindowManager.GeometrySelectionInfo)

Example 37 with UserCancelException

use of org.vcell.util.UserCancelException in project vcell by virtualcell.

the class UserRegistrationManager method registrationOperationGUI.

public static void registrationOperationGUI(final RequestManager requestManager, final DocumentWindowManager currWindowManager, final ClientServerInfo currentClientServerInfo, final String userAction, final ClientServerManager clientServerManager) throws Exception {
    if (!(userAction.equals(LoginManager.USERACTION_REGISTER) || userAction.equals(LoginManager.USERACTION_EDITINFO) || userAction.equals(LoginManager.USERACTION_LOSTPASSWORD))) {
        throw new IllegalArgumentException(UserRegistrationOP.class.getName() + ".registrationOperationGUI:  Only New registration, Edit UserInfo or Lost Password allowed.");
    }
    if ((userAction.equals(LoginManager.USERACTION_REGISTER) || userAction.equals(LoginManager.USERACTION_LOSTPASSWORD)) && clientServerManager != null) {
        throw new IllegalArgumentException(UserRegistrationOP.class.getName() + ".registrationOperationGUI:  Register New User Info requires clientServerManager null.");
    }
    if (userAction.equals(LoginManager.USERACTION_EDITINFO) && clientServerManager == null) {
        throw new IllegalArgumentException(UserRegistrationOP.class.getName() + ".registrationOperationGUI:  Edit User Info requires clientServerManager not null.");
    }
    RegistrationService registrationService = null;
    if (clientServerManager != null) {
        registrationService = clientServerManager.getRegistrationProvider();
    } else {
        registrationService = VCellServiceHelper.getInstance().loadService(RegistrationService.class);
    }
    if (userAction.equals(LoginManager.USERACTION_LOSTPASSWORD)) {
        if (currentClientServerInfo.getUsername() == null || currentClientServerInfo.getUsername().length() == 0) {
            throw new IllegalArgumentException("Lost Password requires a VCell User Name.");
        }
        String result = PopupGenerator.showWarningDialog(currWindowManager, null, new UserMessage("Sending Password via email for user '" + currentClientServerInfo.getUsername() + "'\nusing currently registered email address.", new String[] { "OK", "Cancel" }, "OK"), null);
        if (!result.equals("OK")) {
            throw UserCancelException.CANCEL_GENERIC;
        }
        registrationService.sendLostPassword(currentClientServerInfo.getUsername());
        return;
    }
    final RegistrationService finalRegistrationProvider = registrationService;
    final String ORIGINAL_USER_INFO_HOLDER = "originalUserInfoHolder";
    // final String DIGESTED_USERIDS_KEY = "DIGESTED_USERIDS_KEY";
    AsynchClientTask gatherInfoTask = new AsynchClientTask("gathering user info for updating", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (userAction.equals(LoginManager.USERACTION_EDITINFO)) {
                UserInfo originalUserInfoHolder = finalRegistrationProvider.getUserInfo(clientServerManager.getUser().getID());
                hashTable.put(ORIGINAL_USER_INFO_HOLDER, originalUserInfoHolder);
            }
        }
    };
    final String NEW_USER_INFO_KEY = "NEW_USER_INFO_KEY";
    AsynchClientTask showPanelTask = new AsynchClientTask("please fill the user registration form", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (registrationPanel == null) {
                registrationPanel = new RegistrationPanel();
            } else {
                if (currentClientServerInfo.getUsername() != null) {
                    // another user already connected
                    registrationPanel.reset();
                }
            }
            UserInfo originalUserInfoHolder = (UserInfo) hashTable.get(ORIGINAL_USER_INFO_HOLDER);
            ;
            if (userAction.equals(LoginManager.USERACTION_EDITINFO) && originalUserInfoHolder != null) {
                registrationPanel.setUserInfo(originalUserInfoHolder, true);
            }
            do {
                int result = DialogUtils.showComponentOKCancelDialog(currWindowManager.getComponent(), registrationPanel, (userAction.equals(LoginManager.USERACTION_REGISTER) ? "Create New User Registration" : "Update Registration Information (" + clientServerManager.getUser().getName() + ")"));
                if (result != JOptionPane.OK_OPTION) {
                    throw UserCancelException.CANCEL_GENERIC;
                }
                UserRegistrationOP.NewPasswordUserInfo newUserInfo = registrationPanel.getUserInfo();
                if (userAction.equals(LoginManager.USERACTION_EDITINFO)) {
                    // set existing digestPassword
                    if (newUserInfo.digestedPassword0 == null && originalUserInfoHolder.digestedPassword0 != null) {
                        newUserInfo.digestedPassword0 = originalUserInfoHolder.digestedPassword0;
                    }
                    if (newUserInfo.otherDigestedPassword == null && originalUserInfoHolder.digestedPassword0 != null) {
                        newUserInfo.otherDigestedPassword = originalUserInfoHolder.digestedPassword0;
                    }
                }
                try {
                    if (!checkUserInfo(currWindowManager, originalUserInfoHolder, newUserInfo, userAction)) {
                        PopupGenerator.showInfoDialog(currWindowManager, "No registration information has changed.");
                        continue;
                    }
                } catch (UserCancelException ex) {
                    continue;
                } catch (Exception ex) {
                    PopupGenerator.showErrorDialog(currWindowManager, ex.getMessage());
                    continue;
                }
                hashTable.put(NEW_USER_INFO_KEY, newUserInfo);
                break;
            } while (true);
        }
    };
    // final String USERID_NOT_UNIQUE = "USERID_NOT_UNIQUE";
    AsynchClientTask updateDbTask = new AsynchClientTask(userAction.equals(LoginManager.USERACTION_REGISTER) ? "registering new user" : "updating user info", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            UserInfo newUserInfo = (UserInfo) hashTable.get(NEW_USER_INFO_KEY);
            // }
            try {
                UserInfo registeredUserInfo = finalRegistrationProvider.insertUserInfo(newUserInfo, (userAction.equals(LoginManager.USERACTION_EDITINFO) ? true : false));
                hashTable.put("registeredUserInfo", registeredUserInfo);
            } catch (UseridIDExistsException e) {
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Error " + (userAction.equals(LoginManager.USERACTION_REGISTER) ? "registering new user" : "updating user info ") + " (" + newUserInfo.userid + "), " + e.getMessage());
            }
        }
    };
    AsynchClientTask connectTask = new AsynchClientTask("user logging in", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            UserInfo registeredUserInfo = (UserInfo) hashTable.get("registeredUserInfo");
            try {
                if (userAction.equals(LoginManager.USERACTION_REGISTER)) {
                    try {
                        ClientServerInfo newClientServerInfo = VCellClient.createClientServerInfo(currentClientServerInfo, registeredUserInfo.userid, registeredUserInfo.digestedPassword0);
                        requestManager.connectToServer(currWindowManager, newClientServerInfo);
                    } finally {
                        ConnectionStatus connectionStatus = requestManager.getConnectionStatus();
                        if (connectionStatus.getStatus() != ConnectionStatus.CONNECTED) {
                            PopupGenerator.showErrorDialog(currWindowManager, "Automatic login of New user '" + registeredUserInfo.userid + "' failed.\n" + "Restart VCell and login as '" + registeredUserInfo.userid + "' to use new VCell account.");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Error logging in user " + " (" + registeredUserInfo.userid + "), " + e.getMessage());
            }
        }
    };
    AsynchClientTask useridErrorTask = new AsynchClientTask("re-enter userid...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, false, false) {

        @Override
        public void run(final Hashtable<String, Object> hashTable) throws Exception {
            if (hashTable.containsKey(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR)) {
                // retry if requested
                if (hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR) instanceof UseridIDExistsException) {
                    // Exception handled here, suppress ClientTaskDispatcher error dialog.
                    hashTable.remove(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR);
                    UserInfo newUserInfo = (UserInfo) hashTable.get(NEW_USER_INFO_KEY);
                    PopupGenerator.showErrorDialog(currWindowManager, "Login ID '" + newUserInfo.userid + "' cannot be used, enter a different one.");
                    // Use thread to restart registration process again
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                registrationOperationGUI(requestManager, currWindowManager, currentClientServerInfo, userAction, clientServerManager);
                            } catch (Exception e) {
                                e.printStackTrace();
                                DialogUtils.showErrorDialog(currWindowManager.getComponent(), e.getMessage());
                            }
                        }
                    }).start();
                }
            }
        }
    };
    ClientTaskDispatcher.dispatch(currWindowManager.getComponent(), new Hashtable<String, Object>(), new AsynchClientTask[] { gatherInfoTask, showPanelTask, updateDbTask, connectTask, useridErrorTask }, false);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Hashtable(java.util.Hashtable) UserCancelException(org.vcell.util.UserCancelException) ClientServerInfo(cbit.vcell.client.server.ClientServerInfo) UserInfo(org.vcell.util.document.UserInfo) RegistrationService(org.vcell.service.registration.RegistrationService) UseridIDExistsException(org.vcell.util.UseridIDExistsException) UserCancelException(org.vcell.util.UserCancelException) UserRegistrationOP(cbit.vcell.server.UserRegistrationOP) UseridIDExistsException(org.vcell.util.UseridIDExistsException) ConnectionStatus(cbit.vcell.client.server.ConnectionStatus) RegistrationPanel(cbit.vcell.desktop.RegistrationPanel)

Example 38 with UserCancelException

use of org.vcell.util.UserCancelException in project vcell by virtualcell.

the class ClientRequestManager method closeWindow.

/**
 * Insert the method's description here.
 * Creation date: (5/24/2005 1:48:09 PM)
 * @param windowID java.lang.String
 */
public boolean closeWindow(final java.lang.String windowID, final boolean exitIfLast) {
    // called from DocumentWindow or from DatabaseWindow
    final TopLevelWindowManager windowManager = getMdiManager().getWindowManager(windowID);
    if (windowManager instanceof DocumentWindowManager) {
        // we'll need to run some checks first
        getMdiManager().showWindow(windowID);
        getMdiManager().blockWindow(windowID);
        CloseOption closeOption = checkBeforeClosing((DocumentWindowManager) windowManager);
        if (closeOption.equals(CloseOption.CANCEL_CLOSE)) {
            // user canceled
            getMdiManager().unBlockWindow(windowID);
            return false;
        } else if (closeOption.equals(CloseOption.SAVE_AND_CLOSE)) {
            AsynchClientTask closeTask = new AsynchClientTask("closing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {

                @Override
                public void run(Hashtable<String, Object> hashTable) throws Exception {
                    // if there is error saving the document, try to unblock the window
                    if (hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR) != null) {
                        getMdiManager().unBlockWindow(windowID);
                        getMdiManager().showWindow(windowID);
                    } else {
                        long openWindows = getMdiManager().closeWindow(windowManager.getManagerID());
                        if (exitIfLast && (openWindows == 0)) {
                            setBExiting(true);
                            exitApplication();
                        }
                    }
                }

                @Override
                public boolean skipIfCancel(UserCancelException exc) {
                    // if save as new edition, don't skip
                    if (exc == UserCancelException.CANCEL_DELETE_OLD || exc == UserCancelException.CANCEL_NEW_NAME) {
                        return false;
                    } else {
                        return true;
                    }
                }
            };
            saveDocument((DocumentWindowManager) windowManager, true, closeTask);
            return true;
        } else {
            long openWindows = getMdiManager().closeWindow(windowID);
            if (exitIfLast && (openWindows == 0)) {
                setBExiting(true);
                exitApplication();
            }
            return true;
        }
    } else if (windowManager instanceof DatabaseWindowManager) {
        // nothing to check here, just close it
        long openWindows = getMdiManager().closeWindow(windowID);
        if (exitIfLast && (openWindows == 0)) {
            setBExiting(true);
            exitApplication();
        }
        return true;
    } else if (windowManager instanceof TestingFrameworkWindowManager) {
        // nothing to check here, just close it
        long openWindows = getMdiManager().closeWindow(windowID);
        if (exitIfLast && (openWindows == 0)) {
            setBExiting(true);
            exitApplication();
        }
        return true;
    } else if (windowManager instanceof BNGWindowManager) {
        // nothing to check here, just close it
        long openWindows = getMdiManager().closeWindow(windowID);
        if (exitIfLast && (openWindows == 0)) {
            setBExiting(true);
            exitApplication();
        }
        return true;
    } else if (windowManager instanceof FieldDataWindowManager) {
        // nothing to check here, just close it
        long openWindows = getMdiManager().closeWindow(windowID);
        if (exitIfLast && (openWindows == 0)) {
            setBExiting(true);
            exitApplication();
        }
        return true;
    } else {
        return false;
    }
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) UserCancelException(org.vcell.util.UserCancelException) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException) CSGObject(cbit.vcell.geometry.CSGObject)

Example 39 with UserCancelException

use of org.vcell.util.UserCancelException in project vcell by virtualcell.

the class GeometrySubVolumePanel method createAnalyticSubVolume.

public static AnalyticSubVolume createAnalyticSubVolume(Component requester, int dimensions, Coordinate center, String newSubVolName) throws UserCancelException {
    // Geometry g = getGeometry();
    // final int dim = g.getDimension();
    AddShapeJPanel addShapeJPanel = new AddShapeJPanel(dimensions);
    addShapeJPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
    addShapeJPanel.setDefaultCenter(center.getX(), center.getY(), center.getZ());
    // (getGeometry().getDimension() > 2?getGeometry().getOrigin().getZ()+getGeometry().getExtent().getZ()/2:null));
    while (true) {
        try {
            final boolean[] acceptFlag = new boolean[] { false };
            LWContainerHandle lwParent = LWNamespace.findLWOwner(requester);
            final JDialog d = new LWTitledDialog(lwParent, "Define New Subdomain Shape");
            // BeanUtils.centerOnComponent(d, GeometrySubVolumePanel.this);
            JPanel main = new JPanel();
            BoxLayout mainBoxLayout = new BoxLayout(main, BoxLayout.Y_AXIS);
            main.setLayout(mainBoxLayout);
            JPanel menuPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            menuPanel.add(LWNamespace.createRightSideIconMenuBar());
            main.add(menuPanel);
            JPanel addCancelJPanel = new JPanel();
            addCancelJPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
            BoxLayout addCancelBoxLayout = new BoxLayout(addCancelJPanel, BoxLayout.X_AXIS);
            addCancelJPanel.setLayout(addCancelBoxLayout);
            {
                JButton helpButton = new JButton("Help");
                helpButton.addActionListener(ae -> {
                    VcellHelpViewer.showStandaloneViewer();
                });
                addCancelJPanel.add(helpButton);
            }
            JButton addJButton = new JButton("New Subdomain");
            addJButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    d.dispose();
                    acceptFlag[0] = true;
                }
            });
            addCancelJPanel.add(addJButton);
            JButton cancelJButton = new JButton("Cancel");
            cancelJButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    d.dispose();
                }
            });
            addCancelJPanel.add(cancelJButton);
            main.add(addShapeJPanel);
            main.add(Box.createVerticalStrut(10));
            main.add(addCancelJPanel);
            main.add(Box.createVerticalStrut(10));
            addShapeJPanel.addPropertyChangeListener(new PropertyChangeListener() {

                public void propertyChange(PropertyChangeEvent evt) {
                    if (evt.getPropertyName().equals(AddShapeJPanel.PROPCHANGE_VALID_ANALYTIC)) {
                        addJButton.setEnabled(((Boolean) evt.getNewValue()));
                    }
                }
            });
            d.setModalityType(ModalityType.DOCUMENT_MODAL);
            // d.setModal(true);
            d.getContentPane().add(main);
            d.pack();
            d.setSize(new Dimension(400, 400));
            d.setVisible(true);
            if (acceptFlag[0]) {
                // new Expression(addShapeJPanel.getCurrentAnalyticExpression()), -1));
                return new AnalyticSubVolume(null, newSubVolName, new Expression(addShapeJPanel.getCurrentAnalyticExpression()), -1);
            } else {
                throw UserCancelException.CANCEL_GENERIC;
            }
        } catch (UserCancelException uce) {
            throw uce;
        } catch (Exception e1) {
            e1.printStackTrace();
            DialogUtils.showErrorDialog(requester, "Error adding shape:\n" + e1.getMessage(), e1);
        }
    }
}
Also used : SubVolume(cbit.vcell.geometry.SubVolume) ActionListener(java.awt.event.ActionListener) JDialog(javax.swing.JDialog) JTextField(javax.swing.JTextField) DownArrowIcon(org.vcell.util.gui.DownArrowIcon) ModalityType(java.awt.Dialog.ModalityType) CSGObject(cbit.vcell.geometry.CSGObject) Geometry(cbit.vcell.geometry.Geometry) GeometrySpec(cbit.vcell.geometry.GeometrySpec) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) JMenuItem(javax.swing.JMenuItem) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) LWContainerHandle(org.vcell.client.logicalwindow.LWContainerHandle) ScrollTable(org.vcell.util.gui.ScrollTable) DocumentEditorSubPanel(cbit.vcell.client.desktop.biomodel.DocumentEditorSubPanel) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) PropertyChangeEvent(java.beans.PropertyChangeEvent) Hashtable(java.util.Hashtable) LWNamespace(org.vcell.client.logicalwindow.LWNamespace) BoxLayout(javax.swing.BoxLayout) VcellHelpViewer(org.vcell.documentation.VcellHelpViewer) FlowLayout(java.awt.FlowLayout) JButton(javax.swing.JButton) JPopupMenu(javax.swing.JPopupMenu) LWTitledDialog(org.vcell.client.logicalwindow.LWTitledDialog) UtilCancelException(org.vcell.util.UtilCancelException) BorderFactory(javax.swing.BorderFactory) GridBagConstraints(java.awt.GridBagConstraints) Component(java.awt.Component) ActionEvent(java.awt.event.ActionEvent) DefaultCellEditor(javax.swing.DefaultCellEditor) Box(javax.swing.Box) TokenMangler(org.vcell.util.TokenMangler) Coordinate(org.vcell.util.Coordinate) Dimension(java.awt.Dimension) PropertyChangeListener(java.beans.PropertyChangeListener) DialogUtils(org.vcell.util.gui.DialogUtils) ClientTaskDispatcher(cbit.vcell.client.task.ClientTaskDispatcher) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) IssueManager(cbit.vcell.client.desktop.biomodel.IssueManager) JTable(javax.swing.JTable) EmptyBorder(javax.swing.border.EmptyBorder) Expression(cbit.vcell.parser.Expression) EtchedBorder(javax.swing.border.EtchedBorder) JPanel(javax.swing.JPanel) UserCancelException(org.vcell.util.UserCancelException) JPanel(javax.swing.JPanel) PropertyChangeEvent(java.beans.PropertyChangeEvent) FlowLayout(java.awt.FlowLayout) PropertyChangeListener(java.beans.PropertyChangeListener) ActionEvent(java.awt.event.ActionEvent) BoxLayout(javax.swing.BoxLayout) LWContainerHandle(org.vcell.client.logicalwindow.LWContainerHandle) JButton(javax.swing.JButton) UserCancelException(org.vcell.util.UserCancelException) Dimension(java.awt.Dimension) UtilCancelException(org.vcell.util.UtilCancelException) UserCancelException(org.vcell.util.UserCancelException) ActionListener(java.awt.event.ActionListener) Expression(cbit.vcell.parser.Expression) EmptyBorder(javax.swing.border.EmptyBorder) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) JDialog(javax.swing.JDialog) LWTitledDialog(org.vcell.client.logicalwindow.LWTitledDialog)

Example 40 with UserCancelException

use of org.vcell.util.UserCancelException 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

UserCancelException (org.vcell.util.UserCancelException)44 Hashtable (java.util.Hashtable)15 UtilCancelException (org.vcell.util.UtilCancelException)15 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)14 PropertyVetoException (java.beans.PropertyVetoException)11 DataAccessException (org.vcell.util.DataAccessException)10 Vector (java.util.Vector)9 ActionEvent (java.awt.event.ActionEvent)8 DataFormatException (java.util.zip.DataFormatException)8 BioModel (cbit.vcell.biomodel.BioModel)7 ActionListener (java.awt.event.ActionListener)7 IOException (java.io.IOException)7 Point (java.awt.Point)6 ArrayList (java.util.ArrayList)6 ImageException (cbit.image.ImageException)5 CSGObject (cbit.vcell.geometry.CSGObject)5 GeometryException (cbit.vcell.geometry.GeometryException)5 Structure (cbit.vcell.model.Structure)5 JButton (javax.swing.JButton)5 ProgrammingException (org.vcell.util.ProgrammingException)5