List of usage examples for org.springframework.validation FieldError getField
public String getField()
From source file:com.google.ie.web.controller.ProjectCommentController.java
/** * Handles request to add comment on a Project. * //from w w w . j ava 2 s. c o m * @param projectComment key of the Project on which the comment is to be * added. * @param user the User object * @throws IOException */ @RequestMapping(value = "/postProjectComments", method = RequestMethod.POST) public void postCommentOnProject(HttpServletRequest request, @ModelAttribute ProjectComment projectComment, BindingResult result, Map<String, Object> map, @RequestParam String recaptchaChallengeField, @RequestParam String recaptchaResponseField, HttpSession session) throws IOException { ViewStatus viewStatus = new ViewStatus(); Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField, recaptchaResponseField); /* call CommentValidator to validate input ProjectComment object */ getCommentValidator().validate(projectComment, result); if (result.hasErrors() || !captchaValidation) { logger.warn("Comment object has " + result.getErrorCount() + " validation errors"); viewStatus.setStatus(WebConstants.ERROR); /* Add a message if the captcha validation fails */ if (!captchaValidation) { viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH); } /* Iterate the errors and add a message for each error */ for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator.hasNext();) { FieldError fieldError = iterator.next(); viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage()); logger.warn("Error found in field: " + fieldError.getField() + " Message :" + fieldError.getDefaultMessage()); } } else { User user = (User) session.getAttribute(WebConstants.USER); Comment comment = commentService.addComment(projectComment, user); if (comment != null) { viewStatus.setStatus(WebConstants.SUCCESS); viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL); } else { viewStatus.setStatus(WebConstants.ERROR); viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED); } } map.remove("projectComment"); map.put(WebConstants.VIEW_STATUS, viewStatus); }
From source file:com.mmj.app.web.controller.BaseController.java
/** * ??/* w w w .j a v a 2 s .c o m*/ * * @param result * @return */ public Result showErrors(BindingResult result) { StringBuffer errorsb = new StringBuffer(); if (result.hasErrors()) { for (FieldError error : result.getFieldErrors()) { errorsb.append(error.getField()); errorsb.append(error.getDefaultMessage()); errorsb.append("|"); } String errorsr = errorsb.toString().substring(0, errorsb.toString().length() - 1); Result.failed(errorsr.replaceAll("null", StringUtils.EMPTY)); } return Result.success(); }
From source file:org.apereo.openlrs.controllers.xapi.XAPIExceptionHandlerAdvice.java
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody/*from w w w. j a v a 2 s. c o m*/ public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request, MethodArgumentNotValidException e) { final List<String> errorMessages = new ArrayList<String>(); for (ObjectError oe : e.getBindingResult().getAllErrors()) { if (oe instanceof FieldError) { final FieldError fe = (FieldError) oe; final String msg = String.format("Field error in object '%s' on field '%s': rejected value [%s].", fe.getObjectName(), fe.getField(), fe.getRejectedValue()); errorMessages.add(msg); } else { errorMessages.add(oe.toString()); } } final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages); this.logException(e); this.logError(result); return result; }
From source file:utils.play.BugWorkaroundForm.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from w w w .j a v a 2s . co m public Form<T> bind(final Map<String, String> data, final String... allowedFields) { DataBinder dataBinder = null; Map<String, String> objectData = data; if (rootName == null) { dataBinder = new DataBinder(blankInstance()); } else { dataBinder = new DataBinder(blankInstance(), rootName); objectData = new HashMap<String, String>(); for (String key : data.keySet()) { if (key.startsWith(rootName + ".")) { objectData.put(key.substring(rootName.length() + 1), data.get(key)); } } } if (allowedFields.length > 0) { dataBinder.setAllowedFields(allowedFields); } SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator()); dataBinder.setValidator(validator); dataBinder.setConversionService(play.data.format.Formatters.conversion); dataBinder.setAutoGrowNestedPaths(true); dataBinder.bind(new MutablePropertyValues(objectData)); Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget()); BindingResult result = dataBinder.getBindingResult(); for (ConstraintViolation<Object> violation : validationErrors) { String field = violation.getPropertyPath().toString(); FieldError fieldError = result.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { result.rejectValue(field, violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), getArgumentsForConstraint(result.getObjectName(), field, violation.getConstraintDescriptor()), violation.getMessage()); } catch (NotReadablePropertyException ex) { throw new IllegalStateException("JSR-303 validated property '" + field + "' does not have a corresponding accessor for data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } if (result.hasErrors()) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); for (FieldError error : result.getFieldErrors()) { String key = error.getObjectName() + "." + error.getField(); System.out.println("Error field:" + key); if (key.startsWith("target.") && rootName == null) { key = key.substring(7); } List<Object> arguments = new ArrayList<>(); for (Object arg : error.getArguments()) { if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) { arguments.add(arg); } } if (!errors.containsKey(key)) { errors.put(key, new ArrayList<ValidationError>()); } errors.get(key).add(new ValidationError(key, error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments)); } return new Form(rootName, backedType, data, errors, F.Option.None()); } else { Object globalError = null; if (result.getTarget() != null) { try { java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate"); globalError = v.invoke(result.getTarget()); } catch (NoSuchMethodException e) { } catch (Throwable e) { throw new RuntimeException(e); } } if (globalError != null) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); if (globalError instanceof String) { errors.put("", new ArrayList<ValidationError>()); errors.get("").add(new ValidationError("", (String) globalError, new ArrayList())); } else if (globalError instanceof List) { for (ValidationError error : (List<ValidationError>) globalError) { List<ValidationError> errorsForKey = errors.get(error.key()); if (errorsForKey == null) { errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>()); } errorsForKey.add(error); } } else if (globalError instanceof Map) { errors = (Map<String, List<ValidationError>>) globalError; } if (result.getTarget() != null) { return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget())); } else { return new Form(rootName, backedType, data, errors, F.Option.None()); } } return new Form(rootName, backedType, new HashMap<String, String>(data), new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget())); } }
From source file:com.google.ie.web.controller.CommentController.java
/** * Handles request to add comment on Idea. * /*ww w. jav a 2 s. com*/ * @param ideaComment key of the Idea on which the comment is to be added. * @param user the User object * @throws IOException */ @RequestMapping(value = "/post", method = RequestMethod.POST) public void postCommentOnIdea(HttpServletRequest request, HttpSession session, @ModelAttribute IdeaComment ideaComment, BindingResult result, Map<String, Object> map, @RequestParam String recaptchaChallengeField, @RequestParam String recaptchaResponseField) throws IOException { /* * get captcha fields from request call CommentValidator to validate * input IdeaComment object */ ViewStatus viewStatus = new ViewStatus(); Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField, recaptchaResponseField); new CommentValidator().validate(ideaComment, result); /* * check for validation or captcha error and if error occured display * the error messages. */ if (result.hasErrors() || !captchaValidation) { logger.warn("Comment object has " + result.getErrorCount() + " validation errors"); viewStatus.setStatus(WebConstants.ERROR); if (!captchaValidation) { viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH); } for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator.hasNext();) { FieldError fieldError = iterator.next(); viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage()); logger.warn("Error found in field: " + fieldError.getField() + " Message :" + fieldError.getDefaultMessage()); } } else { User user = (User) session.getAttribute(WebConstants.USER); /* Call comment service to add new comment */ Comment comment = commentService.addComment(ideaComment, user); if (comment != null) { viewStatus.setStatus(WebConstants.SUCCESS); viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL); } else { viewStatus.setStatus(WebConstants.ERROR); viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED); } } map.remove("ideaComment"); map.put(WebConstants.VIEW_STATUS, viewStatus); }
From source file:cz.muni.fi.mvc.controllers.StewardController.java
/** * Creates a new Steward/* www . java 2s.c om*/ * * @param model display data * @return jsp page */ @RequestMapping(method = RequestMethod.POST, value = "/create") public String create(@Valid @ModelAttribute("stewardCreate") StewardCreationalDTO formBean, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder, HttpServletRequest request) { if (bindingResult.hasErrors()) { for (FieldError fe : bindingResult.getFieldErrors()) { model.addAttribute(fe.getField() + "_error", true); log.trace("FieldError: {}", fe); } for (ObjectError ge : bindingResult.getGlobalErrors()) { log.trace("ObjectError: {}", ge); } return "steward/new"; } Long id = 0L; try { // if (stewardFacade.getRelevantStewards(formBean.getPersonalIdentificator()) != null) { // bindingResult.addError(new FieldError("stewardCreate", "personalIdentificator", // formBean.getPersonalIdentificator(), false, // new String[]{"StewardCreationalDTOValidator.invalid.personalIdetificator"}, // null, "Personal identificator already exists.")); // model.addAttribute("personalIdentificator_error", true); // return "steward/new"; // } id = stewardFacade.createSteward(formBean); redirectAttributes.addFlashAttribute("alert_info", "Steward with id: " + id + " was created"); } catch (Exception ex) { model.addAttribute("alert_danger", "Steward was not created because of some unexpected error"); redirectAttributes.addFlashAttribute("alert_danger", "Steward was not created because of some unexpected error"); } request.getSession().setAttribute("authenticated", stewardFacade.getStewardWithPersonalIdentificator(formBean.getPersonalIdentificator())); return "redirect:" + uriBuilder.path("/steward").toUriString(); }
From source file:com.oak_yoga_studio.controller.AdminController.java
@RequestMapping(value = "/addFaculty", method = RequestMethod.POST) public String addFaculty(Faculty faculty, BindingResult result, HttpSession session, RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) { String view = "redirect:/viewFaculties"; if (!result.hasErrors()) { try {/*from w w w . jav a2 s.c om*/ faculty.setProfilePicture(file.getBytes()); } catch (IOException ex) { //Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex); } faculty.getCredential().setActive(false); faculty.setActive(false); facultyServcie.addFaculty(faculty); session.removeAttribute("credential"); flashAttr.addFlashAttribute("successful registered", "Faculty signed up succesfully. please log in to proceed"); // Customer c=(Customer) session.getAttribute("loggedCustomer"); } else { for (FieldError err : result.getFieldErrors()) { System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage()); } view = "addFaculty"; } return view; }
From source file:by.creepid.docgeneration.validation.ValidatorPhaseListener.java
private void validateValidatable(Validatable validatable, FacesContext facesContext) { Validator validator = (Validator) ContextHelper.getBean("firmRegValidator", Validator.class); WebUtils.clearFacesMessages(facesContext); Errors errors = new BindException(validatable, validatable.getClass().getSimpleName()); validator.validate(validatable, errors); for (Object error : errors.getAllErrors()) { FieldError fieldError = (FieldError) error; String smessage = fieldError.getDefaultMessage(); FacesMessage message = new FacesMessage(); message.setSeverity(FacesMessage.SEVERITY_ERROR); message.setSummary(smessage);/* ww w. j ava 2 s . c o m*/ message.setDetail(smessage); facesContext.addMessage(fieldError.getField(), message); } Iterator messages = facesContext.getMessages(); while (messages.hasNext()) { FacesMessage message = (FacesMessage) messages.next(); System.out.printf(message.getSummary() + "#" + message.getDetail()); } if (errors.hasErrors()) { facesContext.renderResponse(); } }
From source file:org.centralperf.controller.RunController.java
/** * Create a new Run//from w w w.ja v a 2s. co m * @param projectId ID of the project (from URI) * @param run The Run to create * @param result BindingResult to check if binding raised some errors * @param model Model prepared for the new project form view in case of errors * @return Redirection to the run detail page once the run has been created */ @RequestMapping(value = "/project/{projectId}/run/new", method = RequestMethod.POST) public String addRun(@PathVariable("projectId") Long projectId, @ModelAttribute("run") @Valid Run run, BindingResult result, Model model, RedirectAttributes redirectAttrs) { if (result.hasErrors()) { String errorMessage = "Error creating Run : "; for (FieldError error : result.getFieldErrors()) { errorMessage += "Field " + error.getField() + ", " + error.getDefaultMessage() + " ( " + error.getRejectedValue() + ")"; } redirectAttrs.addFlashAttribute("error", errorMessage); return "redirect:/project/" + projectId + "/detail"; } ScriptVersion scriptVersion = scriptVersionRepository.findOne(run.getScriptVersion().getId()); run.setScriptVersion(scriptVersion); runRepository.save(run); return "redirect:/project/" + projectId + "/run/" + run.getId() + "/detail"; }
From source file:org.gvnix.web.json.BindingResultSerializer.java
/** * Iterate over list items errors and load it on allErrorsMessages map. * <p/>/*from w w w.jav a 2 s . c om*/ * Delegates on {@link #loadObjectError(FieldError, String, Map)} * * @param fieldErrors * @param allErrorsMessages */ @SuppressWarnings("unchecked") private void loadListErrors(List<FieldError> fieldErrors, Map<String, Object> allErrorsMessages) { // Get prefix to unwrapping list: // "list[0].employedSince" String fieldNamePath = fieldErrors.get(0).getField(); // "list" String prefix = StringUtils.substringBefore(fieldNamePath, "["); String index; Map<String, Object> currentErrors; // Iterate over errors for (FieldError error : fieldErrors) { // get property path without list prefix // "[0].employedSince" fieldNamePath = StringUtils.substringAfter(error.getField(), prefix); // Get item's index: // "[0].employedSince" index = StringUtils.substringBefore(StringUtils.substringAfter(fieldNamePath, "["), "]"); // Remove index definition from field path // "employedSince" fieldNamePath = StringUtils.substringAfter(fieldNamePath, "."); // Check if this item already has errors registered currentErrors = (Map<String, Object>) allErrorsMessages.get(index); if (currentErrors == null) { // No errors registered: create map to contain this error currentErrors = new HashMap<String, Object>(); allErrorsMessages.put(index, currentErrors); } // Load error on item's map loadObjectError(error, fieldNamePath, currentErrors); } }