Example usage for org.springframework.validation BindingResult reject

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

Introduction

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

Prototype

void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage);

Source Link

Document

Register a global error for the entire target object, using the given error description.

Usage

From source file:cherry.foundation.logicalerror.LogicalErrorUtil.java

public static void reject(BindingResult binding, ILogicalError logicalError, Object... args) {
    binding.reject(logicalError.code(), args, logicalError.code());
}

From source file:cherry.sqlapp.controller.sqltool.LogicErrorUtil.java

public void rejectOnOptimisticLockingFailure(BindingResult binding) {
    binding.reject(LogicError.OptimisticLockingFailure.name(), new Object[] {},
            LogicError.OptimisticLockingFailure.name());
}

From source file:cherry.sqlapp.controller.sqltool.LogicErrorUtil.java

public void rejectOnBadSqlGrammer(BindingResult binding, BadSqlGrammarException ex) {
    Throwable rootCause = getRootCause(ex);
    binding.reject(LogicError.BadSqlGrammer.name(), new Object[] { rootCause.getMessage() },
            LogicError.BadSqlGrammer.name());
}

From source file:main.java.net.bornil.controller.event.EventMgmtController.java

/**
 * Searches an existing event// w  w w.ja v a2s.c  om
 * 
 * @param event
 *            Event model with event id to search
 * @param result
 *            Used for displaying model validation result to the client
 * @param model
 *            Model object to hold fetched values
 * 
 * @return Final view to be rendered.
 */
@RequestMapping(value = "/eventSearch", method = RequestMethod.POST)
public String searchEvent(@ModelAttribute(MODEL_EVENT) Event event, BindingResult result, Model model) {

    // TODO :: Ques: What is the better way to handle validation?
    if (event.getEvtId() == null || event.getEvtId() == 0) {
        result.rejectValue("evtId", "err.required", new String[] { "evtId" }, "");
        return "event/eventMgmt";
    }

    Event evt = eventService.getEvent(event.getEvtId());
    if (evt.isNew()) {
        result.reject("err.notFound", new String[] { "Event" }, "Default");
    } else {
        List<Event> list = new ArrayList<Event>();
        list.add(evt);
        model.addAttribute(MODEL_EVENT_LIST, list);
    }
    return "event/eventMgmt";
}

From source file:cn.loveapple.service.controller.contents.action.SiteController.java

/**
 * ?//from   w w w . j  ava2  s  .  c  om
 * 
 * @param session
 * @param model
 * @return
 */
@RequestMapping(value = "core/registConfirm", method = RequestMethod.POST)
public String registConfirm(@Valid SiteForm form, BindingResult result, HttpSession session, Model model,
        Locale locale) {
    model.addAttribute(form);
    SiteValidator validator = new SiteValidator(messageSource, locale);
    if (result.hasErrors()) {
        if (log.isDebugEnabled()) {
            log.debug(ToStringBuilder.reflectionToString(result.getAllErrors()));
        }
        return "core/regist";
    }

    SiteModel siteModel = siteContentsService.findSite(form.getUnixName());

    if (siteModel != null) {
        result.reject("loveappleErrors.beRegisted", validator.createArgs("msg.site"), "");
        return "core/regist";
    }

    session.setAttribute(FORM, form);

    return "core/registConfirm";
}

From source file:org.openmrs.web.controller.visit.VisitFormController.java

private void validateEncounter(Encounter e, BindingResult result) {
    Errors encounterErrors = new BindException(e, "encounter");
    ValidationUtils.invokeValidator(new EncounterValidator(), e, encounterErrors);
    if (encounterErrors.hasErrors()) {
        //bind the errors to the model object
        for (ObjectError error : encounterErrors.getAllErrors()) {
            result.reject(error.getCode(), error.getArguments(), error.getDefaultMessage());
        }/*from  www .  j ava2 s  .c om*/
    }
}

From source file:com.denimgroup.threadfix.webapp.controller.SystemSettingsController.java

@JsonView(AllViews.FormInfo.class)
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Object processSubmit(@ModelAttribute DefaultConfiguration defaultConfiguration,
        HttpServletRequest request, BindingResult bindingResult) {

    if (defaultConfiguration.getDeleteUploadedFiles()) {
        try {//from  w w w  . j av a2  s.  c om
            scanService.deleteScanFileLocations();
            defaultConfiguration.setDeleteUploadedFiles(false);
        } catch (RestIOException e) {
            return RestResponse
                    .failure("Unable to delete files in 'File Upload Location' directory." + e.getMessage());
        }
    }

    if (defaultConfiguration.getSessionTimeout() != null && defaultConfiguration.getSessionTimeout() > 30) {
        bindingResult.reject("sessionTimeout", null, "30 is the maximum.");
    }

    if (defaultConfiguration.fileUploadLocationExists()) {
        checkingFolder(defaultConfiguration, bindingResult);
    }

    // This was added because Spring autobinding was not saving the export fields properly
    List<CSVExportField> exportFields = list();
    Map<String, String[]> params = request.getParameterMap();
    int index = 0;

    while (index != -1) {
        String key = "csvExportFields[" + index + "]";
        String[] enumValue = params.get(key);

        if (enumValue != null) {
            exportFields.add(CSVExportField.valueOf(enumValue[0]));
            index++;
        } else {
            index = -1;
        }
    }

    defaultConfiguration.setCsvExportFields(exportFields);

    Map<String, String> errors = addReportErrors(defaultConfiguration);

    if (bindingResult.hasErrors() || errors.size() > 0) {

        // TODO look into this
        if (bindingResult.hasFieldErrors("proxyPort")) {
            bindingResult.reject("proxyPort", new Object[] {}, "Please enter a valid port number.");
        }

        return FormRestResponse.failure("Unable save System Settings. Try again.", bindingResult, errors);
    } else {
        defaultConfigService.saveConfiguration(defaultConfiguration);
        return success(defaultConfiguration);
    }
}

From source file:cn.loveapple.service.controller.member.action.MemberController.java

/**
 * ?//from   w  w  w  . j  a v a  2s  . com
 * 
 * @param session
 * @param model
 * @return
 */
@RequestMapping(value = "registConfirm", method = RequestMethod.POST)
public String registConfirm(@Valid MemberForm form, BindingResult result, HttpSession session, Model model,
        Locale locale) {
    model.addAttribute(form);
    MemberValidator validator = new MemberValidator(messageSource, locale);
    validator.validate(form, result);
    if (result.hasErrors()) {
        if (log.isDebugEnabled()) {
            log.debug(ToStringBuilder.reflectionToString(result.getAllErrors()));
        }
        return "member/regist";
    }

    LoveappleMemberModel member = memberCoreService.findByEmail(form.getMail());
    if (member != null) {
        result.reject("loveappleErrors.beRegisted", validator.createArgs("msg.member"), "");
        return "member/regist";
    }

    member = createModel(form, locale);

    session.setAttribute(FORM, form);
    session.setAttribute(LOVEAPPLE_MEMBER_TMP, member);

    return "member/registConfirm";
}

From source file:org.openmrs.web.controller.patient.ShortPatientFormController.java

/**
 * Handles the form submission by validating the form fields and saving it to the DB
 * //from ww  w.  j  a va2s . c o  m
 * @param request the webRequest object
 * @param relationshipsMap
 * @param patientModel the modelObject containing the patient info collected from the form
 *            fields
 * @param result
 * @return the view to forward to
 * @should pass if all the form data is valid
 * @should create a new patient
 * @should send the user back to the form in case of validation errors
 * @should void a name and replace it with a new one if it is changed to a unique value
 * @should void an address and replace it with a new one if it is changed to a unique value
 * @should add a new name if the person had no names
 * @should add a new address if the person had none
 * @should ignore a new address that was added and voided at same time
 * @should set the cause of death as none a coded concept
 * @should set the cause of death as a none coded concept
 * @should void the cause of death obs that is none coded
 * @should add a new person attribute with a non empty value
 * @should not add a new person attribute with an empty value
 * @should void an existing person attribute with an empty value
 * @should should replace an existing attribute with a new one when edited
 * @should not void address if it was not changed
 * @should void address if it was changed
 */
@RequestMapping(method = RequestMethod.POST, value = SHORT_PATIENT_FORM_URL)
public String saveShortPatient(WebRequest request,
        @ModelAttribute("personNameCache") PersonName personNameCache,
        @ModelAttribute("personAddressCache") PersonAddress personAddressCache,
        @ModelAttribute("relationshipsMap") Map<String, Relationship> relationshipsMap,
        @ModelAttribute("patientModel") ShortPatientModel patientModel, BindingResult result) {

    if (Context.isAuthenticated()) {
        // First do form validation so that we can easily bind errors to
        // fields
        new ShortPatientFormValidator().validate(patientModel, result);
        if (result.hasErrors()) {
            return "module/legacyui/admin/patients/shortPatientForm";
        }

        Patient patient = null;
        patient = getPatientFromFormData(patientModel);

        Errors patientErrors = new BindException(patient, "patient");
        patientValidator.validate(patient, patientErrors);
        if (patientErrors.hasErrors()) {
            // bind the errors to the patientModel object by adding them to
            // result since this is not a patient object
            // so that spring doesn't try to look for getters/setters for
            // Patient in ShortPatientModel
            for (ObjectError error : patientErrors.getAllErrors()) {
                result.reject(error.getCode(), error.getArguments(), "Validation errors found");
            }

            return "module/legacyui/admin/patients/shortPatientForm";
        }

        // check if name/address were edited, void them and replace them
        boolean foundChanges = hasPersonNameOrAddressChanged(patient, personNameCache, personAddressCache);

        try {
            patient = Context.getPatientService().savePatient(patient);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("Patient.saved"), WebRequest.SCOPE_SESSION);

            // TODO do we really still need this, besides ensuring that the
            // cause of death is provided?
            // process and save the death info
            saveDeathInfo(patientModel, request);

            if (!patient.getVoided() && relationshipsMap != null) {
                for (Relationship relationship : relationshipsMap.values()) {
                    // if the user added a person to this relationship, save
                    // it
                    if (relationship.getPersonA() != null && relationship.getPersonB() != null) {
                        Context.getPersonService().saveRelationship(relationship);
                    }
                }
            }
        } catch (APIException e) {
            log.error("Error occurred while attempting to save patient", e);
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    Context.getMessageSourceService().getMessage("Patient.save.error"),
                    WebRequest.SCOPE_SESSION);
            // TODO revert the changes and send them back to the form

            // don't send the user back to the form because the created
            // person name/addresses
            // will be recreated over again if the user attempts to resubmit
            if (!foundChanges) {
                return "module/legacyui/admin/patients/shortPatientForm";
            }
        }

        return "redirect:" + PATIENT_DASHBOARD_URL + "?patientId=" + patient.getPatientId();

    }

    return "module/legacyui/findPatient";
}

From source file:com.healthcit.cacure.web.controller.question.TableElementEditController.java

/**
 * Process data entered by user//  ww w  .j  ava2  s  . c o m
 * @param question
 * @param formId
 * @return
 */
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) TableElement table, BindingResult result,
        @ModelAttribute(LOOKUP_DATA) Map lookupData, SessionStatus status, HttpServletRequest req) {

    validateEditOperation(table);
    boolean isNew = table.isNew();
    Long formId = null;

    try {
        if (table.isNew()) {
            formId = getFormId();
            qaManager.addNewFormElement(table, formId);
        } else {
            qaManager.updateFormElement(table);
            formId = table.getForm().getId();
        }
    } catch (PersistenceException e) {
        Throwable t = e.getCause();
        if (t instanceof GenericJDBCException) {
            String message = ((GenericJDBCException) t).getSQLException().getNextException().getMessage();
            if (isNew) {
                table.resetId();
                table.getDescriptionList().clear();
            }
            if (message.indexOf("A table with the same short name already exists") > -1) {
                int beginIndex = message.indexOf('[');
                int endIndex = message.indexOf(']');
                String shortName = message.substring(beginIndex + 1, endIndex);
                Object[] params = { shortName };
                result.rejectValue("tableShortName", "notunique.shortName", params, "Short name is not unique");
                return new ModelAndView("questionTableEdit");
            }
            if (message.indexOf("A question with the same short name already exists") > -1) {
                int beginIndex = message.indexOf('[');
                int endIndex = message.indexOf(']');
                String shortName = message.substring(beginIndex + 1, endIndex);
                Object[] params = { shortName };
                result.reject("notunique.shortName", params, "Short name is not unique");
                return new ModelAndView("questionTableEdit");
            } else {
                throw e;
            }
        } else {
            throw e;
        }
    }

    table.setCategories(prepareCategories(req, lookupData));
    //      TODO Save 2 times is not good idea. We clear constraints by second update (see implementation)
    //      Changes to attached to session object save automatically. So categories are seved
    //      qaManager.updateFormElement(table);

    // after question is saved - return to question listing
    return new ModelAndView(new RedirectView(Constants.QUESTION_LISTING_URI + "?formId=" + formId, true));
}