List of usage examples for org.springframework.validation BindingResult getAllErrors
List<ObjectError> getAllErrors();
From source file:org.springframework.springfaces.mvc.bind.ReverseDataBinder.java
/** * Perform the reverse bind on the <tt>dataBinder</tt> provided in the constructor. Note: Calling with method will * also trigger a <tt>bind</tt> operation on the <tt>dataBinder</tt>. This method returns {@link PropertyValues} * containing a name/value pairs for each property that can be bound. Property values are encoded as Strings using * the property editors bound to the original dataBinder. * @return property values that could be re-bound using the data binder * @throws IllegalStateException if the target object values cannot be bound *//*from w w w . j a v a 2 s .c o m*/ public PropertyValues reverseBind() { Assert.notNull(this.dataBinder.getTarget(), "ReverseDataBinder.reverseBind can only be used with a DataBinder that has a target object"); MutablePropertyValues rtn = new MutablePropertyValues(); BeanWrapper target = PropertyAccessorFactory.forBeanPropertyAccess(this.dataBinder.getTarget()); ConversionService conversionService = this.dataBinder.getConversionService(); if (conversionService != null) { target.setConversionService(conversionService); } PropertyDescriptor[] propertyDescriptors = target.getPropertyDescriptors(); BeanWrapper defaultValues = null; if (this.skipDefaultValues) { defaultValues = newDefaultTargetValues(this.dataBinder.getTarget()); } for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor property = propertyDescriptors[i]; String propertyName = PropertyAccessorUtils.canonicalPropertyName(property.getName()); Object propertyValue = target.getPropertyValue(propertyName); if (isSkippedProperty(property)) { continue; } if (!isMutableProperty(property)) { if (this.logger.isDebugEnabled()) { this.logger.debug("Ignoring '" + propertyName + "' due to missing read/write methods"); } continue; } if (defaultValues != null && ObjectUtils.nullSafeEquals(defaultValues.getPropertyValue(propertyName), propertyValue)) { if (this.logger.isDebugEnabled()) { this.logger.debug("Skipping '" + propertyName + "' as property contains default value"); } continue; } // Find a property editor PropertyEditorRegistrySupport propertyEditorRegistrySupport = null; if (target instanceof PropertyEditorRegistrySupport) { propertyEditorRegistrySupport = (PropertyEditorRegistrySupport) target; } PropertyEditor propertyEditor = findEditor(propertyName, propertyEditorRegistrySupport, target.getWrappedInstance(), target.getPropertyType(propertyName), target.getPropertyTypeDescriptor(propertyName)); // Convert and store the value String convertedPropertyValue = convertToStringUsingPropertyEditor(propertyValue, propertyEditor); if (convertedPropertyValue != null) { rtn.addPropertyValue(propertyName, convertedPropertyValue); } } this.dataBinder.bind(rtn); BindingResult bindingResult = this.dataBinder.getBindingResult(); if (bindingResult.hasErrors()) { throw new IllegalStateException("Unable to reverse bind from target '" + this.dataBinder.getObjectName() + "', the properties '" + rtn + "' will result in binding errors when re-bound " + bindingResult.getAllErrors()); } return rtn; }
From source file:pl.hycom.pip.messanger.controller.GreetingController.java
@PostMapping("/admin/greeting") public String addGreeting(@Valid Greeting greeting, BindingResult bindingResult, Model model) { try {/*from w ww . j a v a 2 s. co m*/ if (!greetingService.isValidLocale(greeting.getLocale())) { log.error("Not supported locale[" + greeting.getLocale() + "]"); addError(bindingResult, "greeting.locale.empty"); } if (bindingResult.hasErrors()) { prepareModel(model, greeting); log.error("Greeting validation errors: " + bindingResult.getAllErrors()); return VIEW_GREETINGS; } List<com.github.messenger4j.profile.Greeting> greetings = getGreetingsWithDefaultLocale(); com.github.messenger4j.profile.Greeting profileGreeting = new com.github.messenger4j.profile.Greeting( greeting.getText(), greeting.getLocale()); greetings.add(profileGreeting); profileClient.setupWelcomeMessages(greetings); log.info("Greeting text correctly updated"); } catch (MessengerApiException | MessengerIOException e) { log.error("Error during changing greeting message", e); addError(bindingResult, "unexpectedError"); prepareModel(model, greeting); model.addAttribute("errors", bindingResult.getFieldErrors()); return VIEW_GREETINGS; } return REDIRECT_ADMIN_GREETINGS; }
From source file:sample.ui.mvc.MessageController.java
@RequestMapping(method = RequestMethod.POST) public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("messages/form", "formErrors", result.getAllErrors()); }// w w w . j ava 2 s.co m message = this.messageRepository.save(message); redirect.addFlashAttribute("globalMessage", "Successfully created a new message"); logger.info("do click"); doClick(message); System.out.println(message); // message.setId(1l); return new ModelAndView("redirect:/{message.id}", "message.id", message.getId()); }
From source file:sample.web.ui.mvc.MessageController.java
@PostMapping // @Timed(value = "long_create", longTask = true) public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("messages/form", "formErrors", result.getAllErrors()); }// w w w . j a v a 2 s . c om message = this.messageRepository.save(message); redirect.addFlashAttribute("globalMessage", "Successfully created a new message"); return new ModelAndView("redirect:/{message.id}", "message.id", message.getId()); }
From source file:sg.ncl.DataController.java
@RequestMapping(value = { "/contribute", "/contribute/{id}" }, method = RequestMethod.POST) public String validateContributeData(@Valid @ModelAttribute("dataset") Dataset dataset, BindingResult bindingResult, Model model, @PathVariable Optional<String> id, HttpSession session) throws WebServiceRuntimeException { setContributor(dataset, session);//from w w w. ja v a2s. c om if (bindingResult.hasErrors()) { StringBuilder message = new StringBuilder(); message.append(ERRORS_STR); message.append(UL_TAG_START); for (ObjectError objectError : bindingResult.getAllErrors()) { FieldError fieldError = (FieldError) objectError; message.append(LI_START_TAG); switch (fieldError.getField()) { case "categoryId": message.append("category must be selected"); break; case "licenseId": message.append("license must be selected"); break; default: message.append(fieldError.getField()); message.append(" "); message.append(fieldError.getDefaultMessage()); } message.append(LI_END_TAG); } message.append(UL_END_TAG); model.addAttribute(MESSAGE_ATTRIBUTE, message.toString()); model.addAttribute(CATEGORIES, getDataCategories()); model.addAttribute(LICENSES, getDataLicenses()); if (id.isPresent()) { Dataset data = getDataset(id.get()); model.addAttribute("data", data); } model.addAttribute(EDITABLE_FLAG, true); return CONTRIBUTE_DATA_PAGE; } JSONObject dataObject = new JSONObject(); dataObject.put("name", dataset.getName()); dataObject.put("description", dataset.getDescription()); dataObject.put("contributorId", dataset.getContributorId()); dataObject.put("visibility", dataset.getVisibility()); dataObject.put("accessibility", dataset.getAccessibility()); dataObject.put("resources", new ArrayList()); dataObject.put("approvedUsers", new ArrayList()); dataObject.put("releasedDate", dataset.getReleasedDate()); dataObject.put("categoryId", dataset.getCategoryId()); dataObject.put("licenseId", dataset.getLicenseId()); dataObject.put("keywords", dataset.getKeywordList()); log.debug("DataObject: {}", dataObject.toString()); HttpEntity<String> request = createHttpEntityWithBody(dataObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = getResponseEntity(id, request); String dataResponseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(dataResponseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); checkExceptionState(dataset, model, exceptionState); return CONTRIBUTE_DATA_PAGE; } } catch (IOException e) { log.error("validateContributeData: {}", e.toString()); throw new WebServiceRuntimeException(e.getMessage()); } log.info("Dataset saved: {}", dataResponseBody); return REDIRECT_DATA; }
From source file:sg.ncl.DataController.java
@RequestMapping(value = "/public/{id}", method = RequestMethod.POST) public String checkPublicDataset(HttpSession session, Model model, @PathVariable String id, @Valid @ModelAttribute("puser") PublicUser puser, BindingResult bindingResult) { if (bindingResult.hasErrors()) { StringBuilder message = new StringBuilder(); message.append(ERRORS_STR);//w w w .j a v a 2s . co m message.append(UL_TAG_START); for (ObjectError objectError : bindingResult.getAllErrors()) { FieldError fieldError = (FieldError) objectError; message.append(LI_START_TAG); switch (fieldError.getField()) { case "fullName": message.append("You have to fill in your full name"); break; case "email": message.append("You have to fill in your email address"); break; case "jobTitle": message.append("You have to fill in your job title"); break; case "institution": message.append("You have to fill in your institution"); break; case "country": message.append("You have to fill in your country"); break; case "licenseAgreed": message.append("You have to agree to the licensing terms"); break; default: message.append(fieldError.getField()); message.append(" "); message.append(fieldError.getDefaultMessage()); } message.append(LI_END_TAG); } message.append(UL_END_TAG); model.addAttribute(MESSAGE_ATTRIBUTE, message); HttpEntity<String> dataRequest = createHttpEntityHeaderOnlyNoAuthHeader(); ResponseEntity dataResponse = restTemplate.exchange(properties.getPublicDataset(id), HttpMethod.GET, dataRequest, String.class); String dataResponseBody = dataResponse.getBody().toString(); JSONObject dataInfoObject = new JSONObject(dataResponseBody); Dataset dataset = extractDataInfo(dataInfoObject.toString()); model.addAttribute(DATASET, dataset); return "data_public_id"; } JSONObject puserObject = new JSONObject(); puserObject.put("fullName", puser.getFullName()); puserObject.put("email", puser.getEmail()); puserObject.put("jobTitle", puser.getJobTitle()); puserObject.put("institution", puser.getInstitution()); puserObject.put("country", puser.getCountry()); puserObject.put("licenseAgreed", puser.isLicenseAgreed()); HttpEntity<String> request = createHttpEntityWithBodyNoAuthHeader(puserObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getPublicDataUsers(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); log.info("Public user saved: {}", responseBody); JSONObject object = new JSONObject(responseBody); session.setAttribute(PUBLIC_USER_ID, object.getLong("id")); return REDIRECT_DATA + "/public/" + id + "/" + RESOURCES; }
From source file:sg.ncl.MainController.java
@RequestMapping(value = "/experiments/create", method = RequestMethod.POST) public String validateExperiment(@ModelAttribute("experimentForm") ExperimentForm experimentForm, BindingResult bindingResult, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors()) { log.info("Create experiment - form has errors"); for (ObjectError objectError : bindingResult.getAllErrors()) { FieldError fieldError = (FieldError) objectError; switch (fieldError.getField()) { case MAX_DURATION: redirectAttributes.addFlashAttribute(MESSAGE, MAX_DURATION_ERROR); break; default: redirectAttributes.addFlashAttribute(MESSAGE, "Form not filled up"); }/*from ww w. ja v a 2 s . c o m*/ } return REDIRECT_CREATE_EXPERIMENT; } if (!experimentForm.getMaxDuration().toString().matches("\\d+")) { redirectAttributes.addFlashAttribute(MESSAGE, MAX_DURATION_ERROR); return REDIRECT_CREATE_EXPERIMENT; } if (experimentForm.getName() == null || experimentForm.getName().isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Experiment Name cannot be empty"); return REDIRECT_CREATE_EXPERIMENT; } if (experimentForm.getDescription() == null || experimentForm.getDescription().isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Description cannot be empty"); return REDIRECT_CREATE_EXPERIMENT; } experimentForm.setScenarioContents(getScenarioContentsFromFile(experimentForm.getScenarioFileName())); JSONObject experimentObject = new JSONObject(); experimentObject.put(USER_ID, session.getAttribute("id").toString()); experimentObject.put(TEAM_ID, experimentForm.getTeamId()); experimentObject.put(TEAM_NAME, experimentForm.getTeamName()); experimentObject.put("name", experimentForm.getName().replaceAll("\\s+", "")); // truncate whitespaces and non-visible characters like \n experimentObject.put(DESCRIPTION, experimentForm.getDescription()); experimentObject.put("nsFile", "file"); experimentObject.put("nsFileContent", experimentForm.getNsFileContent()); experimentObject.put("idleSwap", "240"); experimentObject.put(MAX_DURATION, experimentForm.getMaxDuration()); log.info("Calling service to create experiment"); HttpEntity<String> request = createHttpEntityWithBody(experimentObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case NS_FILE_PARSE_EXCEPTION: log.warn("Ns file error"); redirectAttributes.addFlashAttribute(MESSAGE, "There is an error when parsing the NS File."); break; case EXPERIMENT_NAME_ALREADY_EXISTS_EXCEPTION: log.warn("Exp name already exists"); redirectAttributes.addFlashAttribute(MESSAGE, "Experiment name already exists."); break; default: log.warn("Exp service or adapter fail"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } log.info("Experiment {} created", experimentForm); return REDIRECT_CREATE_EXPERIMENT; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } // // TODO Uploaded function for network configuration and optional dataset // if (!networkFile.isEmpty()) { // try { // String networkFileName = getSessionIdOfLoggedInUser(session) + "-networkconfig-" + networkFile.getOriginalFilename(); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + networkFileName))); // FileCopyUtils.copy(networkFile.getInputStream(), stream); // stream.close(); // redirectAttributes.addFlashAttribute(MESSAGE, // "You successfully uploaded " + networkFile.getOriginalFilename() + "!"); // // remember network file name here // } // catch (Exception e) { // redirectAttributes.addFlashAttribute(MESSAGE, // "You failed to upload " + networkFile.getOriginalFilename() + " => " + e.getMessage()); // return REDIRECT_CREATE_EXPERIMENT; // } // } // // if (!dataFile.isEmpty()) { // try { // String dataFileName = getSessionIdOfLoggedInUser(session) + "-data-" + dataFile.getOriginalFilename(); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + dataFileName))); // FileCopyUtils.copy(dataFile.getInputStream(), stream); // stream.close(); // redirectAttributes.addFlashAttribute("message2", // "You successfully uploaded " + dataFile.getOriginalFilename() + "!"); // // remember data file name here // } // catch (Exception e) { // redirectAttributes.addFlashAttribute("message2", // "You failed to upload " + dataFile.getOriginalFilename() + " => " + e.getMessage()); // } // } // // // add current experiment to experiment manager // experimentManager.addExperiment(getSessionIdOfLoggedInUser(session), experiment); // // increase exp count to be display on Teams page // teamManager.incrementExperimentCount(experiment.getTeamId()); return REDIRECT_EXPERIMENTS; }
From source file:sg.ncl.MainController.java
private String buildErrorMessage(BindingResult binding) { StringBuilder message = new StringBuilder(); message.append(TAG_ERRORS);/*from ww w.j a v a 2s. com*/ message.append(TAG_UL); for (ObjectError objectError : binding.getAllErrors()) { FieldError fieldError = (FieldError) objectError; message.append(TAG_LI); switch (fieldError.getField()) { case ORGANISATION_TYPE: message.append("Organisation Type "); message.append(fieldError.getDefaultMessage()); break; case ORGANISATION_NAME: message.append("Organisation Name "); message.append(fieldError.getDefaultMessage()); break; case KEY_PROJECT_NAME: message.append("Project Name "); message.append(fieldError.getDefaultMessage()); break; case KEY_OWNER: message.append("Owner "); message.append(fieldError.getDefaultMessage()); break; case KEY_DATE_CREATED: message.append("Date Created "); message.append(fieldError.getDefaultMessage()); break; case "month": message.append("Month "); message.append(fieldError.getDefaultMessage()); break; default: message.append(fieldError.getField()); message.append(TAG_SPACE); message.append(fieldError.getDefaultMessage()); } message.append(TAG_LI_CLOSE); } message.append(TAG_UL_CLOSE); return message.toString(); }
From source file:sg.ncl.MainController.java
@PostMapping("/admin/statistics") public String adminUsageStatisticsQuery(@Valid @ModelAttribute("query") ProjectUsageQuery query, BindingResult result, RedirectAttributes attributes, HttpSession session) { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; }//from ww w. ja v a2s .c o m List<ProjectDetails> newProjects = new ArrayList<>(); List<ProjectDetails> activeProjects = new ArrayList<>(); List<ProjectDetails> inactiveProjects = new ArrayList<>(); List<ProjectDetails> stoppedProjects = new ArrayList<>(); List<String> months = new ArrayList<>(); Map<String, MonthlyUtilization> utilizationMap = new HashMap<>(); Map<String, Integer> statsCategoryMap = new HashMap<>(); Map<String, Integer> statsAcademicMap = new HashMap<>(); int totalCategoryUsage = 0; int totalAcademicUsage = 0; if (result.hasErrors()) { StringBuilder message = new StringBuilder(); message.append(TAG_ERRORS); message.append(TAG_UL); for (ObjectError objectError : result.getAllErrors()) { FieldError fieldError = (FieldError) objectError; message.append(TAG_LI); message.append(fieldError.getField()); message.append(TAG_SPACE); message.append(fieldError.getDefaultMessage()); message.append(TAG_LI_CLOSE); } message.append(TAG_UL_CLOSE); attributes.addFlashAttribute(MESSAGE, message.toString()); } else { DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMM-yyyy").toFormatter(); YearMonth m_s = YearMonth.parse(query.getStart(), formatter); YearMonth m_e = YearMonth.parse(query.getEnd(), formatter); YearMonth counter = m_s; while (!counter.isAfter(m_e)) { String monthYear = counter.format(formatter); utilizationMap.put(monthYear, new MonthlyUtilization(monthYear)); months.add(monthYear); counter = counter.plusMonths(1); } List<ProjectDetails> projectsList = getProjects(); for (ProjectDetails project : projectsList) { // compute active and inactive projects differentiateProjects(newProjects, activeProjects, inactiveProjects, stoppedProjects, m_s, m_e, project); // monthly utilisation computeMonthlyUtilisation(utilizationMap, formatter, m_s, m_e, project); // usage statistics by category totalCategoryUsage += getCategoryUsage(statsCategoryMap, m_s, m_e, project); // usage statistics by academic institutes totalAcademicUsage += getAcademicUsage(statsAcademicMap, m_s, m_e, project); } } attributes.addFlashAttribute(KEY_QUERY, query); attributes.addFlashAttribute("newProjects", newProjects); attributes.addFlashAttribute("activeProjects", activeProjects); attributes.addFlashAttribute("inactiveProjects", inactiveProjects); attributes.addFlashAttribute("stoppedProjects", stoppedProjects); attributes.addFlashAttribute("months", months); attributes.addFlashAttribute("utilization", utilizationMap); attributes.addFlashAttribute("statsCategory", statsCategoryMap); attributes.addFlashAttribute("totalCategoryUsage", totalCategoryUsage); attributes.addFlashAttribute("statsAcademic", statsAcademicMap); attributes.addFlashAttribute("totalAcademicUsage", totalAcademicUsage); return "redirect:/admin/statistics"; }
From source file:ubc.pavlab.aspiredb.server.controller.FileUploadController.java
@RequestMapping(value = "/upload_action.html", method = RequestMethod.POST) public @ResponseBody String uploadFile(FileUploadBean uploadItem, BindingResult result) { ExtJSFormResult extjsFormResult = new ExtJSFormResult(); if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { log.error("Error: " + error.getCode() + " - " + error.getDefaultMessage()); }/*from www. ja v a 2 s. c om*/ // set extjs return - error extjsFormResult.setSuccess(false); return extjsFormResult.toString(); } if (uploadItem.getFile().getSize() > 0) { File serverFile = null; try { serverFile = saveFileFromInputStream(uploadItem.getFile().getInputStream()); // set extjs return - sucsess extjsFormResult.setSuccess(true); extjsFormResult .setData("{ \"filePath\" : \"" + serverFile.getAbsolutePath().replace('\\', '/') + "\" } "); extjsFormResult.setMessage("success"); log.info("Successfully saved " + uploadItem.getFile().getOriginalFilename() + " to " + serverFile.getAbsolutePath()); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); // set extjs return - sucsess extjsFormResult.setSuccess(false); extjsFormResult.setMessage(e.getLocalizedMessage()); } } return extjsFormResult.toString(); }