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, String defaultMessage);

Source Link

Document

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

Usage

From source file:org.davidmendoza.esu.web.admin.ArticuloController.java

@RequestMapping(value = "/nuevo", method = RequestMethod.POST)
public String nuevo(@ModelAttribute("articulo") Articulo articulo, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    articuloValidator.validate(articulo, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo crear el articulo. {}", bindingResult.getAllErrors());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);//w  ww . j a va2  s. c  o m
        return "admin/articulo/nuevo";
    }

    try {
        articuloService.crea(articulo);
    } catch (Exception e) {
        log.error("No se pudo crear el articulo", e);
        bindingResult.reject("No se pudo crear el articulo. {}", e.getMessage());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);
        return "admin/articulo/nuevo";
    }
    return "redirect:/admin/articulo/ver/" + articulo.getId();
}

From source file:org.davidmendoza.esu.web.admin.ArticuloController.java

@RequestMapping(value = "/editar", method = RequestMethod.POST)
public String editar(@ModelAttribute("articulo") Articulo articulo, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    articuloValidator.validate(articulo, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo editar el articulo. {}", bindingResult.getAllErrors());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);/*from  w ww.j  a va 2s .c  o m*/
        return "admin/articulo/editar";
    }

    try {
        articuloService.actualiza(articulo);
    } catch (Exception e) {
        log.error("No se pudo editar el articulo", e);
        bindingResult.reject("No se pudo editar el articulo. {}", e.getMessage());
        Usuario autor = usuarioService.obtiene(articulo.getAutor().getId());
        articulo.setAutor(autor);
        return "admin/articulo/editar";
    }
    return "redirect:/admin/articulo/ver/" + articulo.getId();
}

From source file:com.iana.dver.controller.DverUserController.java

@RequestMapping(value = "/getIepInfo/{iepdot}", method = RequestMethod.GET)
public String setupIepInfoPage(final Model model, @ModelAttribute("configVO") DverConfigVO configVO,
        BindingResult result, @PathVariable("iepdot") String iepdot, HttpServletRequest request) {
    try {/* www . j  ava 2 s .co m*/
        logger.info("on Iep Info Page.....");
        configVO = this.dverUserService.getDverConfigByDOT(iepdot);
        if (configVO != null) {
            model.addAttribute("configVO", configVO);
        } else {
            result.reject("no.iep.found",
                    "The Contact information for DOT: " + iepdot + " is currently not available.");
        }
        return "iep-info";
    } catch (Exception ex) {

        DVERUtil.sendExceptionEmails("setupIepInfoPage method of DverUserController \n " + ex);
        logger.error("Error in setupIepInfoPage()....." + ex);
        return "error";

    }

}

From source file:org.davidmendoza.esu.web.admin.ArticuloController.java

@RequestMapping(value = "/publicacion", method = RequestMethod.POST)
public String nuevaPublicacion(@ModelAttribute("publicacion") Publicacion publicacion,
        BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model, Principal principal) {
    publicacionValidator.validate(publicacion, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("No se pudo crear la publicacion. {}", bindingResult.getAllErrors());
        inicializaPublicacion(model, publicacion);
        return "admin/articulo/publicacion";
    }/*  w  w w. j a va  2  s.c  o  m*/

    try {
        Usuario usuario = usuarioService.obtiene(principal.getName());
        publicacion.setEditor(usuario);
        publicacionService.nueva(publicacion);
    } catch (Exception e) {
        log.error("No se pudo crear la publicacion", e);
        inicializaPublicacion(model, publicacion);
        bindingResult.reject("No se pudo crear la publicacion. {}", e.getMessage());
        return "admin/articulo/publicacion";
    }

    return "redirect:/admin/articulo/ver/" + publicacion.getArticulo().getId();
}

From source file:com.iana.dver.controller.DverAdminController.java

@RequestMapping(value = "/getDverConfig/{userId}", method = RequestMethod.GET)
public String getDverContactDetails(final Model model, @ModelAttribute("configVO") DverConfigVO configVO,
        BindingResult result, @PathVariable("userId") Integer userId, HttpServletRequest request) {
    try {/*from www  . jav  a  2  s  . com*/
        logger.info("on DVER Contact details.....");
        configVO = this.dverUserService.getDverConfigById(userId);
        if (configVO != null) {
            model.addAttribute("configVO", configVO);
        } else {
            result.reject("no.contact.details.found", "The Contact information for user with user id : "
                    + userId + " is currently not available.");
        }
        return "iep-info";
    } catch (Exception ex) {
        DVERUtil.sendExceptionEmails("getDverContactDetails method of DverAdminController \n " + ex);
        logger.error("Error in getDverContactDetails()....." + ex);
        return "error";
    }
}

From source file:org.openmrs.module.appointmentscheduling.web.controller.AppointmentTypeFormController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(HttpServletRequest request, AppointmentType appointmentType, BindingResult result)
        throws Exception {

    HttpSession httpSession = request.getSession();

    if (Context.isAuthenticated()) {
        AppointmentService appointmentService = Context.getService(AppointmentService.class);

        if (request.getParameter("save") != null) {
            new AppointmentTypeValidator().validate(appointmentType, result);
            if (result.hasErrors()) {
                return null;
            } else {
                appointmentService.saveAppointmentType(appointmentType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.AppointmentType.saved");
            }/*  ww  w. j  av  a 2 s.c o m*/
        }

        // if the user is retiring out the AppointmentType
        else if (request.getParameter("retire") != null) {
            String retireReason = request.getParameter("retireReason");
            if (appointmentType.getAppointmentTypeId() != null && !(StringUtils.hasText(retireReason))) {
                result.reject("retireReason", "general.retiredReason.empty");
                return null;
            }

            appointmentService.retireAppointmentType(appointmentType, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentType.retiredSuccessfully");
        }

        // if the user is unretiring the AppointmentType
        else if (request.getParameter("unretire") != null) {
            appointmentService.unretireAppointmentType(appointmentType);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentType.unretiredSuccessfully");
        }

        // if the user is purging the appointmentType
        else if (request.getParameter("purge") != null) {

            try {
                appointmentService.purgeAppointmentType(appointmentType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.AppointmentType.purgedSuccessfully");
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                //view = "appointmentType.form?appointmentTypeId=" + appointmentType.getAppointmentTypeId();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                //view = "appointmentType.form?appointmentTypeId=" + appointmentType.getAppointmentTypeId();
            }
        }

    }

    return "redirect:appointmentTypeList.list";
}

From source file:org.openmrs.module.hr.web.controller.JobTitleController.java

@RequestMapping(value = "module/hr/admin/jobTitle.form", method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, @ModelAttribute("job") HrJobTitle jobTitle,
        BindingResult errors) {
    HRPostService hrPostService = Context.getService(HRPostService.class);
    List<HrIscoCodes> iscoCodeList = hrPostService.getAllIscoCodes();
    ConceptService cs = Context.getConceptService();
    Concept cadre = cs.getConceptByMapping("Cadre", "HR Module");
    Collection<ConceptAnswer> cadreAnswers;
    if (cadre != null)
        cadreAnswers = cadre.getAnswers();
    else//  w  w  w  . j a v  a  2s. co m
        cadreAnswers = new ArrayList<ConceptAnswer>();
    ModelAndView formView = new ModelAndView(SUCCESS_FORM_VIEW);
    formView.addObject("IscoCodeList", iscoCodeList);
    formView.addObject("CadreAnswers", cadreAnswers);
    List<HrJobTitle> jobList = null;
    if (Context.isAuthenticated()) {
        ModelAndView listView = new ModelAndView(SUCCESS_LIST_VIEW);
        if (request.getParameter("retireJobTitle") != null) {
            String retireReason = request.getParameter("retireReason");
            if (jobTitle.getId() != null && (retireReason == null || retireReason.length() == 0)) {
                errors.reject("retireReason", "Retire reason cannot be empty");
                return formView;
            }
            hrPostService.retireJobTitle(hrPostService.getJobTitleById(jobTitle.getId()), retireReason,
                    Context.getAuthenticatedUser());
            request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Job Title Retired Successfully");
            jobList = hrPostService.getAllJobTitles();
            listView.addObject("JobList", jobList);
            return listView;
        } else if (request.getParameter("unretireJobTitle") != null) {
            hrPostService.unretireJobTitle(hrPostService.getJobTitleById(jobTitle.getId()));
            request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "Job Title Unretired Successfully");
            jobList = hrPostService.getAllJobTitles();
            listView.addObject("JobList", jobList);
            return listView;
        } else {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "error.null");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cadre", "error.null");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "grades", "error.null");
            if (request.getParameter("IscoCode") == null)
                errors.reject("IscoCode", "error.null");
            if (errors.hasErrors()) {
                return formView;
            } else {
                jobTitle.setHrIscoCodes(hrPostService.getIscoCodeById(request.getParameter("IscoCode")));
                hrPostService.saveJobTitle(jobTitle);
                request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "Job Title saved Successfully");
                jobList = hrPostService.getAllJobTitles();
                listView.addObject("JobList", jobList);
                return listView;
            }
        }
    }
    return formView;
}

From source file:org.openmrs.web.controller.location.LocationAttributeTypeFormController.java

/**
 * Handle submission for create or edit//from ww w.  j av a2  s . c  om
 */
@RequestMapping(value = "/admin/locations/locationAttributeType", method = RequestMethod.POST)
public String handleSubmit(WebRequest request,
        @ModelAttribute("attributeType") LocationAttributeType attributeType, BindingResult errors) {

    LocationService service = Context.getLocationService();

    if (request.getParameter("purge") != null) {
        try {
            service.purgeLocationAttributeType(attributeType);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "LocationAttributeType.purgedSuccessfully",
                    WebRequest.SCOPE_SESSION);
        } catch (Exception e) {
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge",
                    WebRequest.SCOPE_SESSION);
        }
        return "redirect:locationAttributeTypes.list";
    }

    new LocationAttributeTypeValidator().validate(attributeType, errors);

    if (errors.hasErrors()) {
        return null; // redisplay the form

    } else {

        if (request.getParameter("save") != null) {
            Context.getLocationService().saveLocationAttributeType(attributeType);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("LocationAttributeType.saved"),
                    WebRequest.SCOPE_SESSION);
        } else if (request.getParameter("retire") != null) {
            String retireReason = request.getParameter("retireReason");
            if (attributeType.getId() != null && !(StringUtils.hasText(retireReason))) {
                errors.reject("retireReason", "general.retiredReason.empty");
                return null;
            }
            Context.getLocationService().retireLocationAttributeType(attributeType, retireReason);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("LocationAttributeType.retired"),
                    WebRequest.SCOPE_SESSION);
        } else if (request.getParameter("unretire") != null) {
            Context.getLocationService().unretireLocationAttributeType(attributeType);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    Context.getMessageSourceService().getMessage("LocationAttributeType.unretired"),
                    WebRequest.SCOPE_SESSION);
        }
        return "redirect:/admin/locations/locationAttributeTypes.list";
    }
}

From source file:org.thymeleaf.engine.springintegration.context.ErrorsSpringIntegrationWebProcessingContextBuilder.java

@Override
protected void initBindingResult(final String bindingVariableName, final Object bindingObject, final ITest test,
        final BindingResult bindingResult, final Locale locale, final Map<String, Object> variables) {

    super.initBindingResult(bindingVariableName, bindingObject, test, bindingResult, locale, variables);

    @SuppressWarnings("unchecked")
    final List<Map<String, Object>> bindingErrorsList = (List<Map<String, Object>>) variables
            .get(BINDING_ERRORS_CONTEXT_VARIABLE_NAME);

    if (bindingErrorsList != null) {

        for (final Map<String, Object> bindingErrors : bindingErrorsList) {

            final Object bindingObj = bindingErrors.get(BINDING_ERRORS_OBJECT_BINDING_NAME);
            if (bindingObj != null) {
                if (bindingObj.toString().equals(bindingVariableName)) {
                    // This error map applies to this binding variable

                    final Object fieldObj = bindingErrors.get(BINDING_ERRORS_OBJECT_BINDING_FIELD_NAME);

                    final Object messageObj = bindingErrors.get(BINDING_ERRORS_OBJECT_BINDING_MESSAGE_NAME);
                    if (messageObj == null) {
                        throw new TestEngineExecutionException(
                                "Error specification does not include property 'message', which is mandatory");
                    }/*from   w  ww  . j  a  va2  s  .c  o m*/

                    if (fieldObj != null) {
                        // Field error
                        bindingResult.rejectValue(fieldObj.toString(), "no_code", messageObj.toString());
                    } else {
                        // Global error
                        bindingResult.reject("no_code", messageObj.toString());
                    }

                }

            }

        }

    }

}