List of usage examples for org.springframework.validation BindingResult getObjectName
String getObjectName();
From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java
@Test public void testDoHandleEditBuildNumberPost02() throws IOException, ServletException { this.setUpSecurity(); SharedBuildNumber originalNumber = new SharedBuildNumber(37); expect(this.request.getParameter("action")).andReturn("edit"); expect(this.request.getMethod()).andReturn("POST"); expect(this.request.getParameter("id")).andReturn("37"); expect(this.service.getSharedBuildNumber(37)).andReturn(originalNumber); expect(this.request.getParameter("name")).andReturn("help"); expect(this.request.getParameter("description")).andReturn(""); expect(this.request.getParameter("format")).andReturn("{0"); expect(this.request.getParameter("dateFormat")).andReturn("Ym"); expect(this.request.getParameter("counter")).andReturn("15.1"); replay(this.service, this.request, this.response); ModelAndView modelAndView = this.controller.doHandle(this.request, this.response); assertNotNull("The model and view should not be null.", modelAndView); assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/editBuildNumber.jsp", modelAndView.getViewName()); Map<String, Object> model = modelAndView.getModel(); assertNotNull("The model should not be null.", model); assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX, model.get("sbnParameterPrefix")); Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm"); assertNotNull("The binding result attribute should not be null.", object); assertTrue("The binding result attribute should be a binding result object.", object instanceof BindingResult); BindingResult result = (BindingResult) object; assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm", result.getObjectName()); assertTrue("The binding result should have errors.", result.hasErrors()); assertEquals("The binding result should have 3 errors.", 3, result.getErrorCount()); List<FieldError> errors = result.getFieldErrors(); assertNotNull("The list of errors should not be null.", errors); assertEquals("The list length is not correct.", 3, errors.size()); assertEquals("The first error is not correct.", "counter", errors.get(0).getField()); assertEquals("The first error has the wrong message.", "The counter must be a positive integer.", errors.get(0).getDefaultMessage()); assertEquals("The second error is not correct.", "name", errors.get(1).getField()); assertEquals("The second error has the wrong message.", "The name must be between 5 and 60 characters long.", errors.get(1).getDefaultMessage()); assertEquals("The third error is not correct.", "format", errors.get(2).getField()); assertEquals("The third error has the wrong message.", "The build number format must be at least 3 characters long.", errors.get(2).getDefaultMessage()); object = model.get("sharedBuildNumberForm"); assertNotNull("sharedBuildNumberForm should not be null.", object); assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber); SharedBuildNumber form = (SharedBuildNumber) object; assertEquals("The name is not correct.", "help", form.getName()); assertEquals("The description is not correct.", "", form.getDescription()); assertEquals("The format is not correct.", "{0", form.getFormat()); assertEquals("The date format is not correct.", "Ym", form.getDateFormat()); assertEquals("The counter is not correct.", 1, form.getCounter()); }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java
/** * @param form/*from ww w . ja v a 2 s .c o 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"; }
From source file:io.ignitr.springboot.common.error.IgnitionErrorAttributes.java
/** * Adds the error message to the error response. * * @param errorAttributes error attributes collection *///www . jav a 2s. c om private void addDetailedMessage(Map<String, Object> errorAttributes, RequestAttributes requestAttributes) { Throwable error = getError(requestAttributes); if (error == null) { errorAttributes.put("details", null); return; } BindingResult result = extractBindingResult(error); if (result == null) { // Don't divulge detailed error information on unhandled exceptions if (error instanceof IgnitionException) { errorAttributes.put("details", error.getMessage()); } return; } if (result.getErrorCount() > 0) { errorAttributes.put("details", "Validation failed for '" + result.getObjectName() + "'. Error count: " + result.getErrorCount()); } else { // Don't divulge detailed error information on unhandled exceptions if (error instanceof IgnitionException) { errorAttributes.put("details", error.getMessage()); } } }
From source file:org.codehaus.groovy.grails.web.binding.DataBindingUtils.java
/** * Binds the given source object to the given target object performing type conversion if necessary * * @param domain The GrailsDomainClass instance * @param object The object to bind to// www . j a v a 2 s. co m * @param source The source object * @param include The list of properties to include * @param exclude The list of properties to exclud * @param filter The prefix to filter by * * @see org.codehaus.groovy.grails.commons.GrailsDomainClass * * @return A BindingResult or null if it wasn't successful */ @SuppressWarnings("unchecked") public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) { BindingResult bindingResult = null; boolean useSpringBinder = false; GrailsApplication grailsApplication = null; if (domain != null) { grailsApplication = domain.getGrailsApplication(); } if (grailsApplication == null) { grailsApplication = GrailsWebRequest.lookupApplication(); } if (grailsApplication != null) { if (Boolean.TRUE.equals(grailsApplication.getFlatConfig().get("grails.databinding.useSpringBinder"))) { useSpringBinder = true; } } if (!useSpringBinder) { try { final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source); final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication); grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude); } catch (InvalidRequestBodyException e) { String messageCode = "invalidRequestBody"; Class objectType = object.getClass(); String defaultMessage = "An error occurred parsing the body of the request"; String[] codes = getMessageCodes(messageCode, objectType); bindingResult = new BeanPropertyBindingResult(object, objectType.getName()); bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage)); } catch (Exception e) { bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName()); bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage())); } } else { if (source instanceof GrailsParameterMap) { GrailsParameterMap parameterMap = (GrailsParameterMap) source; HttpServletRequest request = parameterMap.getRequest(); GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request); dataBinder.bind(parameterMap, filter); bindingResult = dataBinder.getBindingResult(); } else if (source instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) source; GrailsDataBinder dataBinder = createDataBinder(object, include, exclude, request); performBindFromRequest(dataBinder, request, filter); bindingResult = dataBinder.getBindingResult(); } else if (source instanceof Map) { Map propertyMap = convertPotentialGStrings((Map) source); GrailsDataBinder binder = createDataBinder(object, include, exclude, null); performBindFromPropertyValues(binder, new MutablePropertyValues(propertyMap), filter); bindingResult = binder.getBindingResult(); } else { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { GrailsDataBinder binder = createDataBinder(object, include, exclude, webRequest.getCurrentRequest()); HttpServletRequest request = webRequest.getCurrentRequest(); performBindFromRequest(binder, request, filter); } } } if (domain != null && bindingResult != null) { BindingResult newResult = new ValidationErrors(object); for (Object error : bindingResult.getAllErrors()) { if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; final boolean isBlank = BLANK.equals(fieldError.getRejectedValue()); if (!isBlank) { newResult.addError(fieldError); } else if (domain.hasPersistentProperty(fieldError.getField())) { final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional(); if (!isOptional) { newResult.addError(fieldError); } } else { newResult.addError(fieldError); } } else { newResult.addError((ObjectError) error); } } bindingResult = newResult; } MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass()); if (mc.hasProperty(object, "errors") != null && bindingResult != null) { ValidationErrors errors = new ValidationErrors(object); errors.addAllErrors(bindingResult); mc.setProperty(object, "errors", errors); } return bindingResult; }
From source file:org.springframework.boot.autoconfigure.web.BasicErrorController.java
protected void addMessage(Map<String, Object> map, Throwable error) { if (error instanceof BindingResult) { BindingResult result = (BindingResult) error; if (result.getErrorCount() > 0) { map.put("errors", result.getAllErrors()); map.put("message", "Validation failed for object='" + result.getObjectName() + "'. Error count: " + result.getErrorCount()); } else {/*from w ww . ja v a 2 s. co m*/ map.put("message", "No errors"); } } else { map.put("message", error.getMessage()); } }