Example usage for com.google.gwt.user.client Window confirm

List of usage examples for com.google.gwt.user.client Window confirm

Introduction

In this page you can find the example usage for com.google.gwt.user.client Window confirm.

Prototype

public static boolean confirm(String msg) 

Source Link

Usage

From source file:org.openelis.modules.animalSampleLogin1.client.AnimalSampleLoginScreenUI.java

License:Open Source License

/**
 * Validates the data on the screen and based on the current state, executes
 * various service operations to commit the data.
 *///from   w ww  . ja v  a  2 s .c  om
@UiHandler("commit")
protected void commit(ClickEvent event) {
    Validation validation;

    finishEditing();

    validation = validate();

    switch (validation.getStatus()) {
    case WARNINGS:
        /*
         * show the warnings and ask the user if the data should still
         * be committed; commit only if the user says yes
         */
        if (!Window.confirm(getWarnings(validation.getExceptions(), true)))
            return;
        break;
    case FLAGGED:
        /*
         * some part of the screen has some operation that needs to be
         * completed before committing the data
         */
        return;
    case ERRORS:
        setError(Messages.get().gen_correctErrors());
        return;
    }

    switch (state) {
    case QUERY:
        commitQuery();
        break;
    case ADD:
        commitUpdate(false);
        break;
    case UPDATE:
        commitUpdate(false);
        break;
    }
}

From source file:org.openelis.modules.animalSampleLogin1.client.AnimalSampleLoginScreenUI.java

License:Open Source License

/**
 * Calls the service method to commit the data on the screen, to the
 * database. Shows any errors/warnings encountered during the commit,
 * otherwise loads the screen with the committed data.
 *///from www  .j  a v a2 s  . c  o  m
protected void commitUpdate(final boolean ignoreWarning) {
    if (isState(ADD))
        setBusy(Messages.get().gen_adding());
    else
        setBusy(Messages.get().gen_updating());

    if (commitUpdateCall == null) {
        commitUpdateCall = new AsyncCallbackUI<SampleManager1>() {
            public void success(SampleManager1 result) {
                Integer id;

                manager = result;
                /*
                 * if either a new sample or a quick entered one was fully
                 * logged in, create an event log to record that
                 */
                if (isFullLogin) {
                    try {
                        id = DictionaryCache.getIdBySystemName("log_type_sample_login");
                        EventLogService.get().add(id, Messages.get().sample_login(), Constants.table().SAMPLE,
                                manager.getSample().getId(), Constants.dictionary().LOG_LEVEL_INFO, null);
                        isFullLogin = false;
                    } catch (Exception e) {
                        Window.alert(e.getMessage());
                        logger.log(Level.SEVERE, e.getMessage(), e);
                        clearStatus();
                        return;
                    }
                }
                evaluateEdit();
                setData();
                setState(DISPLAY);
                fireDataChange();
                clearStatus();

                /*
                 * the cache and scriptlets are cleared only if the
                 * add/update succeeds because otherwise, they can't be used
                 * by any tabs if the user wants to change any data
                 */
                cache = null;
                clearScriptlets();
            }

            public void validationErrors(ValidationErrorsList e) {
                showErrors(e);
                if (!e.hasErrors() && (e.hasWarnings() || e.hasCautions()) && !ignoreWarning)
                    if (Window.confirm(getWarnings(e.getErrorList(), true)))
                        commitUpdate(true);
            }

            public void failure(Throwable e) {
                if (isState(ADD))
                    Window.alert("commitAdd(): " + e.getMessage());
                else
                    Window.alert("commitUpdate(): " + e.getMessage());
                logger.log(Level.SEVERE, e.getMessage(), e);
                clearStatus();
            }
        };
    }
    SampleService1.get().update(manager, ignoreWarning, commitUpdateCall);
}

From source file:org.openelis.modules.animalSampleLogin1.client.AnimalSampleLoginScreenUI.java

License:Open Source License

/**
 * Calls the service method to merge a quick-entered sample that has this
 * accession number with the sample on the screen, if the number is not
 * null, the user confirms changing it and the sample on the screen is not
 * an existing one. Otherwise, just sets the number in the manager.
 *///from   ww  w.j a  va 2 s .  c  om
private void setAccessionNumber(Integer accession) {
    if (accession == null) {
        manager.getSample().setAccessionNumber(accession);
        return;
    }

    if (getAccessionNumber() != null) {
        if (!Window.confirm(Messages.get().sample_accessionNumberEditConfirm())) {
            accessionNumber.setValue(getAccessionNumber());
            accessionNumber.setFocus(true);
            return;
        }
    }

    /*
     * remove any exceptions added because of the previous value
     */
    accessionNumber.clearExceptions();

    manager.getSample().setAccessionNumber(accession);
    setBusy(Messages.get().gen_fetching());
    if (isState(ADD)) {
        isBusy = true;
        /*
         * this is an async call to make sure that the focus gets set to the
         * field next in the tabbing order to accession number, regardless
         * of the browser and OS, which may not happen with a sync call
         */
        SampleService1.get().mergeQuickEntry(manager, mergeQuickEntryCall);
    } else if (isState(UPDATE)) {
        isBusy = true;
        /*
         * this is an async call to make sure that the focus gets set to the
         * field next in the tabbing order to accession number, regardless
         * of the browser and OS, which may not happen with a sync call
         */
        SampleService1.get().validateAccessionNumber(manager, validateAccessionNumberCall);
    }
}

From source file:org.openelis.modules.attachment.client.AttachmentScreenUI.java

License:Open Source License

/**
 * Puts the screen in delete state and deletes the nodes for all selected
 * attachments/*  w  w w .ja va  2s. c  om*/
 */
@UiHandler("deleteButton")
protected void delete(ClickEvent event) {
    Integer id, selNodes[];
    String desc, name;
    AttachmentManager am;
    SystemUserPermission perm;
    Node node;
    ArrayList<Node> removeNodes;

    /*
     * manager will be null if the user selected the node for loading the
     * next page or if no node is selected
     */
    if (manager == null) {
        Window.alert(Messages.get().attachment_selectAnAttachment());
        return;
    }

    setState(DELETE);
    deleteManagers = new ArrayList<AttachmentManager>();
    removeNodes = new ArrayList<Node>();
    perm = UserCache.getPermission();

    setBusy(Messages.get().gen_lockForDelete());
    /*
     * go through the selected nodes and make a list of managers and nodes
     * for the attachments that can be deleted; the list of nodes is used to
     * remove the nodes in a separate loop; they're not removed in this loop
     * because that'll mess up the indexes that this loop depends on
     */
    selNodes = tree.getSelectedNodes();
    Arrays.sort(selNodes);
    for (Integer i : selNodes) {
        node = tree.getNodeAt(i);
        if (ATTACHMENT_ITEM_LEAF.equals(node.getType()))
            node = node.getParent();

        id = node.getData();
        /*
         * the id will be null if the user selected the node that says
         * "Click for more records"
         */
        if (id == null)
            continue;

        am = managers.get(id);
        desc = am.getAttachment().getDescription();
        /*
         * try to lock each selected node's attachment and issue and refresh
         * the node with the fetched data
         */
        try {
            am = AttachmentService.get().fetchForUpdate(id);
            AttachmentService.get().fetchIssueForUpdate(id);
            manager = am;
            managers.put(id, am);
            reloadAttachment(node);
            /*
             * the attachment will be deleted if it and its issue could be
             * locked, it isn't attached and the user has permission to
             * delete it; if it has an issue, ask the user to confirm
             * deletion
             */
            desc = am.getAttachment().getDescription();
            if (am.item.count() > 0) {
                Window.alert(Messages.get().attachment_cantDeleteAttachedException(desc));
                unlockAndReloadAttachment(id, node);
                continue;
            }

            name = SectionCache.getById(am.getAttachment().getSectionId()).getName();
            if (!perm.has(name, SectionFlags.CANCEL)) {
                Window.alert(Messages.get().attachment_deletePermException(desc));
                unlockAndReloadAttachment(id, node);
                continue;
            }

            if (am.getIssue() != null) {
                if (!Window
                        .confirm(Messages.get().attachment_attachmentHasIssue(desc, am.getIssue().getText()))) {
                    unlockAndReloadAttachment(id, node);
                    continue;
                }
            }
            /*
             * this attachment can be deleted
             */
            deleteManagers.add(am);
            removeNodes.add(node);
        } catch (EntityLockedException e) {
            /*
             * either the attachment or the issue couldn't be locked; unlock
             * them both
             */
            Window.alert(Messages.get().attachment_attachmentLockException(desc, e.getUserName(),
                    new Date(e.getExpires()).toString()));
            unlockAndReloadAttachment(id, node);
        } catch (Exception e) {
            Window.alert(e.getMessage());
            logger.log(Level.SEVERE, e.getMessage() != null ? e.getMessage() : "null", e);
        }
    }

    /*
     * remove the nodes whose attachments can be deleted
     */
    if (removeNodes.size() > 0)
        for (Node n : removeNodes)
            tree.removeNode(n);

    /*
     * don't leave any nodes selected because the user may think that they
     * will get deleted when "Commit" is clicked, but they won't be; that's
     * because their attachments either can't be deleted possibly because
     * they're attached, or the user chose not to delete them because they
     * have issues
     */
    tree.unselectAll();
    manager = null;
    clearStatus();
}

From source file:org.openelis.modules.auxData.client.AuxDataTabUI.java

License:Open Source License

@UiHandler("removeAuxButton")
protected void removeAux(ClickEvent event) {
    int r;/* w ww  . j  a v  a  2s.co  m*/
    AuxDataViewDO data;
    ArrayList<Integer> ids;

    r = table.getSelectedRow();
    if (r == -1)
        return;
    if (Window.confirm(Messages.get().aux_removeMessage())) {
        data = (AuxDataViewDO) table.getRowAt(r).getData();
        ids = new ArrayList<Integer>(1);
        ids.add(data.getAuxFieldGroupId());
        parentBus.fireEventFromSource(new RemoveAuxGroupEvent(ids), this);
    }
    removeAuxButton.setEnabled(false);
}

From source file:org.openelis.modules.clinicalSampleLogin1.client.ClinicalSampleLoginScreenUI.java

License:Open Source License

/**
 * Calls the service method to commit the data on the screen, to the
 * database. Shows any errors/warnings encountered during the commit,
 * otherwise loads the screen with the committed data.
 *//*from  w ww .ja v  a 2  s. c o  m*/
protected void commitUpdate(final boolean ignoreWarning) {
    Integer accession;
    String prefix;
    PatientDO data;
    ValidationErrorsList e1;

    if (isState(ADD))
        setBusy(Messages.get().gen_adding());
    else
        setBusy(Messages.get().gen_updating());

    try {
        /*
         * add the patient if it's a new one; update it if it's locked
         */
        data = manager.getSampleClinical().getPatient();
        if (data.getId() == null) {
            PatientService.get().validate(data);
            data = PatientService.get().add(data);
            manager.getSampleClinical().setPatientId(data.getId());
            manager.getSampleClinical().setPatient(data);
        } else if (isPatientLocked) {
            PatientService.get().validate(data);
            data = PatientService.get().update(data);
            manager.getSampleClinical().setPatient(data);
            isPatientLocked = false;
        }
    } catch (ValidationErrorsList e) {
        /*
         * for display
         */
        accession = manager.getSample().getAccessionNumber();
        if (accession == null)
            accession = 0;

        /*
         * new FormErrorExceptions are created to prepend accession number
         * to the messages of FormErrorExceptions returned by patient
         * validation; other exceptions are shown as is
         */
        e1 = new ValidationErrorsList();
        prefix = Messages.get().sample_accessionPrefix(accession);
        for (Exception ex : e.getErrorList()) {
            if (ex instanceof FormErrorException)
                e1.add(new FormErrorException(DataBaseUtil.concatWithSeparator(prefix, " ", ex.getMessage())));
            else
                e1.add(ex);
        }

        showErrors(e1);
        return;
    } catch (Exception e) {
        if (isState(ADD))
            Window.alert("commitAdd(): " + e.getMessage());
        else
            Window.alert("commitUpdate(): " + e.getMessage());
        logger.log(Level.SEVERE, e.getMessage(), e);
        clearStatus();
        return;
    }

    if (commitUpdateCall == null) {
        commitUpdateCall = new AsyncCallbackUI<SampleManager1>() {
            public void success(SampleManager1 result) {
                Integer id;

                manager = result;
                /*
                 * if either a new sample or a quick entered one was fully
                 * logged in, create an event log to record that
                 */
                if (isFullLogin) {
                    try {
                        id = DictionaryCache.getIdBySystemName("log_type_sample_login");
                        EventLogService.get().add(id, Messages.get().sample_login(), Constants.table().SAMPLE,
                                manager.getSample().getId(), Constants.dictionary().LOG_LEVEL_INFO, null);
                        isFullLogin = false;
                    } catch (Exception e) {
                        Window.alert(e.getMessage());
                        logger.log(Level.SEVERE, e.getMessage(), e);
                        clearStatus();
                        return;
                    }
                }
                evaluateEdit();
                setData();
                setState(DISPLAY);
                fireDataChange();
                clearStatus();

                /*
                 * the cache and scriptlets are cleared only if the
                 * add/update succeeds because otherwise, they can't be used
                 * by any tabs if the user wants to change any data
                 */
                cache = null;
                clearScriptlets();
            }

            public void validationErrors(ValidationErrorsList e) {
                showErrors(e);
                if (!e.hasErrors() && (e.hasWarnings() || e.hasCautions()) && !ignoreWarning)
                    if (Window.confirm(getWarnings(e.getErrorList(), true)))
                        commitUpdate(true);
            }

            public void failure(Throwable e) {
                if (isState(ADD))
                    Window.alert("commitAdd(): " + e.getMessage());
                else
                    Window.alert("commitUpdate(): " + e.getMessage());
                logger.log(Level.SEVERE, e.getMessage(), e);
                clearStatus();
            }
        };
    }

    SampleService1.get().update(manager, ignoreWarning, commitUpdateCall);
}

From source file:org.openelis.modules.clinicalSampleLogin1.client.ClinicalSampleLoginScreenUI.java

License:Open Source License

/**
 * Calls the service method to merge a quick-entered sample that has this
 * accession number with the sample on the screen, if the number is not
 * null, the user confirms changing it and the sample on the screen is not
 * an existing one. Otherwise, just sets the number in the manager.
 */// w w w  .j  av  a  2 s . co  m
private void setAccessionNumber(Integer accession) {
    if (accession == null) {
        manager.getSample().setAccessionNumber(accession);
        return;
    }

    if (getAccessionNumber() != null) {
        if (!Window.confirm(Messages.get().sample_accessionNumberEditConfirm())) {
            accessionNumber.setValue(getAccessionNumber());
            accessionNumber.setFocus(true);
            return;
        }
    }

    /*
     * remove any exceptions added because of the previous value
     */
    accessionNumber.clearExceptions();

    manager.getSample().setAccessionNumber(accession);
    setBusy(Messages.get().gen_fetching());
    if (isState(ADD)) {
        if (mergeQuickEntryCall == null) {
            mergeQuickEntryCall = new AsyncCallbackUI<SampleManager1>() {
                @Override
                public void success(SampleManager1 result) {
                    manager = result;
                    try {
                        /*
                         * add scriptlets for any newly added tests and aux
                         * data
                         */
                        addTestScriptlets();
                        addAuxScriptlets();
                        runScriptlets(null, null, Action_Before.NEW_DOMAIN);
                        setData();
                        setState(UPDATE);
                        fireDataChange();
                        clearStatus();
                        checkTRF();
                    } catch (Exception e) {
                        Window.alert(e.getMessage());
                        logger.log(Level.SEVERE, e.getMessage(), e);
                        clearStatus();
                    }
                }

                public void notFound() {
                    clearStatus();
                    checkTRF();
                }

                public void failure(Throwable e) {
                    if (e instanceof InconsistencyException) {
                        accessionNumber.addException((InconsistencyException) e);
                    } else {
                        manager.getSample().setAccessionNumber(null);
                        accessionNumber.setValue(null);
                        Window.alert(e.getMessage());
                        logger.log(Level.SEVERE, e.getMessage(), e);
                    }
                    clearStatus();
                }

                public void finish() {
                    isBusy = false;
                }
            };
        }
        isBusy = true;
        /*
         * this is an async call to make sure that the focus gets set to the
         * field next in the tabbing order to accession number, regardless
         * of the browser and OS, which may not happen with a sync call
         */
        SampleService1.get().mergeQuickEntry(manager, mergeQuickEntryCall);
    } else if (isState(UPDATE)) {
        if (validateAccessionNumberCall == null) {
            validateAccessionNumberCall = new AsyncCallbackUI<Void>() {
                @Override
                public void success(Void result) {
                    clearStatus();
                    if (isFullLogin)
                        checkTRF();
                }

                public void failure(Throwable e) {
                    if (e instanceof InconsistencyException) {
                        accessionNumber.addException((InconsistencyException) e);
                    } else {
                        manager.getSample().setAccessionNumber(null);
                        accessionNumber.setValue(null);
                        Window.alert(e.getMessage());
                        logger.log(Level.SEVERE, e.getMessage(), e);
                    }
                    clearStatus();
                }

                public void finish() {
                    isBusy = false;
                }
            };
        }

        isBusy = true;
        /*
         * this is an async call to make sure that the focus gets set to the
         * field next in the tabbing order to accession number, regardless
         * of the browser and OS, which may not happen with a sync call
         */
        SampleService1.get().validateAccessionNumber(manager, validateAccessionNumberCall);
    }
}

From source file:org.openelis.modules.environmentalSampleLogin1.client.EnvironmentalSampleLoginScreenUI.java

License:Open Source License

/**
 * Calls the service method to commit the data on the screen, to the
 * database. Shows any errors/warnings encountered during the commit,
 * otherwise loads the screen with the committed data.
 *///  ww  w  .  j  av a 2s . c  o  m
protected void commitUpdate(final boolean ignoreWarning) {
    if (isState(ADD))
        setBusy(Messages.get().gen_adding());
    else
        setBusy(Messages.get().gen_updating());

    if (commitUpdateCall == null) {
        commitUpdateCall = new AsyncCallbackUI<SampleManager1>() {
            public void success(SampleManager1 result) {
                Integer id;

                manager = result;
                /*
                 * if either a new sample or a quick entered one was fully
                 * logged in, create an event log to record that
                 */
                if (isFullLogin) {
                    try {
                        id = DictionaryCache.getIdBySystemName("log_type_sample_login");
                        EventLogService.get().add(id, Messages.get().sample_login(), Constants.table().SAMPLE,
                                manager.getSample().getId(), Constants.dictionary().LOG_LEVEL_INFO, null);
                        isFullLogin = false;
                    } catch (Exception e) {
                        Window.alert(e.getMessage());
                        logger.log(Level.SEVERE, e.getMessage(), e);
                        clearStatus();
                        return;
                    }
                }
                evaluateEdit();
                setData();
                setState(DISPLAY);
                fireDataChange();
                clearStatus();

                /*
                 * the cache and scriptlets are cleared only if the
                 * add/update succeeds because otherwise, they can't be used
                 * by any tabs if the user wants to change any data
                 */
                cache = null;
                clearScriptlets();
            }

            public void validationErrors(ValidationErrorsList e) {
                showErrors(e);
                if (!e.hasErrors() && (e.hasWarnings() || e.hasCautions()) && !ignoreWarning)
                    if (Window.confirm(getWarnings(e.getErrorList(), true)))
                        commitUpdate(true);
            }

            public void failure(Throwable e) {
                if (isState(ADD))
                    Window.alert("commitAdd(): " + e.getMessage());
                else
                    Window.alert("commitUpdate(): " + e.getMessage());
                logger.log(Level.SEVERE, e.getMessage(), e);
                clearStatus();
            }
        };
    }

    SampleService1.get().update(manager, ignoreWarning, commitUpdateCall);
}

From source file:org.openelis.modules.exchangeDataSelection.client.ExchangeDataSelectionScreen.java

License:Open Source License

private void initialize() {
    screen = this;

    queryButton = (AppButton) def.getWidget("query");
    addScreenHandler(queryButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            query();/* ww w .j a  v  a  2  s  . c o m*/
        }

        public void onStateChange(StateChangeEvent<State> event) {
            queryButton.enable(EnumSet.of(State.DEFAULT, State.DISPLAY).contains(event.getState())
                    && userPermission.hasSelectPermission());
            if (event.getState() == State.QUERY)
                queryButton.setState(ButtonState.LOCK_PRESSED);
        }
    });

    previousButton = (AppButton) def.getWidget("previous");
    addScreenHandler(previousButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            previous();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            previousButton.enable(EnumSet.of(State.DISPLAY).contains(event.getState()));
        }
    });

    nextButton = (AppButton) def.getWidget("next");
    addScreenHandler(nextButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            next();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            nextButton.enable(EnumSet.of(State.DISPLAY).contains(event.getState()));
        }
    });

    addButton = (AppButton) def.getWidget("add");
    addScreenHandler(addButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            add();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            addButton.enable(EnumSet.of(State.DEFAULT, State.DISPLAY).contains(event.getState())
                    && userPermission.hasAddPermission());
            if (event.getState() == State.ADD)
                addButton.setState(ButtonState.LOCK_PRESSED);
        }
    });

    updateButton = (AppButton) def.getWidget("update");
    addScreenHandler(updateButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            update();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            updateButton.enable(EnumSet.of(State.DISPLAY).contains(event.getState())
                    && userPermission.hasUpdatePermission());
            if (event.getState() == State.UPDATE)
                updateButton.setState(ButtonState.LOCK_PRESSED);
        }
    });

    deleteButton = (AppButton) def.getWidget("delete");
    addScreenHandler(deleteButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            delete();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            deleteButton.enable(EnumSet.of(State.DISPLAY).contains(event.getState())
                    && userPermission.hasDeletePermission());
            if (event.getState() == State.DELETE)
                deleteButton.setState(ButtonState.LOCK_PRESSED);
        }
    });

    commitButton = (AppButton) def.getWidget("commit");
    addScreenHandler(commitButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            commit();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            commitButton.enable(
                    EnumSet.of(State.QUERY, State.ADD, State.UPDATE, State.DELETE).contains(event.getState()));
        }
    });

    abortButton = (AppButton) def.getWidget("abort");
    addScreenHandler(abortButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            abort();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            abortButton.enable(
                    EnumSet.of(State.QUERY, State.ADD, State.UPDATE, State.DELETE).contains(event.getState()));
        }
    });

    duplicate = (MenuItem) def.getWidget("duplicateRecord");
    addScreenHandler(duplicate, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            duplicate();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            duplicate.enable(
                    EnumSet.of(State.DISPLAY).contains(event.getState()) && userPermission.hasAddPermission());
        }
    });

    criteriaHistory = (MenuItem) def.getWidget("exchangeCriteriaHistory");
    addScreenHandler(criteriaHistory, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            criteriaHistory();
        }

        private void criteriaHistory() {
            IdNameVO hist;

            hist = new IdNameVO(manager.getExchangeCriteria().getId(), manager.getExchangeCriteria().getName());
            HistoryScreen.showHistory(Messages.get().exchangeCriteriaHistory(),
                    Constants.table().EXCHANGE_CRITERIA, hist);

        }

        public void onStateChange(StateChangeEvent<State> event) {
            criteriaHistory.enable(EnumSet.of(State.DISPLAY).contains(event.getState()));
        }
    });

    profileHistory = (MenuItem) def.getWidget("exchangeProfileHistory");
    addScreenHandler(profileHistory, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            profileHistory();
        }

        private void profileHistory() {
            int count;
            IdNameVO list[];
            ExchangeProfileManager man;
            ExchangeProfileDO data;
            DictionaryDO dict;

            try {
                man = manager.getProfiles();
                count = man.count();
                list = new IdNameVO[count];
                for (int i = 0; i < count; i++) {
                    data = man.getProfileAt(i);
                    dict = DictionaryCache.getById(data.getProfileId());
                    list[i] = new IdNameVO(data.getId(), dict.getEntry());
                }
            } catch (Exception e) {
                e.printStackTrace();
                Window.alert(e.getMessage());
                return;
            }

            HistoryScreen.showHistory(Messages.get().exchangeProfileHistory(),
                    Constants.table().EXCHANGE_PROFILE, list);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            profileHistory.enable(EnumSet.of(State.DISPLAY).contains(event.getState()));
        }
    });

    name = (TextBox) def.getWidget(ExchangeCriteriaMeta.getName());
    addScreenHandler(name, new ScreenEventHandler<String>() {
        public void onDataChange(DataChangeEvent event) {
            name.setValue(manager.getExchangeCriteria().getName());
        }

        public void onValueChange(ValueChangeEvent<String> event) {
            manager.getExchangeCriteria().setName(event.getValue());
        }

        public void onStateChange(StateChangeEvent<State> event) {
            name.enable(EnumSet.of(State.QUERY, State.ADD, State.UPDATE).contains(event.getState()));
            name.setQueryMode(event.getState() == State.QUERY);
        }
    });

    environment = (Dropdown) def.getWidget(ExchangeCriteriaMeta.getEnvironmentId());
    addScreenHandler(environment, new ScreenEventHandler<Integer>() {
        public void onDataChange(DataChangeEvent event) {
            environment.setSelection(manager.getExchangeCriteria().getEnvironmentId());
        }

        public void onValueChange(ValueChangeEvent<Integer> event) {
            manager.getExchangeCriteria().setEnvironmentId(event.getValue());
        }

        public void onStateChange(StateChangeEvent<State> event) {
            environment.enable(EnumSet.of(State.QUERY, State.ADD, State.UPDATE).contains(event.getState()));
            environment.setQueryMode(event.getState() == State.QUERY);
        }
    });

    destinationUri = (TextBox) def.getWidget(ExchangeCriteriaMeta.getDestinationUri());
    addScreenHandler(destinationUri, new ScreenEventHandler<String>() {
        public void onDataChange(DataChangeEvent event) {
            destinationUri.setValue(manager.getExchangeCriteria().getDestinationUri());
        }

        public void onValueChange(ValueChangeEvent<String> event) {
            manager.getExchangeCriteria().setDestinationUri(event.getValue());
        }

        public void onStateChange(StateChangeEvent<State> event) {
            destinationUri.enable(EnumSet.of(State.QUERY, State.ADD, State.UPDATE).contains(event.getState()));
            destinationUri.setQueryMode(event.getState() == State.QUERY);
        }
    });

    isAllAnalysesIncluded = (CheckBox) def.getWidget(ExchangeCriteriaMeta.getIsAllAnalysesIncluded());
    addScreenHandler(isAllAnalysesIncluded, new ScreenEventHandler<String>() {
        public void onDataChange(DataChangeEvent event) {
            isAllAnalysesIncluded.setValue(manager.getExchangeCriteria().getIsAllAnalysesIncluded());
        }

        public void onValueChange(ValueChangeEvent<String> event) {
            String val;
            ArrayList<Exception> exceptions;

            val = event.getValue();
            manager.getExchangeCriteria().setIsAllAnalysesIncluded(val);

            if ("N".equals(val))
                return;

            exceptions = test.getExceptions();
            if (exceptions == null)
                return;

            /*
             * this is done so that if the error for not having included at
             * least one test in the query was added to the dropdown because 
             * isAllAnalysisIncluded was unchecked, then the error gets removed
             * on checking isAllAnalysisIncluded and commit doesn't fail in 
             * the front-end   
             */
            for (Exception e : exceptions) {
                if (Messages.get().noTestForNotIncludeAllAnalysesException().equals(e.getMessage())) {
                    exceptions.remove(e);
                    break;
                }
            }
            test.clearExceptions();
            for (Exception e : exceptions)
                test.addException(e);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            isAllAnalysesIncluded
                    .enable(EnumSet.of(State.QUERY, State.ADD, State.UPDATE).contains(event.getState()));
            isAllAnalysesIncluded.setQueryMode(event.getState() == State.QUERY);
        }
    });

    profileTable = (TableWidget) def.getWidget("profileTable");
    addScreenHandler(profileTable, new ScreenEventHandler<ArrayList<TableDataRow>>() {
        public void onDataChange(DataChangeEvent event) {
            if (state != State.QUERY)
                profileTable.load(getProfileTableModel());
        }

        public void onStateChange(StateChangeEvent<State> event) {
            boolean enable;

            profileTable.enable(true);
            profileTable.setQueryMode(event.getState() == State.QUERY);

            enable = EnumSet.of(State.ADD, State.UPDATE).contains(event.getState());
            profileTable.enableDrag(enable);
            profileTable.enableDrop(enable);
        }
    });

    profileTable.addBeforeCellEditedHandler(new BeforeCellEditedHandler() {
        public void onBeforeCellEdited(BeforeCellEditedEvent event) {
            if (state != State.ADD && state != State.UPDATE)
                event.cancel();
        }
    });

    profileTable.addCellEditedHandler(new CellEditedHandler() {
        public void onCellUpdated(CellEditedEvent event) {
            int r, c;
            Object val;
            ExchangeProfileDO data;

            r = event.getRow();
            c = event.getCol();
            val = profileTable.getObject(r, c);

            try {
                data = manager.getProfiles().getProfileAt(r);
            } catch (Exception e) {
                Window.alert(e.getMessage());
                return;
            }

            switch (c) {
            case 0:
                data.setProfileId((Integer) val);
                break;
            }
        }
    });

    profileTable.addRowAddedHandler(new RowAddedHandler() {
        public void onRowAdded(RowAddedEvent event) {
            try {
                manager.getProfiles().addProfile(new ExchangeProfileDO());
            } catch (Exception e) {
                Window.alert(e.getMessage());
                return;
            }
        }
    });

    profileTable.addRowDeletedHandler(new RowDeletedHandler() {
        public void onRowDeleted(RowDeletedEvent event) {
            try {
                manager.getProfiles().removeProfileAt(event.getIndex());
            } catch (Exception e) {
                Window.alert(e.getMessage());
                return;
            }
        }
    });

    profileTable.addRowMovedHandler(new RowMovedHandler() {
        public void onRowMoved(RowMovedEvent event) {
            try {
                manager.getProfiles().moveProfile(event.getOldIndex(), event.getNewIndex());
            } catch (Exception e) {
                Window.alert(e.getMessage());
            }
        }
    });

    profileTable.enableDrag(true);
    profileTable.enableDrop(true);
    profileTable.addTarget(profileTable);

    removeProfileButton = (AppButton) def.getWidget("removeProfileButton");
    addScreenHandler(removeProfileButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            int r;

            r = profileTable.getSelectedRow();
            if (r > -1 && profileTable.numRows() > 0)
                profileTable.deleteRow(r);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            removeProfileButton.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
        }
    });

    addProfileButton = (AppButton) def.getWidget("addProfileButton");
    addScreenHandler(addProfileButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            int n;

            profileTable.addRow();
            n = profileTable.numRows() - 1;
            profileTable.selectRow(n);
            profileTable.scrollToSelection();
            profileTable.startEditing(n, 0);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            addProfileButton.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
        }
    });

    releasedDate = (CalendarLookUp) def.getWidget(SampleMeta.getAnalysisReleasedDate());
    addScreenHandler(releasedDate, new ScreenEventHandler<Datetime>() {
        public void onDataChange(DataChangeEvent event) {
            releasedDate.setQuery(getQuery(SampleMeta.getAnalysisReleasedDate()));
        }

        public void onStateChange(StateChangeEvent<State> event) {
            releasedDate.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
            /*
             * query mode is enabled in display mode to make sure that if there
             * is a range of date to be shown, it get shown correctly
             */
            releasedDate.setQueryMode(
                    EnumSet.of(State.ADD, State.UPDATE, State.DISPLAY).contains(event.getState()));
        }
    });

    domain = (Dropdown) def.getWidget(SampleMeta.getDomain());
    addScreenHandler(domain, new ScreenEventHandler<String>() {
        public void onDataChange(DataChangeEvent event) {
            QueryData field;

            field = getQuery(SampleMeta.getDomain());
            domain.setSelection(field != null ? field.getQuery() : field);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            /*
             * this dropdown is not set to be in query mode because it needs
             * to only allow single selection 
             */
            domain.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
        }
    });

    test = (Dropdown) def.getWidget(SampleMeta.getAnalysisTestId());
    addScreenHandler(test, new ScreenEventHandler<Integer>() {
        public void onDataChange(DataChangeEvent event) {
            test.setQuery(getQuery(SampleMeta.getAnalysisTestId()));
        }

        public void onStateChange(StateChangeEvent<State> event) {
            test.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
            /*
             * query mode is enabled in display mode to make sure that multiple
             * selections get shown in the textbox
             */
            test.setQueryMode(EnumSet.of(State.ADD, State.UPDATE, State.DISPLAY).contains(event.getState()));
        }
    });

    reportToTable = (TableWidget) def.getWidget("reportToTable");
    addScreenHandler(reportToTable, new ScreenEventHandler<ArrayList<TableDataRow>>() {
        public void onDataChange(DataChangeEvent event) {
            reportToTable.load(getReportToTableModel());
        }

        public void onStateChange(StateChangeEvent<State> event) {
            /*
             * In query state the table is not set in query mode, because it's 
             * not used for querying for exchange criteria. Due to that, since
             * the autocomplete for organizations is required, an error could
             * get added to the table in query state, because of the autocomplete
             * being blank. Thus the autocomplete is made required based on
             * the state. 
             */
            //reportToOrganizationName.getField().required = EnumSet.of(State.ADD, State.UPDATE).contains(event.getState());

            reportToTable.enable(true);
        }
    });

    reportToTable.addBeforeCellEditedHandler(new BeforeCellEditedHandler() {
        public void onBeforeCellEdited(BeforeCellEditedEvent event) {
            if (state != State.ADD && state != State.UPDATE)
                event.cancel();
        }
    });

    reportToTable.addCellEditedHandler(new CellEditedHandler() {
        public void onCellUpdated(CellEditedEvent event) {
            int r, c;
            Object val;
            TableDataRow row;

            r = event.getRow();
            c = event.getCol();
            row = reportToTable.getRow(r);
            val = reportToTable.getObject(r, c);

            switch (c) {
            case 0:
                row.key = (val != null ? ((TableDataRow) val).key : null);
                break;
            }
        }
    });

    removeReportToButton = (AppButton) def.getWidget("removeReportToButton");
    addScreenHandler(removeReportToButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            int r;

            r = reportToTable.getSelectedRow();
            if (r > -1 && reportToTable.numRows() > 0)
                reportToTable.deleteRow(r);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            removeReportToButton.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
        }
    });

    addReportToButton = (AppButton) def.getWidget("addReportToButton");
    addScreenHandler(addReportToButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            int n;

            reportToTable.addRow();
            n = reportToTable.numRows() - 1;
            reportToTable.selectRow(n);
            reportToTable.scrollToSelection();
            reportToTable.startEditing(n, 0);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            addReportToButton.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
        }
    });

    reportToOrganizationName = (AutoComplete) reportToTable.getColumns().get(0).getColumnWidget();
    reportToOrganizationName.addGetMatchesHandler(new GetMatchesHandler() {
        public void onGetMatches(GetMatchesEvent event) {
            TableDataRow row;
            AddressDO addr;
            OrganizationDO data;
            ArrayList<OrganizationDO> list;
            ArrayList<TableDataRow> model;

            window.setBusy();
            try {
                list = OrganizationService1Impl.INSTANCE
                        .fetchByIdOrName(QueryFieldUtil.parseAutocomplete(event.getMatch()));
                model = new ArrayList<TableDataRow>();
                for (int i = 0; i < list.size(); i++) {
                    row = new TableDataRow(4);
                    data = list.get(i);

                    row.key = data.getId();
                    row.cells.get(0).setValue(data.getName());
                    addr = data.getAddress();
                    row.cells.get(1).setValue(addr.getStreetAddress());
                    row.cells.get(2).setValue(addr.getCity());
                    row.cells.get(3).setValue(addr.getState());

                    model.add(row);
                }
                reportToOrganizationName.showAutoMatches(model);
            } catch (Throwable e) {
                e.printStackTrace();
                Window.alert(e.getMessage());
            }
            window.clearStatus();
        }
    });

    profileVersion = (Dropdown) def.getWidget(SampleMeta.getOrgParamValue());
    addScreenHandler(profileVersion, new ScreenEventHandler<Integer>() {
        public void onDataChange(DataChangeEvent event) {
            profileVersion.setQuery(getQuery(SampleMeta.getOrgParamValue()));
        }

        public void onStateChange(StateChangeEvent<State> event) {
            /*
             * this dropdown is not set to be in query mode because it needs
             * to only allow single selection 
             */
            profileVersion.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));
        }
    });

    testResultFlags = (Dropdown) def.getWidget(SampleMeta.getAnalysisResultTestResultFlagsId());
    addScreenHandler(testResultFlags, new ScreenEventHandler<Integer>() {
        public void onDataChange(DataChangeEvent event) {
            testResultFlags.setQuery(getQuery(SampleMeta.getAnalysisResultTestResultFlagsId()));
        }

        public void onStateChange(StateChangeEvent<State> event) {
            testResultFlags.enable(EnumSet.of(State.ADD, State.UPDATE).contains(event.getState()));

            /*
             * query mode is enabled in display mode to make sure that multiple
             * selections get shown in the textbox
             */
            testResultFlags.setQueryMode(
                    EnumSet.of(State.ADD, State.UPDATE, State.DISPLAY).contains(event.getState()));
        }
    });

    searchButton = (AppButton) def.getWidget("searchButton");
    addScreenHandler(searchButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            search();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            searchButton.enable(EnumSet.of(State.ADD, State.UPDATE, State.DISPLAY).contains(event.getState()));
        }
    });

    lastRunTable = (TableWidget) def.getWidget("lastRunTable");
    addScreenHandler(lastRunTable, new ScreenEventHandler<ArrayList<TableDataRow>>() {
        public void onDataChange(DataChangeEvent event) {
            loadLastRunTableModel();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            lastRunTable.enable(true);
        }
    });

    lastRunTable.addSelectionHandler(new SelectionHandler<TableRow>() {
        public void onSelection(SelectionEvent<TableRow> event) {
            EventLogDO data;

            /*
             * if a list of samples is being shown in the text area then ask
             * the user if he/she wants them to be replaced with the list generated
             * on the date associated with this row 
             */
            if (DataBaseUtil.isEmpty(queryResults.getText())
                    || Window.confirm(Messages.get().replaceCurrentSampleList())) {
                data = (EventLogDO) lastRunTable.getSelection().data;
                setQueryResults(data.getText());
            }
        }
    });

    lastRunTable.addBeforeCellEditedHandler(new BeforeCellEditedHandler() {
        public void onBeforeCellEdited(BeforeCellEditedEvent event) {
            event.cancel();
        }
    });

    lastRunPrevButton = (AppButton) def.getWidget("lastRunPrevButton");
    addScreenHandler(lastRunPrevButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            if (pageNum > 0) {
                pageNum--;
                DataChangeEvent.fire(screen, lastRunTable);
            } else {
                window.setError(Messages.get().noMoreRecordInDir());
            }
        }

        public void onStateChange(StateChangeEvent<State> event) {
            lastRunPrevButton.enable(EnumSet.of(State.UPDATE, State.DISPLAY).contains(event.getState()));
        }
    });

    lastRunNextButton = (AppButton) def.getWidget("lastRunNextButton");
    addScreenHandler(lastRunNextButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            pageNum++;
            DataChangeEvent.fire(screen, lastRunTable);
        }

        public void onStateChange(StateChangeEvent<State> event) {
            lastRunNextButton.enable(EnumSet.of(State.UPDATE, State.DISPLAY).contains(event.getState()));
        }
    });

    queryResults = (TextArea) def.getWidget("queryResults");
    addScreenHandler(queryResults, new ScreenEventHandler<String>() {
        public void onDataChange(DataChangeEvent event) {
            setQueryResults(null);
        }

        public void onValueChange(ValueChangeEvent<String> event) {
            exportToLocationButton.enable(!DataBaseUtil.isEmpty(event.getValue()));
        }

        public void onStateChange(StateChangeEvent<State> event) {
            queryResults.enable(EnumSet.of(State.ADD, State.UPDATE, State.DISPLAY).contains(event.getState()));
        }
    });

    exportToLocationButton = (AppButton) def.getWidget("exportToLocationButton");
    addScreenHandler(exportToLocationButton, new ScreenEventHandler<Object>() {
        public void onClick(ClickEvent event) {
            exportToLocation();
        }

        public void onStateChange(StateChangeEvent<State> event) {
            exportToLocationButton.enable(false);
        }
    });

    //
    // left hand navigation panel
    //
    nav = new ScreenNavigator<IdNameVO>(def) {
        public void executeQuery(final Query query) {
            window.setBusy(Messages.get().querying());

            query.setRowsPerPage(20);
            ExchangeDataSelectionService.get().query(query, new AsyncCallback<ArrayList<IdNameVO>>() {
                public void onSuccess(ArrayList<IdNameVO> result) {
                    setQueryResult(result);
                }

                public void onFailure(Throwable error) {
                    setQueryResult(null);
                    if (error instanceof NotFoundException) {
                        window.setDone(Messages.get().noRecordsFound());
                        setState(State.DEFAULT);
                    } else if (error instanceof LastPageException) {
                        window.setError("No more records in this direction");
                    } else {
                        Window.alert("Error: Exchange Data Selection call query failed; " + error.getMessage());
                        window.setError(Messages.get().queryFailed());
                    }
                }
            });
        }

        public boolean fetch(IdNameVO entry) {
            return fetchById((entry == null) ? null : entry.getId());
        }

        public ArrayList<TableDataRow> getModel() {
            ArrayList<IdNameVO> result;
            ArrayList<TableDataRow> model;

            model = null;
            result = nav.getQueryResult();
            if (result != null) {
                model = new ArrayList<TableDataRow>();
                for (IdNameVO entry : result)
                    model.add(new TableDataRow(entry.getId(), entry.getName()));
            }
            return model;
        }
    };

    atoz = (ButtonGroup) def.getWidget("atozButtons");
    addScreenHandler(atoz, new ScreenEventHandler<Object>() {
        public void onStateChange(StateChangeEvent<State> event) {
            boolean enable;

            enable = EnumSet.of(State.DEFAULT, State.DISPLAY).contains(event.getState())
                    && userPermission.hasSelectPermission();
            atoz.enable(enable);
            nav.enable(enable);
        }

        public void onClick(ClickEvent event) {
            Query query;
            QueryData field;

            field = new QueryData();
            field.setKey(ExchangeCriteriaMeta.getName());
            field.setQuery(((AppButton) event.getSource()).getAction());
            field.setType(QueryData.Type.STRING);

            query = new Query();
            query.setFields(field);
            nav.setQuery(query);
        }
    });

    window.addBeforeClosedHandler(new BeforeCloseHandler<WindowInt>() {
        public void onBeforeClosed(BeforeCloseEvent<WindowInt> event) {
            if (EnumSet.of(State.ADD, State.UPDATE, State.DELETE).contains(state)) {
                event.cancel();
                window.setError(Messages.get().mustCommitOrAbort());
            }
        }
    });
}

From source file:org.openelis.modules.neonatalScreeningSampleLogin.client.NeonatalScreeningSampleLoginScreenUI.java

License:Open Source License

/**
 * Validates the data on the screen and based on the current state, executes
 * various service operations to commit the data.
 *//*from   www  .java 2 s .c o m*/
@UiHandler("commit")
protected void commit(ClickEvent event) {
    AddressDO paddr, naddr;
    Validation validation;

    finishEditing();

    if (isState(ADD, UPDATE)) {
        /*
         * if the patient's address has not been set, then set it from next
         * of kin's address
         */
        paddr = manager.getSampleNeonatal().getPatient().getAddress();
        naddr = manager.getSampleNeonatal().getNextOfKin().getAddress();

        if (isEmpty(paddr) && !isEmpty(naddr)) {
            paddr.setMultipleUnit(naddr.getMultipleUnit());
            paddr.setStreetAddress(naddr.getStreetAddress());
            paddr.setCity(naddr.getCity());
            paddr.setState(naddr.getState());
            paddr.setZipCode(naddr.getZipCode());
            fireDataChange();
        }
    }

    validation = validate();

    switch (validation.getStatus()) {
    case WARNINGS:
        /*
         * show the warnings and ask the user if the data should still
         * be committed; commit only if the user says yes
         */
        if (!Window.confirm(getWarnings(validation.getExceptions(), true)))
            return;
        break;
    case FLAGGED:
        /*
         * some part of the screen has some operation that needs to be
         * completed before committing the data
         */
        return;
    case ERRORS:
        setError(Messages.get().gen_correctErrors());
        return;
    }

    switch (state) {
    case QUERY:
        commitQuery();
        break;
    case ADD:
        commitUpdate(false);
        break;
    case UPDATE:
        commitUpdate(false);
        break;
    }
}