List of usage examples for org.springframework.validation FieldError getField
public String getField()
From source file:com.sra.biotech.submittool.persistence.client.SubmitExceptionHandler.java
@ExceptionHandler({ InvalidRequestException.class }) protected ResponseEntity<Object> handleInvalidRequest(RuntimeException e, WebRequest request) { InvalidRequestException ire = (InvalidRequestException) e; List<FieldErrorResource> fieldErrorResources = new ArrayList<>(); List<FieldError> fieldErrors = ire.getErrors().getFieldErrors(); for (FieldError fieldError : fieldErrors) { FieldErrorResource fieldErrorResource = new FieldErrorResource(); fieldErrorResource.setResource(fieldError.getObjectName()); fieldErrorResource.setField(fieldError.getField()); fieldErrorResource.setCode(fieldError.getCode()); fieldErrorResource.setMessage(fieldError.getDefaultMessage()); fieldErrorResources.add(fieldErrorResource); }/*from w w w.ja v a2 s. com*/ ErrorResource error = new ErrorResource("InvalidRequest", ire.getMessage()); error.setFieldErrors(fieldErrorResources); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return handleExceptionInternal(e, error, headers, HttpStatus.UNPROCESSABLE_ENTITY, request); }
From source file:org.fornax.cartridges.sculptor.framework.web.errorhandling.ErrorBindingPhaseListener.java
/** * Pull out the Spring Errors object from context and convert each error into * a FacesMessage./*w w w .j a va2s . c om*/ * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent) */ public void afterPhase(PhaseEvent event) { FacesContext context = event.getFacesContext(); RequestContext requestContext = RequestContextHolder.getRequestContext(); if (requestContext == null) return; Map<?, ?> model; try { model = requestContext.getFlashScope().asMap(); } catch (IllegalStateException e) { return; } Locale locale = context.getExternalContext().getRequestLocale(); for (Iterator<?> iter = model.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); Object value = model.get(key); // If we have an Errors object and it is not the duplicate currentFormObject // one (always provided for compatibility with single object forms) if (value instanceof Errors && !key.endsWith("currentFormObject")) { Errors errors = (Errors) value; for (Iterator<?> eter = errors.getAllErrors().iterator(); eter.hasNext();) { ObjectError error = (ObjectError) eter.next(); String summary = null; try { ResourceBundle bundle = ResourceBundle.getBundle("i18n.messages", context.getViewRoot().getLocale()); summary = bundle.getString(error.getCode()); /* another way of getting the error code resolved */ /* it might be better to use this one */ /*FacesContext fc = FacesContext.getCurrentInstance(); ELContext elc = fc.getELContext(); ExpressionFactory ef = fc.getApplication().getExpressionFactory(); ValueExpression ve = ef.createValueExpression(elc, "#{msg}", PropertyResourceBundle.class); PropertyResourceBundle msg = (PropertyResourceBundle) ve.getValue(elc); if (msg != null) { summary = msg.getString(error.getCode()); }*/ summary = MessageFormat.format(summary, error.getArguments()); // if it's a field error we prepend the name of the field to the message if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; summary = fieldError.getField() + " - " + summary; } } catch (MissingResourceException mrexception) { summary = error.getDefaultMessage(); // try to translate the message if (messageSource != null) { summary = messageSource.getMessage(error, locale); } if (summary != null) { summary = MessageFormat.format(summary, error.getArguments()); } } if (summary != null) { String detail = summary; FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail); context.addMessage(null, message); } } } } }
From source file:com.google.ie.common.validation.IdeaValidator.java
@Override public void validate(Object target, Errors errors) { Idea idea = (Idea) target;/*from w w w . j a v a 2 s . co m*/ ValidationUtils.rejectIfEmptyOrWhitespace(errors, TITLE, IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD); ValidationUtils.rejectIfEmptyOrWhitespace(errors, DESCRIPTION, IdeaExchangeErrorCodes.FIELD_REQUIRED, IdeaExchangeConstants.Messages.REQUIRED_FIELD); if (!idea.isIdeaRightsGivenUp()) { errors.rejectValue(IDEA_RIGHTS_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE, IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); log.warn("Validation Error : " + IDEA_RIGHTS_GIVEN_UP + " -: " + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); } if (!idea.isIpGivenUp()) { errors.rejectValue(IP_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE, IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); log.warn("Validation Error : " + IP_GIVEN_UP + " -: " + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE); } if (!StringUtils.isBlank(idea.getTitle()) && idea.getTitle().trim().length() > LENGTH_500) { errors.rejectValue(TITLE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + TITLE + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getDescription()) && idea.getDescription().trim().length() > LENGTH_3000) { errors.rejectValue(DESCRIPTION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + DESCRIPTION + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getIdeaSummary()) && idea.getIdeaSummary().trim().length() > LENGTH_3000) { errors.rejectValue(IDEA_SUMMARY, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + IDEA_SUMMARY + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getMonetization()) && idea.getMonetization().trim().length() > LENGTH_500) { errors.rejectValue(MONETIZATION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + MONETIZATION + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getTargetAudience()) && idea.getTargetAudience().trim().length() > LENGTH_500) { errors.rejectValue(TARGET_AUDIENCE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + TARGET_AUDIENCE + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (!StringUtils.isBlank(idea.getCompetition()) && idea.getCompetition().trim().length() > LENGTH_500) { errors.rejectValue(COMPETITION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT, IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); log.warn("Validation Error : " + COMPETITION + " -: " + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE); } if (idea.getTags() != null && idea.getTags().length() > ZERO) { ValidationUtils.invokeValidator(stringValidatorForTagTitle, idea.getTags(), errors); } if (log.isDebugEnabled()) { if (errors.hasErrors()) { log.debug("Validator found " + errors.getErrorCount() + " errors"); for (Iterator<FieldError> iterator = errors.getFieldErrors().iterator(); iterator.hasNext();) { FieldError fieldError = iterator.next(); log.debug("Error found in field: " + fieldError.getField() + " Message :" + fieldError.getDefaultMessage()); } } else { log.debug("Validator found no errors"); } } }
From source file:com.springsource.greenhouse.signup.SignupController.java
private List<Map<String, String>> getErrorsMap(BindingResult formBinding) { List<FieldError> fieldErrors = formBinding.getFieldErrors(); List<Map<String, String>> errors = new ArrayList<Map<String, String>>(fieldErrors.size()); for (FieldError fieldError : fieldErrors) { Map<String, String> fieldErrorMap = new HashMap<String, String>(); fieldErrorMap.put("field", fieldError.getField()); fieldErrorMap.put("code", fieldError.getCode()); fieldErrorMap.put("message", fieldError.getDefaultMessage()); errors.add(fieldErrorMap);/*from ww w. j av a 2 s. c o m*/ } return errors; }
From source file:org.codeqinvest.web.project.CreateProjectController.java
/** * This methods handles the submitted form for creating a new project. *///ww w . j ava 2s. co m @RequestMapping(value = "/create", method = RequestMethod.POST) ModelAndView create(@ModelAttribute Project project, BindingResult bindingResult, @ModelAttribute("retrievedSonarProjectsAsJson") String sonarProjects, Model model) { projectConnectionsValidator.validate(project, bindingResult); if (bindingResult.hasErrors()) { log.info("Rejected creation of project due {} validation errors", bindingResult.getErrorCount()); if (log.isDebugEnabled()) { for (FieldError fieldError : bindingResult.getFieldErrors()) { log.debug("Field {} has following error: {}", fieldError.getField(), fieldError.getCode()); } } addDeserializedSonarProjectsToModel(sonarProjects, model); model.addAttribute("fieldErrors", bindingResult.getFieldErrors()); return new ModelAndView("createProject"); } // this little hack is necessary until a better way for binding the value from the form is found CodeChangeSettings codeChangeSettings = project.getCodeChangeSettings(); if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) { codeChangeSettings.setNumberOfCommits(codeChangeSettings.getDays()); codeChangeSettings.setDays(null); } Project addedProject = projectRepository.save(project); analyzerScheduler.scheduleAnalyzer(addedProject); log.info("Created project {} and scheduled its quality analysis", project.getName()); RedirectView redirect = new RedirectView("/projects/" + addedProject.getId()); redirect.setExposeModelAttributes(false); return new ModelAndView(redirect); }
From source file:cz.muni.fi.mvc.controllers.DestinationController.java
/** * Creates a new Destination//from www. j a v a 2 s . co m * @param model display data * @return jsp page */ @RequestMapping(method = RequestMethod.POST, value = "/create") public String create(@Valid @ModelAttribute("destinationCreate") DestinationCreationalDTO formBean, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) { 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 "destination/new"; } try { if (destinationFacade.getDestinationWithLocation(formBean.getLocation()) == null) { bindingResult.addError(new FieldError("destinationCreate", "location", "Destination was not created because it already exists.")); model.addAttribute("location_error", true); return "destination/new"; } Long id = destinationFacade.createDestination(formBean); redirectAttributes.addFlashAttribute("alert_info", "Destination with id: " + id + " was created"); } catch (Exception ex) { model.addAttribute("alert_danger", "Destination was not created because of some unexpected error"); redirectAttributes.addFlashAttribute("alert_danger", "Destination was not created because it already exists."); } return "redirect:" + uriBuilder.path("/destination").toUriString(); }
From source file:cz.muni.fi.pa165.mvc.controllers.GameController.java
@RequestMapping(value = "/create", method = RequestMethod.POST) public String create(@Valid @ModelAttribute("playerCreate") GameCreateDTO formBean, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) { log.debug("create(playerCreate={})", formBean); //in case of validation error forward back to the the form if (bindingResult.hasErrors()) { log.debug("some errror"); for (ObjectError ge : bindingResult.getGlobalErrors()) { log.trace("ObjectError: {}", ge); }//from ww w . ja va2s . co m for (FieldError fe : bindingResult.getFieldErrors()) { model.addAttribute(fe.getField() + "_error", true); log.trace("FieldError: {}", fe); } return "game/new"; } //create game if (formBean.getGuestTeam().equals(formBean.getHomeTeam())) { redirectAttributes.addFlashAttribute("alert_warning", "Game creation failed - two same teams were selected!"); return "redirect:" + uriBuilder.path("/game/list").build().encode().toUriString(); } Long id = gameFacade.create(formBean); //report success redirectAttributes.addFlashAttribute("alert_success", "Match " + id + " was created"); return "redirect:" + uriBuilder.path("/game/list").buildAndExpand(id).encode().toUriString(); }
From source file:cz.muni.fi.mvc.controllers.DestinationController.java
/** * Updates destination/*from w w w. j a v a 2 s . c om*/ * * @param id, modelAttribute, bindingResult, model, redirectAttributes, uriBuilder * @return JSP page */ @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) public String updateDestination(@PathVariable("id") long id, @Valid @ModelAttribute("destination") UpdateDestinationLocationDTO updatedDestination, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) { 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 "destination/edit"; } if ((updatedDestination.getLocation()).equals("")) { redirectAttributes.addFlashAttribute("alert_danger", "Location of destination is empty"); return "redirect:" + uriBuilder.path("/destination/edit/{id}").buildAndExpand(id).encode().toUriString(); } try { destinationFacade.updateDestinationLocation(updatedDestination); } catch (Exception ex) { redirectAttributes.addFlashAttribute("alert_danger", "Destination " + id + " wasn't updated because location already exists"); return "redirect:" + uriBuilder.path("/destination/edit/{id}").buildAndExpand(id).encode().toUriString(); } redirectAttributes.addFlashAttribute("alert_success", "Destination " + id + " was updated"); return "redirect:" + uriBuilder.path("/destination").toUriString(); }
From source file:cz.muni.fi.pa165.mvc.controllers.GameController.java
@RequestMapping(value = "/edit", method = RequestMethod.POST) public String edit(@Valid @ModelAttribute("gameEdit") GameCreateDTO formBean, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) { log.debug("edit(gameEdit={})", formBean); //in case of validation error forward back to the the form if (bindingResult.hasErrors()) { log.debug("some errror"); for (ObjectError ge : bindingResult.getGlobalErrors()) { log.trace("ObjectError: {}", ge); }/*from w w w . j a v a 2 s . c o m*/ for (FieldError fe : bindingResult.getFieldErrors()) { model.addAttribute(fe.getField() + "_error", true); log.trace("FieldError: {}", fe); } return "game/edit"; } if (formBean.getGuestTeam().equals(formBean.getHomeTeam())) { redirectAttributes.addFlashAttribute("alert_warning", "Game editing failed - two same teams were selected!"); return "redirect:" + uriBuilder.path("/game/list").build().encode().toUriString(); } GameDTO g = gameFacade.findById(formBean.getId()); g.setDateOfGame(formBean.getDateOfGame()); g.setGuestTeam(teamFacade.getTeamById(formBean.getGuestTeam())); g.setHomeTeam(teamFacade.getTeamById(formBean.getHomeTeam())); gameFacade.update(g); //report success redirectAttributes.addFlashAttribute("alert_success", "Player was edited"); return "redirect:" + uriBuilder.path("/game/list").toUriString(); }
From source file:cz.muni.fi.dndtroopsweb.controllers.TroopController.java
/** * Changes mission based on form for chosen troop * * @param formBean troop to be modified//from w w w . j a v a 2s . co m * @return details of modified troop */ @RequestMapping(value = "/job/{id}", method = RequestMethod.POST) public String job(@Valid @ModelAttribute("hero") TroopDTO formBean, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) { log.debug("update mission(troop={})", formBean); //in case of validation error forward back to the the form if (bindingResult.hasErrors()) { for (ObjectError ge : bindingResult.getGlobalErrors()) { log.trace("ObjectError: {}", ge); } for (FieldError fe : bindingResult.getFieldErrors()) { model.addAttribute(fe.getField() + "_error", true); log.trace("FieldError: {}", fe); } return "troop/mission"; } troopFacade.changeMission(formBean.getId(), formBean.getMission()); Long id = formBean.getId(); redirectAttributes.addFlashAttribute("alert_success", "Mission updated"); return "redirect:" + uriBuilder.path("/troop/details/{id}").buildAndExpand(id).encode().toUriString(); }