Search in sources :

Example 61 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class DateFormattingTests method styleDateWithInvalidFormat.

@Test
void styleDateWithInvalidFormat() {
    String propertyName = "styleDate";
    String propertyValue = "99/01/01";
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    propertyValues.add(propertyName, propertyValue);
    binder.bind(propertyValues);
    BindingResult bindingResult = binder.getBindingResult();
    assertThat(bindingResult.getErrorCount()).isEqualTo(1);
    FieldError fieldError = bindingResult.getFieldError(propertyName);
    TypeMismatchException exception = fieldError.unwrap(TypeMismatchException.class);
    assertThat(exception).hasMessageContaining("for property 'styleDate'").hasCauseInstanceOf(ConversionFailedException.class).getCause().hasMessageContaining("for value '99/01/01'").hasCauseInstanceOf(IllegalArgumentException.class).getCause().hasMessageContaining("Parse attempt failed for value [99/01/01]").hasCauseInstanceOf(ParseException.class).getCause().hasMessageContainingAll("Unable to parse date time value \"99/01/01\" using configuration from", "@org.springframework.format.annotation.DateTimeFormat", "style=", "S-", "iso=NONE").hasCauseInstanceOf(ParseException.class).getCause().hasMessageStartingWith("Unparseable date: \"99/01/01\"").hasNoCause();
}
Also used : BindingResult(org.springframework.validation.BindingResult) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) TypeMismatchException(org.springframework.beans.TypeMismatchException) FieldError(org.springframework.validation.FieldError) ParseException(java.text.ParseException) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 62 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class BindingAwareConcurrentModel method removeBindingResultIfNecessary.

private void removeBindingResultIfNecessary(String key, @Nullable Object value) {
    if (!key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
        String resultKey = BindingResult.MODEL_KEY_PREFIX + key;
        BindingResult result = (BindingResult) get(resultKey);
        if (result != null && result.getTarget() != value) {
            remove(resultKey);
        }
    }
}
Also used : BindingResult(org.springframework.validation.BindingResult)

Example 63 with BindingResult

use of org.springframework.validation.BindingResult in project OpenClinica by OpenClinica.

the class SDVController method viewAllSubjectFormHandler.

@RequestMapping("/viewAllSubjectSDVform")
public ModelMap viewAllSubjectFormHandler(HttpServletRequest request, HttpServletResponse response, @RequestParam("studyId") int studyId) {
    ModelMap gridMap = new ModelMap();
    StudyDAO studyDAO = new StudyDAO(dataSource);
    // StudyEventDAO studyEventDAO = new StudyEventDAO(dataSource);
    StudyBean studyBean = (StudyBean) studyDAO.findByPK(studyId);
    String pattern = "MM/dd/yyyy";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    // List<StudyEventBean> studyEventBeans = studyEventDAO.findAllByStudy(studyBean);
    // List<EventCRFBean> eventCRFBeans = sdvUtil.getAllEventCRFs(studyEventBeans);
    // set up the parameters to take part in filtering
    ServletRequestDataBinder dataBinder = new ServletRequestDataBinder(new SdvFilterDataBean());
    dataBinder.setAllowedFields(new String[] { "study_subject_id", "studyEventDefinition", "studyEventStatus", "eventCRFStatus", "sdvRequirement", "eventcrfSDVStatus", "startUpdatedDate", "endDate", "eventCRFName" });
    dataBinder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(sdf, true));
    dataBinder.bind(request);
    BindingResult bindingResult = dataBinder.getBindingResult();
    // eventCRFBeans = sdvUtil.filterEventCRFs(eventCRFBeans,bindingResult);
    // set up request attributes for sidebar
    // Not necessary when using old page design...
    // setUpSidebar(request);
    request.setAttribute("studyId", studyId);
    // We need a study subject id for the first tab; take it somewhat arbitrarily from the first study event bean
    /* int studySubjectId = 0;

        StudyEventBean studyBeanUrl = studyEventBeans.get(0);
        if(studyBeanUrl != null) {
            studySubjectId= studyBeanUrl.getStudySubjectId();
        }
        request.setAttribute("studySubjectId",studySubjectId);*/
    // set up the elements for the view's filter box
    /*sdvUtil.prepareSDVSelectElements(request,studyBean);*/
    ArrayList<String> pageMessages = (ArrayList<String>) request.getAttribute("pageMessages");
    if (pageMessages == null) {
        pageMessages = new ArrayList<String>();
    }
    request.setAttribute("pageMessages", pageMessages);
    String sdvMatrix = sdvUtil.renderEventCRFTableWithLimit(request, studyId, "");
    gridMap.addAttribute(SUBJECT_SDV_TABLE_ATTRIBUTE, sdvMatrix);
    return gridMap;
}
Also used : BindingResult(org.springframework.validation.BindingResult) CustomDateEditor(org.springframework.beans.propertyeditors.CustomDateEditor) ModelMap(org.springframework.ui.ModelMap) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) ServletRequestDataBinder(org.springframework.web.bind.ServletRequestDataBinder) ArrayList(java.util.ArrayList) SdvFilterDataBean(org.akaza.openclinica.controller.helper.SdvFilterDataBean) StudyDAO(org.akaza.openclinica.dao.managestudy.StudyDAO) SimpleDateFormat(java.text.SimpleDateFormat) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 64 with BindingResult

use of org.springframework.validation.BindingResult in project zhcet-web by zhcet-amu.

the class PasswordResetController method savePassword.

@PostMapping
@PreAuthorize("hasAuthority('PASSWORD_CHANGE_PRIVILEGE')")
public String savePassword(@Valid PasswordReset passwordReset, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    Optional<User> optionalUser = Auditor.getLoggedInAuthentication().map(Authentication::getPrincipal).filter(principal -> !principal.getClass().isAssignableFrom(User.class)).map(principal -> ((User) principal).getUserId()).flatMap(userService::findById);
    if (!optionalUser.isPresent()) {
        redirectAttributes.addAttribute("error", "Unknown Error");
    } else {
        User user = optionalUser.get();
        if (bindingResult.hasErrors()) {
            redirectAttributes.addFlashAttribute("password", passwordReset);
            redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.password", bindingResult);
        } else {
            try {
                passwordResetService.resetPassword(user, passwordReset);
                redirectAttributes.addFlashAttribute("reset_success", true);
                return "redirect:/login";
            } catch (TokenValidationException tve) {
                log.warn("Token Verification : Password Reset : {}", tve.getMessage());
                redirectAttributes.addAttribute("error", tve.getMessage());
            } catch (PasswordValidationException pve) {
                log.debug("Password Verification Exception", pve);
                redirectAttributes.addFlashAttribute("pass_errors", pve.getMessage());
            }
        }
    }
    return String.format("redirect:/login/password/reset?hash=%s&auth=%s", passwordReset.getHash(), passwordReset.getToken());
}
Also used : User(amu.zhcet.data.user.User) RedirectAttributes(org.springframework.web.servlet.mvc.support.RedirectAttributes) PostMapping(org.springframework.web.bind.annotation.PostMapping) RequestParam(org.springframework.web.bind.annotation.RequestParam) PasswordValidationException(amu.zhcet.auth.password.PasswordValidationException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) BindingResult(org.springframework.validation.BindingResult) Controller(org.springframework.stereotype.Controller) Valid(javax.validation.Valid) Slf4j(lombok.extern.slf4j.Slf4j) Model(org.springframework.ui.Model) PasswordReset(amu.zhcet.auth.password.PasswordReset) GetMapping(org.springframework.web.bind.annotation.GetMapping) Optional(java.util.Optional) UserService(amu.zhcet.data.user.UserService) Auditor(amu.zhcet.auth.Auditor) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) User(amu.zhcet.data.user.User) PasswordValidationException(amu.zhcet.auth.password.PasswordValidationException) PostMapping(org.springframework.web.bind.annotation.PostMapping) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 65 with BindingResult

use of org.springframework.validation.BindingResult in project alf.io by alfio-event.

the class TicketApiV2Controller method updateTicketInfo.

@PutMapping("/api/v2/public/event/{eventName}/ticket/{ticketIdentifier}")
public ResponseEntity<ValidatedResponse<Boolean>> updateTicketInfo(@PathVariable("eventName") String eventName, @PathVariable("ticketIdentifier") String ticketIdentifier, @RequestBody UpdateTicketOwnerForm updateTicketOwner, BindingResult bindingResult, Authentication authentication) {
    var a = ticketReservationManager.fetchComplete(eventName, ticketIdentifier);
    if (a.isEmpty()) {
        return ResponseEntity.notFound().build();
    }
    Optional<UserDetails> userDetails = Optional.ofNullable(authentication).map(Authentication::getPrincipal).filter(UserDetails.class::isInstance).map(UserDetails.class::cast);
    Locale locale = LocaleUtil.forLanguageTag(a.get().getMiddle().getUserLanguage(), a.get().getLeft());
    var assignmentResult = ticketHelper.assignTicket(eventName, ticketIdentifier, updateTicketOwner, Optional.of(bindingResult), locale, userDetails, false);
    return assignmentResult.map(r -> ResponseEntity.status(r.getLeft().isSuccess() ? HttpStatus.OK : HttpStatus.UNPROCESSABLE_ENTITY).body(new ValidatedResponse<>(r.getLeft(), r.getLeft().isSuccess()))).orElseThrow(IllegalStateException::new);
}
Also used : Locale(java.util.Locale) TicketInfo(alfio.controller.api.v2.model.TicketInfo) TicketHelper(alfio.controller.api.support.TicketHelper) TicketCategoryRepository(alfio.repository.TicketCategoryRepository) PaymentProxy(alfio.model.transaction.PaymentProxy) TemplateProcessor(alfio.controller.support.TemplateProcessor) MessageSourceManager(alfio.manager.i18n.MessageSourceManager) MessageDigest(java.security.MessageDigest) BindingResult(org.springframework.validation.BindingResult) StringUtils(org.apache.commons.lang3.StringUtils) Formatters(alfio.controller.support.Formatters) Locale(java.util.Locale) ValidatedResponse(alfio.manager.support.response.ValidatedResponse) UserDetails(org.springframework.security.core.userdetails.UserDetails) ReservationInfo(alfio.controller.api.v2.model.ReservationInfo) DatesWithTimeZoneOffset(alfio.controller.api.v2.model.DatesWithTimeZoneOffset) OutputStream(java.io.OutputStream) OrganizationRepository(alfio.repository.user.OrganizationRepository) TicketRepository(alfio.repository.TicketRepository) Organization(alfio.model.user.Organization) EventUtil.firstMatchingCallLink(alfio.util.EventUtil.firstMatchingCallLink) TemplateManager(alfio.util.TemplateManager) MediaType(org.springframework.http.MediaType) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) StandardCharsets(java.nio.charset.StandardCharsets) ZoneId(java.time.ZoneId) HttpStatus(org.springframework.http.HttpStatus) TicketReservationManager(alfio.manager.TicketReservationManager) List(java.util.List) ImageUtil(alfio.util.ImageUtil) ChronoUnit(java.time.temporal.ChronoUnit) OnlineCheckInInfo(alfio.controller.api.v2.model.OnlineCheckInInfo) alfio.model(alfio.model) NotificationManager(alfio.manager.NotificationManager) LocaleUtil(alfio.util.LocaleUtil) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) BookingInfoTicketLoader(alfio.controller.api.v2.user.support.BookingInfoTicketLoader) Optional(java.util.Optional) FileUploadManager(alfio.manager.FileUploadManager) ResponseEntity(org.springframework.http.ResponseEntity) ExtensionManager(alfio.manager.ExtensionManager) AllArgsConstructor(lombok.AllArgsConstructor) DigestUtils(org.apache.commons.codec.digest.DigestUtils) Authentication(org.springframework.security.core.Authentication) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication)

Aggregations

BindingResult (org.springframework.validation.BindingResult)143 Test (org.junit.jupiter.api.Test)29 Test (org.junit.Test)28 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)24 List (java.util.List)23 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)23 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)21 ResponseEntity (org.springframework.http.ResponseEntity)20 Collectors (java.util.stream.Collectors)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)18 FieldError (org.springframework.validation.FieldError)18 ObjectError (org.springframework.validation.ObjectError)17 Model (org.springframework.ui.Model)15 ControllerAdvice (org.springframework.web.bind.annotation.ControllerAdvice)14 HashMap (java.util.HashMap)13 Nonnull (javax.annotation.Nonnull)13 Nullable (javax.annotation.Nullable)13 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)13 DefaultProblem (org.zalando.problem.DefaultProblem)13 Problem (org.zalando.problem.Problem)13