Example usage for org.springframework.validation BindException reject

List of usage examples for org.springframework.validation BindException reject

Introduction

In this page you can find the example usage for org.springframework.validation BindException reject.

Prototype

@Override
    public void reject(String errorCode) 

Source Link

Usage

From source file:net.mindengine.oculus.frontend.web.controllers.project.build.BuildEditController.java

@SuppressWarnings("unchecked")
@Override// w w w . j a  v a 2  s  .  c o m
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Build build = (Build) command;
    Project project = projectDAO.getProject(build.getProjectId());

    build.setId(Long.parseLong(request.getParameter("id")));

    if (buildDAO.getBuildByNameAndProject(build.getName(), build.getProjectId()) != null) {
        errors.reject("Build with such name already exists");
        Map model = errors.getModel();
        model.put("project", project);
        return new ModelAndView(getFormView(), model);
    }

    buildDAO.updateBuild(build);

    Long rootId = projectDAO.getProjectRootId(project.getId(), 10);
    CustomizationUtils.updateUnitCustomizationValues(rootId, build.getId(), Customization.UNIT_BUILD,
            customizationDAO, request);

    return new ModelAndView(new RedirectView("../project/build-display?id=" + build.getId()));
}

From source file:net.mindengine.oculus.frontend.web.controllers.trm.customize.UploadProjectController.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from www . jav  a  2 s. c  o  m
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    TrmUploadProject uploadProject = (TrmUploadProject) command;
    if ("Current Version".equals(uploadProject.getVersion())) {
        uploadProject.setVersion("current");
    }

    if (uploadProject.getZippedFile() == null || uploadProject.getZippedFile().length == 0) {
        errors.reject("trm.uploadproject.error.file.empty");
        Map model = errors.getModel();
        model.put("uploadProject", uploadProject);
        return new ModelAndView(getFormView(), model);
    }

    Project project = projectDAO.getProject(Long.parseLong(request.getParameter("projectId")));
    if (project == null)
        throw new UnexistentResource("Project with id " + request.getParameter("projectId") + " doesn't exist");
    ClientServerRemoteInterface server = config.lookupGridServer();

    /*
     * Uploading project to server
     */
    User user = getUser(request);
    String fileName = UUID.randomUUID().toString().replace("-", "");
    File tmpFile = File.createTempFile(fileName, ".tmp");
    FileUtils.writeByteArrayToFile(tmpFile, uploadProject.getZippedFile());
    server.uploadProject(project.getPath(), uploadProject.getVersion(), tmpFile, user.getName());

    return new ModelAndView(getSuccessView());
}

From source file:org.openmrs.web.controller.user.RoleFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//from  w w w.  j  a va  2 s .c  o m
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        Role role = (Role) obj;
        try {
            Context.getUserService().saveRole(role);
            view = getSuccessView();
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Role.saved");
        } catch (APIException e) {
            errors.reject(e.getMessage());
            return showForm(request, response, errors);
        }
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.web.controller.maintenance.ImplementationIdFormController.java

/**
 * Actions taken when the form is submitted
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *///from ww w. j  a v  a 2  s .c  o m
@Override
protected ModelAndView onSubmit(HttpServletRequest req, HttpServletResponse response, Object object,
        BindException exceptions) throws Exception {

    ImplementationId implId = (ImplementationId) object;

    new ImplementationIdValidator().validate(implId, exceptions);

    if (exceptions.hasErrors()) {
        return showForm(req, response, exceptions);
    }

    try {
        Context.getAdministrationService().setImplementationId(implId);
        req.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "ImplementationId.validatedId");
    } catch (APIException e) {
        log.warn("Unable to set implementation id", e);
        exceptions.reject(e.getMessage());
        req.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        return showForm(req, response, exceptions);
    }

    return new ModelAndView(new RedirectView(getSuccessView()));
}

From source file:org.inbio.modeling.web.controller.ShowMapController.java

/** Default behavior on direct access */
@Override/*from ww w .j  a va2s  .c om*/
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response,
        BindException errors) {

    HttpSession session = null;
    ModelAndView model = null;

    // retrieve the session Information.
    CurrentInstanceData currentInstanceData = null;

    // retrieve the session Information.
    session = request.getSession();
    currentInstanceData = SessionUtils.isSessionAlive(session);

    if (currentInstanceData == null) {
        Exception ex = new Exception("errors.noSession");
        Logger.getLogger(ColumnController.class.getName()).log(Level.SEVERE, null, ex);
        errors.reject(ex.getMessage());
    }

    // Send the layer list to the JSP
    model = new ModelAndView();
    model.setViewName("showResultingMap");
    model.addObject(filtersKey, filtersMap.getFilters());
    model.addObject("exportForm", new ExportData());
    model.addObject("fullSessionInfo", currentInstanceData);
    model.addObject("speciesLayers", layerManagerImpl.getSpeciesDistributionLayerList());
    model.addObject("mainLayer", currentInstanceData.getLimitLayerName());

    if (errors != null && errors.hasErrors())
        model.addAllObjects(errors.getModel());

    return model;
}

From source file:org.inbio.modeling.web.controller.UpdateUserInfoController.java

/** default behavior for direct access (url) */
@Override/*from   www .j ava 2s . com*/
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {

    UserForm userForm = (UserForm) command;
    String uri = request.getRequestURI();

    if (uri.matches(".*deleteUser.*")) {
        this.deleteUser(userForm);
    } else if (uri.matches(".*updateUser.*")) {

        if (!userForm.getPassword1().equals(userForm.getPassword2())) {
            Exception ex = new Exception("errors.passwordNotMatch");
            //Logger.getLogger(ColumnController.class.getName()).log(Level.SEVERE, null, ex);
            errors.reject(ex.getMessage());
            return showForm(request, response, errors);
        } else {
            if ((userForm.getPassword1().equals("") || userForm.getPassword2().equals(""))) {
                Exception ex = new Exception("errors.emptyPassword");
                //Logger.getLogger(ColumnController.class.getName()).log(Level.SEVERE, null, ex);
                errors.reject(ex.getMessage());
                return showForm(request, response, errors);
            } else {
                if (userForm.getFullname().equals("")) {
                    Exception ex = new Exception("errors.emptyFullName");
                    //Logger.getLogger(ColumnController.class.getName()).log(Level.SEVERE, null, ex);
                    errors.reject(ex.getMessage());
                    return showForm(request, response, errors);
                } else {
                    if (userForm.getUsername().equals("")) {
                        Exception ex = new Exception("errors.emptyUserName");
                        //Logger.getLogger(ColumnController.class.getName()).log(Level.SEVERE, null, ex);
                        errors.reject(ex.getMessage());
                        return showForm(request, response, errors);
                    } else {
                        if (userForm.getUserId() == null)
                            this.newUser(userForm);
                        else
                            this.updateUser(userForm);
                    }
                }
            }
        }
    }

    ModelAndView model = null;

    // Send the layer list to the JSP
    model = new ModelAndView();
    model.setViewName("redirect:listUsers.html");

    return model;
}

From source file:org.openmrs.web.controller.person.PersonFormController.java

/**
 * @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *//*from  www  .  ja va 2s.  co m*/
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object obj, BindException errors) throws Exception {
    if (!Context.isAuthenticated()) {
        errors.reject("auth.invalid");
    }

    if (errors.hasErrors()) {
        return showForm(request, response, errors);
    }

    Person person = (Person) obj;

    MessageSourceAccessor msa = getMessageSourceAccessor();
    String action = request.getParameter("action");

    if (action.equals(msa.getMessage("Person.save"))) {
        updatePersonAddresses(request, person, errors);

        updatePersonNames(request, person);

        updatePersonAttributes(request, errors, person);
    }

    if (errors.hasErrors()) {
        return showForm(request, response, errors);
    }

    return super.processFormSubmission(request, response, person, errors);
}

From source file:org.openmrs.module.personalhr.web.controller.PatientRelationshipsFormController.java

@Override
protected void onBindAndValidate(final HttpServletRequest request, final Object commandObject,
        final BindException errors) throws Exception {
    final String command = request.getParameter("command");
    this.log.debug("Entering PatientRelationshipsFormController:onBindAndValidate, command=" + command);
    final PhrPatient phrPatient = (PhrPatient) commandObject;
    final List<PhrSharingToken> tokens = phrPatient.getSharingTokens();
    final PhrSharingToken newToken = phrPatient.getNewSharingToken();

    try {//from w w w .  j av a  2  s  . c om
        if ("Save Changes".equals(command)) {
            for (final PhrSharingToken token : tokens) {
                //validate email address
                if (PersonalhrUtil.isNullOrEmpty(token.getRelatedPersonEmail())) {
                    errors.reject("Email can not be empty!");
                } else if (!PersonalhrUtil.isValidEmail(token.getRelatedPersonEmail())) {
                    errors.reject("Invalid email address: " + token.getRelatedPersonEmail());
                } else {
                    this.log.debug("token.getRelatedPersonEmail()=" + token.getRelatedPersonEmail());
                }
                //validate sharing type
                if ("Select One".equalsIgnoreCase(token.getShareType())) {
                    errors.reject(
                            "Please select the type of information you want to share with the specified person: "
                                    + token.getRelatedPersonName());
                } else {
                    this.log.debug("token.getShareType()=" + token.getShareType());
                }

            }
        } else if ("Add".equals(command)) {
            final PhrSharingToken token = newToken;

            //validate person name
            if (PersonalhrUtil.isNullOrEmpty(token.getRelatedPersonName())) {
                errors.reject("Person name can not be empty!");
            } else {
                this.log.debug("token.getRelatedPersonName()=" + token.getRelatedPersonName());
            }

            //validate email address
            if (PersonalhrUtil.isNullOrEmpty(token.getRelatedPersonEmail())) {
                errors.reject("Email can not be empty for added relationship!");
            } else if (!PersonalhrUtil.isValidEmail(token.getRelatedPersonEmail())) {
                errors.reject("Invalid email address: " + token.getRelatedPersonEmail());
            } else {
                this.log.debug("token.getRelatedPersonEmail()=" + token.getRelatedPersonEmail());
            }
            //validate sharing type
            if ("Select One".equalsIgnoreCase(token.getShareType())) {
                errors.reject(
                        "Please select the type of information you want to share with the specified person: "
                                + token.getRelatedPersonName());
            } else {
                this.log.debug("token.getShareType()=" + token.getShareType());
            }
        }
    } catch (final Exception ex) {
        this.log.error("Exception during form validation", ex);
        errors.reject("Exception during form validation, see log for more details: " + ex);
    }
}

From source file:org.inbio.modeling.web.controller.IntervalsController.java

/** default behavior for direct access */
@Override//from   www.java 2s . co m
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response,
        BindException errors) {

    CurrentInstanceData currentInstanceData = null;
    EditIntervalForm iForm = null;
    HttpSession session = null;
    ModelAndView model = null;

    // retrieve the session Information.
    session = request.getSession();
    currentInstanceData = SessionUtils.isSessionAlive(session);

    if (currentInstanceData != null) {
        iForm = new EditIntervalForm();
        iForm.setLayers(currentInstanceData.getLayerList());
    } else {
        Exception ex = new Exception("errors.noSession");
        Logger.getLogger(ColumnController.class.getName()).log(Level.SEVERE, null, ex);
        errors.reject(ex.getMessage());
    }

    model = new ModelAndView();
    model.setViewName("intervals");
    model.addObject("intervalsForm", iForm);

    if (errors != null && errors.hasErrors())
        model.addAllObjects(errors.getModel());

    return model;
}

From source file:org.openmrs.web.controller.person.PersonFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    if (!Context.isAuthenticated()) {
        errors.reject("auth.invalid");
    }//from   ww  w.  j  a  va 2s .c om

    if (errors.hasErrors()) {
        return showForm(request, response, errors);
    }

    HttpSession httpSession = request.getSession();

    Person person = (Person) command;

    MessageSourceAccessor msa = getMessageSourceAccessor();
    String action = request.getParameter("action");
    PersonService ps = Context.getPersonService();

    StringBuilder linkedProviders = new StringBuilder();
    if (action.equals(msa.getMessage("Person.delete")) || action.equals(msa.getMessage("Person.void"))) {
        Collection<Provider> providerCollection = Context.getProviderService().getProvidersByPerson(person);
        if (providerCollection != null && !providerCollection.isEmpty()) {
            for (Provider provider : providerCollection) {
                linkedProviders.append(provider.getName() + ", ");
            }
            linkedProviders = new StringBuilder(linkedProviders.substring(0, linkedProviders.length() - 2));
        }
    }
    String linkedProvidersString = linkedProviders.toString();
    if (action.equals(msa.getMessage("Person.delete"))) {
        try {
            if (!linkedProvidersString.isEmpty()) {
                errors.reject(
                        Context.getMessageSourceService().getMessage("Person.cannot.delete.linkedTo.providers")
                                + " " + linkedProviders);
            }

            Collection<User> userCollection = Context.getUserService().getUsersByPerson(person, true);
            String linkedUsers = "";
            if (userCollection != null && !userCollection.isEmpty()) {
                for (User user : userCollection) {
                    linkedUsers = linkedUsers + user.getSystemId() + ", ";
                }
                linkedUsers = linkedUsers.substring(0, linkedUsers.length() - 2);
            }
            if (!linkedUsers.isEmpty()) {
                errors.reject(
                        Context.getMessageSourceService().getMessage("Person.cannot.delete.linkedTo.users")
                                + " " + linkedUsers);
            }

            if (errors.hasErrors()) {
                return showForm(request, response, errors);
            } else {
                ps.purgePerson(person);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.deleted");

                return new ModelAndView(new RedirectView("index.htm"));
            }
        } catch (DataIntegrityViolationException e) {
            log.error("Unable to delete person because of database FK errors: " + person, e);
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Person.cannot.delete");

            return new ModelAndView(
                    new RedirectView(getSuccessView() + "?personId=" + person.getPersonId().toString()));
        }
    } else if (action.equals(msa.getMessage("Person.void"))) {
        String voidReason = request.getParameter("voidReason");
        if (StringUtils.isBlank(voidReason)) {
            voidReason = msa.getMessage("PersonForm.default.voidReason", null, "Voided from person form",
                    Context.getLocale());
        }
        if (linkedProvidersString.isEmpty()) {
            ps.voidPerson(person, voidReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.voided");
        } else {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Person.cannot.void.linkedTo.providers") + " "
                            + linkedProviders);
        }
        return new ModelAndView(new RedirectView(getSuccessView() + "?personId=" + person.getPersonId()));
    } else if (action.equals(msa.getMessage("Person.unvoid"))) {
        ps.unvoidPerson(person);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.unvoided");

        return new ModelAndView(new RedirectView(getSuccessView() + "?personId=" + person.getPersonId()));
    } else {
        ps.savePerson(person);

        // If person is dead
        if (person.getDead()) {
            log.debug("Person is dead, so let's make sure there's an Obs for it");
            // need to make sure there is an Obs that represents the patient's cause of death, if applicable

            String causeOfDeathConceptId = Context.getAdministrationService()
                    .getGlobalProperty("concept.causeOfDeath");
            Concept causeOfDeath = Context.getConceptService().getConcept(causeOfDeathConceptId);

            if (causeOfDeath != null) {
                List<Obs> obssDeath = Context.getObsService().getObservationsByPersonAndConcept(person,
                        causeOfDeath);
                if (obssDeath != null) {
                    if (obssDeath.size() > 1) {
                        log.error("Multiple causes of death (" + obssDeath.size() + ")?  Shouldn't be...");
                    } else {
                        Obs obsDeath = null;
                        if (obssDeath.size() == 1) {
                            // already has a cause of death - let's edit it.
                            log.debug("Already has a cause of death, so changing it");

                            obsDeath = obssDeath.iterator().next();

                        } else {
                            // no cause of death obs yet, so let's make one
                            log.debug("No cause of death yet, let's create one.");

                            obsDeath = new Obs();
                            obsDeath.setPerson(person);
                            obsDeath.setConcept(causeOfDeath);
                            Location location = Context.getLocationService().getDefaultLocation();
                            // TODO person healthcenter //if ( loc == null ) loc = patient.getHealthCenter();
                            if (location != null) {
                                obsDeath.setLocation(location);
                            } else {
                                log.error(
                                        "Could not find a suitable location for which to create this new Obs");
                            }
                        }

                        // put the right concept and (maybe) text in this obs
                        Concept currCause = person.getCauseOfDeath();
                        if (currCause == null) {
                            // set to NONE
                            log.debug("Current cause is null, attempting to set to NONE");
                            String noneConcept = Context.getAdministrationService()
                                    .getGlobalProperty("concept.none");
                            currCause = Context.getConceptService().getConcept(noneConcept);
                        }

                        if (currCause != null) {
                            log.debug("Current cause is not null, setting to value_coded");
                            obsDeath.setValueCoded(currCause);
                            obsDeath.setValueCodedName(currCause.getName()); // ABKTODO: presume current locale?

                            Date dateDeath = person.getDeathDate();
                            if (dateDeath == null) {
                                dateDeath = new Date();
                            }

                            obsDeath.setObsDatetime(dateDeath);

                            // check if this is an "other" concept - if so, then we need to add value_text
                            String otherConcept = Context.getAdministrationService()
                                    .getGlobalProperty("concept.otherNonCoded");
                            Concept conceptOther = Context.getConceptService().getConcept(otherConcept);
                            boolean deathReasonChanged = false;
                            if (conceptOther != null) {
                                String otherInfo = ServletRequestUtils.getStringParameter(request,
                                        "causeOfDeath_other", "");
                                if (conceptOther.equals(currCause)) {
                                    // seems like this is an other concept - let's try to get the "other" field info
                                    deathReasonChanged = !otherInfo.equals(obsDeath.getValueText());
                                    log.debug("Setting value_text as " + otherInfo);
                                    obsDeath.setValueText(otherInfo);
                                } else {
                                    // non empty text value implies concept changed from OTHER NON CODED to NONE
                                    deathReasonChanged = !otherInfo.equals("");
                                    log.debug("New concept is NOT the OTHER concept, so setting to blank");
                                    obsDeath.setValueText("");
                                }
                            } else {
                                log.debug("Don't seem to know about an OTHER concept, so deleting value_text");
                                obsDeath.setValueText("");
                            }
                            boolean shouldSaveObs = (null == obsDeath.getId()) || deathReasonChanged;
                            if (shouldSaveObs) {
                                if (null == obsDeath.getVoidReason()) {
                                    obsDeath.setVoidReason("Changed in patient demographics editor");
                                }
                                Context.getObsService().saveObs(obsDeath, obsDeath.getVoidReason());
                            }
                        } else {
                            log.debug("Current cause is still null - aborting mission");
                        }
                    }
                }
            } else {
                log.debug(
                        "Cause of death is null - should not have gotten here without throwing an error on the form.");
            }

        }

        String view = getSuccessView();
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Person.saved");
        view = view + "?personId=" + person.getPersonId();

        return new ModelAndView(new RedirectView(view));
    }
}