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:com.rr.generic.ui.calendar.calendarController.java

@RequestMapping(value = "/saveEvent.do", method = RequestMethod.POST)
public @ResponseBody Integer saveEvent(@ModelAttribute(value = "calendarEvent") calendarEvents calendarEvent,
        BindingResult errors,
        @RequestParam(value = "alertAllUsers", required = false, defaultValue = "0") Integer alertUsers,
        @RequestParam(value = "eventDocuments", required = false) List<MultipartFile> eventDocuments,
        HttpSession session, HttpServletRequest request,
        @RequestParam(value = "selectedEntities", required = false) List<Integer> selectedEntities)
        throws Exception {

    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            System.out.println(error.getDefaultMessage());
        }// www . ja  v  a  2 s.  co m
    }

    User userDetails = (User) session.getAttribute("userDetails");

    boolean alertAllUsers = false;

    if (alertUsers == 1) {
        alertAllUsers = true;
    }

    /* Need to transfer String start and end date to real date */
    DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    Date realStartDate = format.parse(calendarEvent.getStartDate());
    Date realEndDate = format.parse(calendarEvent.getEndDate());

    calendarEvent.setEventStartDate(realStartDate);
    calendarEvent.setEventEndDate(realEndDate);

    if (eventDocuments != null) {
        calendarEvent.setUploadedDocuments(eventDocuments);
    }
    Integer originalEventId = calendarEvent.getId();
    Integer eventId = calendarManager.saveEvent(calendarEvent);

    program programDetails = programManager.getProgramById(programId);

    calendarEventTypes eventType = calendarManager.getEventType(calendarEvent.getEventTypeId());

    /* Remove existing entities */
    calendarManager.removeEventEntities(programId, eventId);

    /* Enter the selected counties */
    if (calendarEvent.getWhichEntity() == 1) {
        /* Need to get all top entities for the program */
        programOrgHierarchy topLevel = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId);
        List<programHierarchyDetails> entities = hierarchymanager.getProgramHierarchyItems(topLevel.getId(), 0);

        if (entities != null && entities.size() > 0) {
            for (programHierarchyDetails entity : entities) {
                calendarEventEntities eventEntity = new calendarEventEntities();
                eventEntity.setEntityId(entity.getId());
                eventEntity.setProgramId(programId);
                eventEntity.setEventId(eventId);

                calendarManager.saveEventEntities(eventEntity);
            }
        }
    } else if (calendarEvent.getWhichEntity() == 2 && selectedEntities != null
            && !"".equals(selectedEntities)) {
        for (Integer entity : selectedEntities) {
            calendarEventEntities eventEntity = new calendarEventEntities();
            eventEntity.setEntityId(entity);
            eventEntity.setProgramId(programId);
            eventEntity.setEventId(eventId);

            calendarManager.saveEventEntities(eventEntity);
        }
    }

    //Modifed Event Notification
    //calendarEvent's id will be populated after save or update, must track some other way
    if (originalEventId > 0 && alertAllUsers == true) {
        // inserting into db an entry so notifications can go out later 
        //insert event email notification
        calendarEmailNotifications calendarEmailNotification = new calendarEmailNotifications();
        calendarEmailNotification.setNotificationType(2);
        calendarEmailNotification.setProgramId(programId);
        calendarEmailNotification.setCalendarEventId(eventId);
        calendarManager.saveCalendarEmailNotification(calendarEmailNotification);

    } //New Event Notification
    else if (alertAllUsers == true) {
        //insert event email notification
        calendarEmailNotifications calendarEmailNotification = new calendarEmailNotifications();
        calendarEmailNotification.setNotificationType(1);
        calendarEmailNotification.setProgramId(programId);
        calendarEmailNotification.setCalendarEventId(eventId);
        calendarManager.saveCalendarEmailNotification(calendarEmailNotification);
    }

    return 1;

}

From source file:mvc.MessageController.java

/**
 *  ? /*from w w  w  . j  av  a 2  s .  c  om*/
 *
 * @param model
 * @param obj
 * @param bindRes
 * @param orderId
 * @param files
 * @param attr
 * @param destinationAuthorId
 * @param cost
 * @return
 * @throws IOException
 * @throws NotRightException
 */
@RequestMapping("/addAuthor")
public String addAuthorMessage(Map<String, Object> model,
        @ModelAttribute("authorMessage") @Valid AuthorMessage obj, BindingResult bindRes,
        @RequestParam("orderId") Long orderId,
        @RequestParam(value = "file", required = false) MultipartFile[] files, RedirectAttributes attr,
        @RequestParam(value = "destinationAuthorId") Long destinationAuthorId,
        @RequestParam(value = "cost", required = false) Double cost,
        @RequestParam(value = "sendToAll", required = false) String sendToAll)
        throws IOException, NotRightException {

    checkBranchRight(orderId, "/Message/addAuthor");
    boolean toAll = (sendToAll != null && !sendToAll.isEmpty());
    String errorAttrName = "errors";
    if (!bindRes.hasErrors()) {
        ServiceResult res = _addAuthorMessage(obj, files, orderId, destinationAuthorId, cost, toAll);
        if (res.hasErrors()) {
            attr.addFlashAttribute(errorAttrName, res.getErrors());
        }
    } else {
        attr.addFlashAttribute(errorAttrName, bindRes.getAllErrors());
    }
    return "redirect:/Order/get?orderId=" + orderId;
}

From source file:au.org.ala.biocache.web.OccurrenceController.java

/**
 * Constructs an error message to be displayed. The error message is based on validation checks that
 * were performed and stored in the supplied result.
 *
 * TODO: If we decide to perform more detailed validations elsewhere it maybe worth providing this in a
 * util or service class.// w  w  w. ja  v a  2s  .c o  m
 *
 * @param result The result from the validation.
 * @return A string representation that can be displayed in a browser.
 */
private String getValidationErrorMessage(BindingResult result) {
    StringBuilder sb = new StringBuilder();
    List<ObjectError> errors = result.getAllErrors();
    for (ObjectError error : errors) {
        logger.debug("Code: " + error.getCode());
        logger.debug(StringUtils.join(error.getCodes(), "@#$^"));
        String code = (error.getCodes() != null && error.getCodes().length > 0) ? error.getCodes()[0] : null;
        logger.debug("The code in use:" + code);
        sb.append(messageSource.getMessage(code, null, error.getDefaultMessage(), null)).append("<br/>");
    }
    return sb.toString();
}

From source file:org.openmrs.module.registration.page.controller.EditPatientContactInfoPageController.java

/**
 * @should void the old person address and replace it with a new one when it is edited
 * @should void the old person address and replace it with a new one when it is edited
 * @should not void the existing address if there are no changes
 */// w  w  w .java2 s.  com
public String post(UiSessionContext sessionContext, PageModel model,
        @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonAddress address,
        @SpringBean("patientService") PatientService patientService, @RequestParam("appId") AppDescriptor app,
        @RequestParam("returnUrl") String returnUrl,
        @SpringBean("adminService") AdministrationService administrationService, HttpServletRequest request,
        @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session,
        @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonAddress() != null && address != null) {
        PersonAddress currentAddress = patient.getPersonAddress();
        if (!currentAddress.equalsContent(address)) {
            //void the old address and replace it with the new one
            patient.addAddress(address);
            currentAddress.setVoided(true);
        }
    }

    NavigableFormStructure formStructure = RegisterPatientFormBuilder.buildFormStructure(app);

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);
    RegistrationUiUtils.validateLatitudeAndLongitudeIfNecessary(address, errors);

    if (formStructure != null) {
        RegisterPatientFormBuilder.resolvePersonAttributeFields(formStructure, patient,
                request.getParameterMap());
    }

    if (!errors.hasErrors()) {
        try {
            //The person address changes get saved along as with the call to save patient
            patientService.savePatient(patient);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    ui.message("registration.editContactInfoMessage.success", patient.getPersonName()));

            return "redirect:" + returnUrl;
        } catch (Exception e) {
            log.warn("Error occurred while saving patient's contact info", e);
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "registration.save.fail");
        }

    } else {
        model.addAttribute("errors", errors);
        StringBuffer errorMessage = new StringBuffer(
                messageSourceService.getMessage("error.failed.validation"));
        errorMessage.append("<ul>");
        for (ObjectError error : errors.getAllErrors()) {
            errorMessage.append("<li>");
            errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), null));
            errorMessage.append("</li>");
        }
        errorMessage.append("</ul>");
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    addModelAttributes(model, patient, formStructure, administrationService, returnUrl);
    //redisplay the form
    return null;
}

From source file:org.openmrs.module.OpenmrsLite.page.controller.EditPatientContactInfoPageController.java

/**
 * @should void the old person address and replace it with a new one when it is edited
 * @should void the old person address and replace it with a new one when it is edited
 * @should not void the existing address if there are no changes
 *//*from   ww w. j  ava2  s  . c o m*/
public String post(UiSessionContext sessionContext, PageModel model,
        @RequestParam("patientId") @BindParams Patient patient, @BindParams PersonAddress address,
        @SpringBean("patientService") PatientService patientService, @RequestParam("appId") AppDescriptor app,
        @RequestParam("returnUrl") String returnUrl,
        @SpringBean("adminService") AdministrationService administrationService, HttpServletRequest request,
        @SpringBean("messageSourceService") MessageSourceService messageSourceService, Session session,
        @SpringBean("patientValidator") PatientValidator patientValidator, UiUtils ui) throws Exception {

    sessionContext.requireAuthentication();

    if (patient.getPersonAddress() != null && address != null) {
        PersonAddress currentAddress = patient.getPersonAddress();
        if (!currentAddress.equalsContent(address)) {
            //void the old address and replace it with the new one
            patient.addAddress(address);
            currentAddress.setVoided(true);
        }
    }

    NavigableFormStructure formStructure = RegisterPatientFormBuilder.buildFormStructure(app);

    BindingResult errors = new BeanPropertyBindingResult(patient, "patient");
    patientValidator.validate(patient, errors);
    RegistrationAppUiUtils.validateLatitudeAndLongitudeIfNecessary(address, errors);

    if (formStructure != null) {
        RegisterPatientFormBuilder.resolvePersonAttributeFields(formStructure, patient,
                request.getParameterMap());
    }

    if (!errors.hasErrors()) {
        try {
            //The person address changes get saved along as with the call to save patient
            patientService.savePatient(patient);
            InfoErrorMessageUtil.flashInfoMessage(request.getSession(),
                    ui.message("OpenmrsLite.editContactInfoMessage.success", patient.getPersonName()));

            return "redirect:" + returnUrl;
        } catch (Exception e) {
            log.warn("Error occurred while saving patient's contact info", e);
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, "OpenmrsLite.save.fail");
        }

    } else {
        model.addAttribute("errors", errors);
        StringBuffer errorMessage = new StringBuffer(
                messageSourceService.getMessage("error.failed.validation"));
        errorMessage.append("<ul>");
        for (ObjectError error : errors.getAllErrors()) {
            errorMessage.append("<li>");
            errorMessage.append(messageSourceService.getMessage(error.getCode(), error.getArguments(),
                    error.getDefaultMessage(), null));
            errorMessage.append("</li>");
        }
        errorMessage.append("</ul>");
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, errorMessage.toString());
    }

    addModelAttributes(model, patient, formStructure, administrationService, returnUrl);
    //redisplay the form
    return null;
}

From source file:alfio.controller.api.user.RestEventApiController.java

@RequestMapping(value = "events/{shortName}/reserve-tickets", method = RequestMethod.POST)
public ResponseEntity<Result<String>> reserveTickets(@PathVariable("shortName") String shortName,
        @RequestBody ReservationForm reservation, BindingResult bindingResult, Locale locale) {
    return eventRepository.findOptionalByShortName(shortName).map(event -> {
        Optional<String> reservationUrl = reservation.validate(bindingResult, ticketReservationManager,
                additionalServiceRepository, eventManager, event).flatMap(selected -> {
                    Date expiration = DateUtils.addMinutes(new Date(),
                            ticketReservationManager.getReservationTimeout(event));
                    try {
                        String reservationId = ticketReservationManager.createTicketReservation(event,
                                selected.getLeft(), selected.getRight(), expiration,
                                Optional.ofNullable(reservation.getPromoCode()), //FIXME check
                                Optional.ofNullable(reservation.getPromoCode()), //FIXME check
                                locale, false);
                        return Optional.of("/event/" + shortName + "/reservation/" + reservationId + "/book");
                    } catch (TicketReservationManager.NotEnoughTicketsException nete) {
                        bindingResult.reject(ErrorsCode.STEP_1_NOT_ENOUGH_TICKETS);
                    } catch (TicketReservationManager.MissingSpecialPriceTokenException missing) {
                        bindingResult.reject(ErrorsCode.STEP_1_ACCESS_RESTRICTED);
                    } catch (TicketReservationManager.InvalidSpecialPriceTokenException invalid) {
                        bindingResult.reject(ErrorsCode.STEP_1_CODE_NOT_FOUND);
                    }/*from  w ww  .  j  ava 2 s. co m*/
                    return Optional.empty();
                });

        Result<String> result = reservationUrl.map(url -> Result.success(url))
                .orElseGet(() -> Result.validationError(bindingResult.getAllErrors()));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java

/**
 * @param form/*from www .j  a v  a 2s.  co  m*/
 * @param result
 * @param map
 * @param status
 * @return
 */
@RequestMapping(value = { "/{userParam}/myprofile" }, method = RequestMethod.POST)
public String edit(@PathVariable String userParam, @Valid @ModelAttribute("user") UserForm form,
        BindingResult result, HttpServletRequest request, ModelMap map, SessionStatus status) {
    logger.debug("###Entering in edit(form,result,map,status) method @POST");
    com.citrix.cpbm.access.User user = form.getUser();

    MyProfileValidator validator = new MyProfileValidator();
    validator.validate(form, result);
    if (result.hasErrors()
            && !(result.getErrorCount() == 1 && result.getAllErrors().get(0).getCode().equals("Size")
                    && form.getUser().getUsername().equals("root"))) {
        displayErrors(result);
        // TODO to return the edit page with errors
        return "redirect:/portal/users/" + userParam + "/myprofile";
    }
    User logedInUser = this.getCurrentUser();
    if (isEmailBlacklisted(user.getEmail().toLowerCase())) {
        logger.info("Email Id : " + form.getUser().getEmail()
                + " rejected because it is not on the whitelist or part of the blacklist. Kindly contact support");
        result.rejectValue("user.email", "signup.emaildomain.blacklist.error");
        return edit(null, user.getObject().getUuid(), request, map);
    }
    if (form.getClearPassword() != null && !form.getClearPassword().isEmpty()) { // password reset
        if (form.getOldPassword() == null) {
            result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false,
                    new String[] { "errors.password.required" }, null, null));
        } else if (!user.getObject().authenticate(form.getOldPassword())) {
            result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false,
                    new String[] { "errors.password.invalid" }, null, null));
        } else {
            user.getObject().setClearPassword(form.getClearPassword());
        }
    }
    com.citrix.cpbm.access.User userClone = form.getUserClone();
    // TODO need to do Validation(Once fix this then remove @Ignore annotation against testUpdateUserFail from Test
    // Suit.
    form.setPhone(form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "")); // removing all characters from phone number
    String oldPhone = userClone.getPhoneWithoutIsdCode() != null ? userClone.getPhoneWithoutIsdCode() : "";
    boolean phoneVerificationEnabled = false;
    if (!form.getPhone().equals(oldPhone.replaceAll(PHONE_NUMBER_REGEX, ""))
            || !form.getCountryCode().toString().equals(user.getCountryCode())) {

        if (connectorManagementService.getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION) != null
                && ((TelephoneVerificationService) connectorManagementService
                        .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).isEnabled()) {
            phoneVerificationEnabled = true;
        }

        if (phoneVerificationEnabled && !userService.hasAuthority(logedInUser, "ROLE_ACCOUNT_CRUD")) {
            String generatedPhoneVerificationPin = (String) request.getSession()
                    .getAttribute("phoneVerificationPin");
            String actualPhoneNumber = (String) request.getSession().getAttribute("phoneNumber");
            if (form.getUserEnteredPhoneVerificationPin() == null
                    || !form.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin)
                    || !areDigitsInPhoneNosEqual(form.getPhone(), actualPhoneNumber)) {
                map.addAttribute("userEditError", "phoneVerfication.error");
                result.rejectValue("phone", "phoneVerfication.error");
                parseResult(result, map);
                return edit(null, user.getObject().getUuid(), request, map);
            }
        }
    }
    String phoneNo = form.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "")
            + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "");
    // Set the phone number
    if (!phoneVerificationEnabled && StringUtils.isEmpty(form.getPhone())) {
        user.setPhone(null);
    } else {
        user.setPhone(phoneNo);
    }

    if ((user.getObject().getTenant().getState() == State.ACTIVE
            || user.getObject().getTenant().getState() == State.LOCKED
            || user.getObject().getTenant().getState() == State.SUSPENDED)
            && !user.getEmail().equals(userClone.getEmail())) {
        userAlertPreferencesService.createUserAlertPreference(user.getObject(), user.getEmail(),
                AlertType.USER_EMAIL);
        // set email so that it wont be updated in users table and other places
        user.setEmail(userClone.getEmail());
        user.setEmailVerified(true);
    }
    userService.update(user, result);
    form.setUser(user);
    map.addAttribute("user", form);
    setPage(map, Page.USER_PERSONAL_PROFILE);
    status.setComplete();
    logger.debug("###Exiting edit(form,result,map,status) method @POST");
    map.clear();
    return "redirect:/portal/users/" + user.getObject().getParam() + "/myprofile";
}