List of usage examples for org.springframework.validation FieldError getField
public String getField()
From source file:org.springframework.web.struts.SpringBindingActionForm.java
/** * Return an ActionMessages representation of this SpringBindingActionForm, * exposing all errors contained in the underlying Spring Errors object. * @see org.springframework.validation.Errors#getAllErrors() */// w ww. j a v a 2s. com private ActionMessages getActionMessages() { ActionMessages actionMessages = new ActionMessages(); Iterator it = this.errors.getAllErrors().iterator(); while (it.hasNext()) { ObjectError objectError = (ObjectError) it.next(); String effectiveMessageKey = findEffectiveMessageKey(objectError); if (effectiveMessageKey == null && !defaultActionMessageAvailable) { // Need to specify default code despite it not beign resolvable: // Struts 1.1 ActionMessage doesn't support default messages. effectiveMessageKey = objectError.getCode(); } ActionMessage message = (effectiveMessageKey != null) ? new ActionMessage(effectiveMessageKey, resolveArguments(objectError.getArguments())) : new ActionMessage(objectError.getDefaultMessage(), false); if (objectError instanceof FieldError) { FieldError fieldError = (FieldError) objectError; actionMessages.add(fieldError.getField(), message); } else { actionMessages.add(ActionMessages.GLOBAL_MESSAGE, message); } } if (logger.isDebugEnabled()) { logger.debug("Final ActionMessages used for binding: " + actionMessages); } return actionMessages; }
From source file:org.springframework.xd.dirt.server.container.ContainerServerApplication.java
private void handleFieldErrors(Exception e) { if (e.getCause() instanceof BindException) { BindException be = (BindException) e.getCause(); for (FieldError error : be.getFieldErrors()) { logger.error(String.format("the value '%s' is not allowed for property '%s'", error.getRejectedValue(), error.getField())); }//from ww w . ja va2 s . c o m } else { e.printStackTrace(); } System.exit(1); }
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 ww. j a v a 2 s . co m 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);/*from w ww.j a va 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 .j a v a 2s .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);/*w ww .ja v a 2s . c o m*/ 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 w w w.j a va2s . 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"; }