Example usage for org.springframework.validation BindingResult getAllErrors

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

Introduction

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

Prototype

List<ObjectError> getAllErrors();

Source Link

Document

Get all errors, both global and field ones.

Usage

From source file:org.egov.wtms.web.controller.transaction.payment.WaterEstimationChargesPaymentController.java

@GetMapping("/verification")
public String showVerificationForm(@RequestParam(required = false) String applicationNumber,
        @RequestParam(required = false) String consumerNumber, WaterConnectionDetails waterConnectionDetails,
        BindingResult bindingResult, Model model) {

    if (waterEstimationChargesPaymentValidator.validate(applicationNumber, consumerNumber, bindingResult)) {
        model.addAttribute("message", bindingResult.getAllErrors().get(0).getDefaultMessage());
        return "estimationpayment-verificationform";
    }/*from ww  w.j av a 2  s . co  m*/
    WaterConnectionDetails connectionDetails = waterConnectionDetailsService
            .findByApplicationNumberOrConsumerCode(
                    isBlank(applicationNumber) ? consumerNumber : applicationNumber);
    model.addAttribute("waterConnectionDetails", connectionDetails);
    model.addAttribute("estimationAmount",
            estimationChargesPaymentService.getEstimationDueAmount(connectionDetails));
    return "estimationpayment-verificationform";
}

From source file:org.encuestame.mvc.page.ForgetPasswordController.java

/**
 * Process Submit.//from  w  w w  . jav a  2s.  c om
 *
 * @param req
 * @param challenge
 * @param response
 * @param user
 * @param result
 * @param status
 * @return
 * @throws EnMeNoResultsFoundException
 */
@RequestMapping(value = "/user/forgot", method = RequestMethod.POST)
public String forgotSubmitForm(HttpServletRequest req, ModelMap model,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String challenge,
        @RequestParam(value = "recaptcha_response_field", required = false) String response,
        @ModelAttribute ForgotPasswordBean user, BindingResult result, SessionStatus status)
        throws EnMeNoResultsFoundException {
    log.info("recaptcha_challenge_field " + challenge);
    log.info("recaptcha_response_field " + response);
    log.info("result erros  " + result.getAllErrors().size());
    log.info("result erros  " + result.getErrorCount());
    final String email = user.getEmail() == null ? "" : user.getEmail();
    setCss(model, "user");
    if (!email.isEmpty()) {
        log.debug("email " + email);
        final ReCaptchaResponse reCaptchaResponse = getReCaptcha().checkAnswer(req.getRemoteAddr(), challenge,
                response);
        final ValidateOperations validation = new ValidateOperations(getSecurityService());
        boolean _isValidEmailFormat = validation.validateEmail(email);
        log.info("EMAIL FORMAT NOT VALID --> " + _isValidEmailFormat);
        if (_isValidEmailFormat) {
            final UserAccount userValidate = validation.checkifEmailExist(email);
            if (userValidate == null) {
                result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, "");
            }
            log.info("reCaptchaResponse " + reCaptchaResponse.isValid());
            //validate reCaptcha
            validation.validateCaptcha(reCaptchaResponse, result);
            if (reCaptchaResponse.getErrorMessage() != null) {
                RequestSessionMap.getCurrent(req).put("resetError", Boolean.TRUE);
                RequestSessionMap.getCurrent(req).put("resetErrorMessage", reCaptchaResponse.getErrorMessage());
                log.fatal("reCaptcha Fatal Error: " + reCaptchaResponse.getErrorMessage());
            }
            log.info("result.hasErrors() " + result.hasErrors());
            if (result.hasErrors()) {
                return "forgot";
            } else {
                final String password = PasswordGenerator.getPassword(6);
                try {
                    /*
                     * Stuffs to change;
                     * 1. user should be to change own password, not auto generate
                     * 2. instead redirect to sign in page, should be to success page.
                     */
                    getSecurityService().renewPassword(
                            ConvertDomainBean.convertBasicSecondaryUserToUserBean(userValidate), password);
                } catch (EnMeException e) {
                    log.error("Error Renewd password " + e.getMessage());
                    return "forgot";
                }
                status.setComplete();
                log.info("password generated: " + password);
                final ForgotPasswordBean forgot = new ForgotPasswordBean();
                model.addAttribute("forgotPasswordBean", forgot);
                return "/user/checkyouremail";
            }
        } else {
            log.info("EMAIL FORMAT NOT VALID");
            result.rejectValue("email", "secure.email.notvalid", new Object[] { user.getEmail() }, "");
            return "forgot";
        }
    } else {
        result.rejectValue("email", "secure.email.emtpy", null, "");
        return "forgot";
    }
}

From source file:org.esupportail.pay.web.admin.PayEvtController.java

@RequestMapping(value = "/{id}/addLogoFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manage')")
public String addLogoFile(@PathVariable("id") Long id, UploadFile uploadFile, BindingResult bindingResult,
        Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        log.warn(bindingResult.getAllErrors());
        return "redirect:/admin/evts/" + id.toString();
    }/*ww  w  .  j a v a  2s. c om*/
    uiModel.asMap().clear();

    // get PosteCandidature from id                                                                                                                                                                                               
    PayEvt evt = PayEvt.findPayEvt(id);

    MultipartFile file = uploadFile.getLogoFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?                                                                                     
    if (file != null) {
        Long fileSize = file.getSize();
        //String contentType = file.getContentType();
        //String filename = file.getOriginalFilename();

        InputStream inputStream = file.getInputStream();
        //byte[] bytes = IOUtils.toByteArray(inputStream);                                                                                                                                            

        evt.getLogoFile().setBinaryFileStream(inputStream, fileSize);
        evt.getLogoFile().persist();
    }

    return "redirect:/admin/evts/" + id.toString();
}

From source file:org.esupportail.pay.web.admin.PayEvtController.java

@RequestMapping(method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String create(@Valid PayEvt payEvt, BindingResult bindingResult, Model uiModel,
        HttpServletRequest httpServletRequest) {
    if (bindingResult.hasErrors()) {
        log.info(bindingResult.getAllErrors());
        populateEditForm(uiModel, payEvt);
        return "admin/evts/create";
    }// ww  w  .  j  a  v a2s.c  om
    uiModel.asMap().clear();

    List<RespLogin> respLogins = new ArrayList<RespLogin>();
    if (httpServletRequest.getParameterValues("logins") != null) {
        List<String> logins = Arrays.asList(httpServletRequest.getParameterValues("logins"));
        for (String login : logins) {
            RespLogin respLogin = RespLogin.findOrCreateRespLogin(login);
            respLogins.add(respLogin);
        }
    }
    payEvt.setRespLogins(respLogins);

    List<RespLogin> viewerLogins = new ArrayList<RespLogin>();
    if (httpServletRequest.getParameterValues("viewerLogins2Add") != null) {
        List<String> logins = Arrays.asList(httpServletRequest.getParameterValues("viewerLogins2Add"));
        for (String login : logins) {
            RespLogin respLogin = RespLogin.findOrCreateRespLogin(login);
            viewerLogins.add(respLogin);
        }
    }
    payEvt.setViewerLogins(viewerLogins);

    if (payEvt.getUrlId() == null || payEvt.getUrlId().isEmpty()) {
        String urlId = urlIdService.generateUrlId4PayEvt(payEvt.getTitle().getTranslation(Label.LOCALE_IDS.en));
        payEvt.setUrlId(urlId);
    }

    payEvt.persist();
    return "redirect:/admin/evts/" + encodeUrlPathSegment(payEvt.getId().toString(), httpServletRequest);
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * This is the entry point for the AJAX call to update the resource
 *//*from   w  ww.  j av a2  s.  c  o  m*/
@SuppressWarnings("unchecked")
public ModelAndView updateDataResource(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    logger.info("Updating a resource...");
    debugRequestParams(request);
    ResourceDetail resource = new ResourceDetail();
    ServletRequestDataBinder binder = createBinder(request, resource);
    binder.bind(request);
    String businessKey = request.getParameter(REQUEST_BUSINESS_UDDI_KEY);
    BindingResult result = binder.getBindingResult();
    validateDataResource(resource, result);

    if (result.getErrorCount() == 0) {
        // it is always the last one, due to the fact that only one is ever submitted
        // although it's id may be something other than 0
        if (logger.isDebugEnabled()) {
            logger.debug("Resource name: " + resource.getName());
            logger.debug("Resource description: " + resource.getDescription());
        }
        uddiUtils.updateResource(resource, request.getParameter(REQUEST_BUSINESS_UDDI_KEY));
        return new ModelAndView(new RedirectView(
                request.getContextPath() + "/register/showDataResources?businessKey=" + businessKey));
    } else {
        logger.error(result.getAllErrors());
        // put the errors in the request
        Map<String, Object> data = new HashMap<String, Object>();
        data.putAll(referenceDataForResource(request, resource));
        data.put(RegistrationController.REQUEST_RESOURCE, resource);
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_RESOURCE, result);
        List<String> beanProperties = retrieveReadonlyPropertiesForResource(resource);
        data.putAll(referenceDataForResourceList(request));
        data.put("readonlyProperties", beanProperties);
        return new ModelAndView("registrationResourceDetail", data);
    }
}

From source file:org.jtalks.jcommune.plugin.questionsandanswers.controller.QuestionsAndAnswersController.java

/**
 * Adds new comment to post//from   w ww.ja  v  a  2s . c om
 *
 * @param dto dto populated in form
 * @param result validation result
 * @param request http servlet request
 *
 * @return result in JSON format
 */
@RequestMapping(method = RequestMethod.POST, value = "newcomment")
@ResponseBody
JsonResponse addComment(@Valid @RequestBody CommentDto dto, BindingResult result, HttpServletRequest request) {
    if (result.hasErrors()) {
        return new FailValidationJsonResponse(result.getAllErrors());
    }
    PostComment comment;
    try {
        Post targetPost = getPluginPostService().get(dto.getPostId());
        //We can't provide limitation properly without database-level locking
        if (targetPost.getNotRemovedComments().size() >= LIMIT_OF_POSTS_VALUE) {
            return new JsonResponse(JsonResponseStatus.FAIL);
        }
        comment = getPluginPostService().addComment(dto.getPostId(), Collections.EMPTY_MAP, dto.getBody());
    } catch (NotFoundException ex) {
        return new FailJsonResponse(JsonResponseReason.ENTITY_NOT_FOUND);
    }
    JodaDateTimeTool dateTimeTool = new JodaDateTimeTool(request);
    return new JsonResponse(JsonResponseStatus.SUCCESS, new CommentDto(comment, dateTimeTool));
}

From source file:org.jtalks.jcommune.plugin.questionsandanswers.controller.QuestionsAndAnswersController.java

/**
 * Edits existence comment/*from ww w.  ja  v  a 2 s.com*/
 *
 * @param dto dto populated in form
 * @param result validation result
 * @param branchId id of a branch to check permission
 *
 * @return result in JSON format
 */
@RequestMapping(method = RequestMethod.POST, value = "editcomment")
@ResponseBody
JsonResponse editComment(@Valid @RequestBody CommentDto dto, BindingResult result,
        @RequestParam("branchId") long branchId) {
    if (result.hasErrors()) {
        return new FailValidationJsonResponse(result.getAllErrors());
    }
    PostComment updatedComment;
    try {
        updatedComment = getCommentService().updateComment(dto.getId(), dto.getBody(), branchId);
    } catch (NotFoundException ex) {
        return new FailJsonResponse(JsonResponseReason.ENTITY_NOT_FOUND);
    }
    return new JsonResponse(JsonResponseStatus.SUCCESS, updatedComment.getBody());
}

From source file:org.jtalks.jcommune.web.controller.UserController.java

/**
 * Register {@link org.jtalks.jcommune.model.entity.JCUser} from populated {@link RegisterUserDto}.
 * <p/>//from  w w  w . j ava 2  s.c  o m
 *
 * @param registerUserDto {@link RegisterUserDto} populated in form
 * @param request   Servlet request.
 * @param locale          to set currently selected language as user's default
 * @return redirect validation result in JSON format
 */
@RequestMapping(value = "/user/new_ajax", method = RequestMethod.POST)
@ResponseBody
public JsonResponse registerUserAjax(@ModelAttribute("newUser") RegisterUserDto registerUserDto,
        HttpServletRequest request, Locale locale) {
    if (isHoneypotCaptchaFilled(registerUserDto, getClientIpAddress(request))) {
        return getCustomErrorJsonResponse(HONEYPOT_CAPTCHA_ERROR);
    }
    BindingResult errors;
    try {
        registerUserDto.getUserDto().setLanguage(Language.byLocale(locale));
        errors = authenticator.register(registerUserDto);
    } catch (NoConnectionException e) {
        return getCustomErrorJsonResponse(CONNECTION_ERROR);
    } catch (UnexpectedErrorException e) {
        return getCustomErrorJsonResponse(UNEXPECTED_ERROR);
    }
    if (errors.hasErrors()) {
        return new JsonResponse(JsonResponseStatus.FAIL, errors.getAllErrors());
    }
    return new JsonResponse(JsonResponseStatus.SUCCESS);
}

From source file:org.ojbc.web.portal.controllers.SubscriptionsController.java

private List<String> getValidationBindingErrorsList(BindingResult errors) {

    List<String> errorMsgList = null;

    if (errors.hasErrors()) {

        List<ObjectError> bindingErrorsList = errors.getAllErrors();

        errorMsgList = new ArrayList<String>();

        for (ObjectError iObjError : bindingErrorsList) {

            String errorMsgCode = iObjError.getCode();

            errorMsgList.add(errorMsgCode);
        }//from   ww w.  jav  a 2 s.co m
    }
    return errorMsgList;
}

From source file:org.openmrs.module.cohort.web.controller.AddCohortAttributesTypeController.java

@RequestMapping(value = "/module/cohort/addcohortattributestype.form", method = RequestMethod.POST)
public String onSubmit(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "name") String attribute_type,
        @RequestParam(required = false, value = "description") String description,
        @ModelAttribute("cohortattributes") CohortAttributeType cohortattributes, BindingResult errors) {
    CohortService departmentService = Context.getService(CohortService.class);
    //PatientService patientService=Context.getService(PatientService.class);
    String voided = request.getParameter("voided");
    String format = request.getParameter("format");
    this.validator.validate(cohortattributes, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());

        model.addAttribute("cohortattributes", new CohortAttributeType());
        List<String> formats = new ArrayList<String>(
                FieldGenHandlerFactory.getSingletonInstance().getHandlers().keySet());
        formats.add("java.lang.Character");
        formats.add("java.lang.Integer");
        formats.add("java.lang.Float");
        formats.add("java.lang.Boolean");
        model.addAttribute("formats", formats);
        return "/module/cohort/addcohortattributestype";
    }//  www.  j  av a  2 s. c o m
    if (attribute_type.length() > 20) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "attribute type cannot be greater than 20");
    } else {
        cohortattributes.setFormat(format);
        departmentService.saveCohort(cohortattributes);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
    }
    return null;
}