List of usage examples for org.springframework.validation FieldError getDefaultMessage
@Override
@Nullable
public String getDefaultMessage()
From source file:fi.hsl.parkandride.front.ExceptionHandlers.java
@ExceptionHandler(BindException.class) public ResponseEntity<Map<String, Object>> bindException(HttpServletRequest request, BindException ex) { List<Violation> violations = new ArrayList<>(); for (FieldError fieldError : ex.getFieldErrors()) { violations.add(/*from w ww . ja va 2 s .c o m*/ new Violation(fieldError.getCode(), fieldError.getField(), fieldError.getDefaultMessage())); } return handleError(request, BAD_REQUEST, ex, "Invalid request parameters", violations); }
From source file:gov.nih.nci.cabig.caaers.web.fields.InputFieldTest.java
public void testErrorWhenRequiredFieldIsNotPresent() throws Exception { bean.setName(null);/*from w ww .j a v a 2s .c om*/ field.setRequired(true); field.validate(wrappedBean, errors); assertEquals("Wrong number of errors", 1, errors.getErrorCount()); assertEquals("Wrong number of field errors", 1, errors.getFieldErrorCount()); FieldError actualError = errors.getFieldError("name"); assertNotNull("Error is on wrong property", actualError); assertEquals("Wrong key for error", "REQUIRED", actualError.getCode()); assertEquals("Wrong default message for error", "<b>Missing:</b> "Nomen"", actualError.getDefaultMessage()); }
From source file:gt.org.ms.api.global.GlobalExceptionHandler.java
@Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors(); List<ValidationError> errors = new ArrayList<ValidationError>(); for (FieldError fieldError : fieldErrors) { errors.add(//from w w w . ja v a2 s . c om new ValidationError(fieldError.getField().replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase(), translateValidationMessage(fieldError.getDefaultMessage()))); } ValidationException ve = new ValidationException(errors); LOG.info("ValidationException", ve); return handleException(ve); }
From source file:org.egov.api.controller.RestEventController.java
@PostMapping(path = "/event/interested", produces = APPLICATION_JSON_VALUE) public ResponseEntity<String> saveUserEvent(@Valid @RequestBody UserEventRequest userEventRequest, BindingResult errors) {/*from w w w .ja va 2s .c o m*/ ApiResponse res = ApiResponse.newInstance(); if (errors.hasErrors()) { String errorMessage = EMPTY; for (FieldError fieldError : errors.getFieldErrors()) errorMessage = errorMessage.concat( fieldError.getField().concat(" ").concat(fieldError.getDefaultMessage()).concat(" <br>")); return res.error(errorMessage); } UserEvent userEvent = userEventService.saveUserEvent(userEventRequest.getUserid(), userEventRequest.getEventid()); if (userEvent == null) return res.error(getMessage("user.event.already.exists")); else { Long interestedCount = userEventService.countUsereventByEventId(userEvent.getEvent().getId()); return res.setDataAdapter(new InterestedCountAdapter()).success(interestedCount); } }
From source file:org.egov.api.controller.RestPushBoxController.java
@PostMapping(path = UPDATE_USER_TOKEN, consumes = APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<String> updateToken(@Valid @RequestBody UserTokenRequest userTokenRequest, BindingResult errors) {/*from w w w. j av a 2s . c o m*/ ApiResponse res = ApiResponse.newInstance(); if (errors.hasErrors()) { String errorMessage = EMPTY; for (FieldError fieldError : errors.getFieldErrors()) errorMessage = errorMessage.concat( fieldError.getField().concat(" ").concat(fieldError.getDefaultMessage()).concat(" <br>")); return res.error(errorMessage); } UserFcmDevice responseObject = notificationService.saveUserDevice(userTokenRequest); return res.setDataAdapter(new UserDeviceAdapter()).success(responseObject, getMessage("msg.userdevice.update.success")); }
From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "") public void validateEnterAccountDetailsStep(ValidationContext context) { MessageContext messageContext = context.getMessageContext(); Errors errors = validator.checkConstraints(this); // handle data binding errors that may of occurred if (messageContext.hasErrorMessages()) { Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() { @Override/*w ww . j a v a 2 s. com*/ public boolean test(@SuppressWarnings("unused") Message message) { return true; } }); messageContext.clearMessages(); for (Message message : errorMessages) { handleDataMappingError(errors, message); } } if (this.glimApplicable) { int index = 0; int selectedCount = 0; for (Boolean clientSelected : this.clientSelectForGroup) { if (clientSelected != null && clientSelected.booleanValue()) { Number clientAmount = this.clientAmount[index]; if (clientAmount == null || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage); } if (clientAmount != null) { BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid", new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid", new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts }); } } // check error message of loan purpose for each client when its mandatory.. Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) { errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid", new Object[] { index + 1 }, "Please specify loan purpose."); this.clientLoanPurposeId[index] = 0; } else { // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over. if (clientLoanPurposeId == null) { this.clientLoanPurposeId[index] = 0; } } selectedCount++; } else { Number clientAmount = this.clientAmount[index]; Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (clientAmount != null || clientLoanPurposeId != null) { String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan."; rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage); } } index++; } if (selectedCount < 2) { String defaultErrorMessage = "Not enough clients for group loan."; rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage); } } if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; if (glimApplicable) { defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product."; rejectGlimTotalAmountField(errors, defaultErrorMessage); } else { rejectAmountField(errors, defaultErrorMessage); } } if (this.amount != null) { BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsAfterDecimal.invalid", new Object[] { this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsBeforeDecimal.invalid", new Object[] { this.digitsBeforeDecimalForMonetaryAmounts }); } } if (this.interestRate == null || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) { String defaultErrorMessage = "Please specify valid Interest rate."; rejectInterestRateField(errors, defaultErrorMessage); } if (this.interestRate != null) { BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros(); int places = interestRateAsDecimal.scale(); if (places > this.digitsAfterDecimalForInterest) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsAfterDecimalForInterest.invalid", new Object[] { this.digitsAfterDecimalForInterest }); } int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForInterest) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid", new Object[] { this.digitsBeforeDecimalForInterest }); } } if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments, this.minNumberOfInstallments, this.maxNumberOfInstallments)) { String defaultErrorMessage = "Please specify valid number of installments."; rejectNumberOfInstallmentsField(errors, defaultErrorMessage); } if (this.graceDuration == null || this.graceDuration.intValue() < 0) { if (!errors.hasFieldErrors("graceDuration")) { String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than " + numberOfInstallments.intValue() + "."; rejectGraceDurationField(errors, defaultErrorMessage); } } else { if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) { String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid", defaultErrorMessage); } if (this.numberOfInstallments != null && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) { String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid", defaultErrorMessage); } } if (dateValidator == null) { dateValidator = new DateValidator(); } if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM, this.disbursementDateYY)) { String defaultErrorMessage = "Please specify valid disbursal date."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", "loanAccountFormBean.DisbursalDate.invalid", ""); } else { LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(), disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate(); org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors(); if (this.redoLoanAccount) { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId); } else { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanDisbursementDate(validDate, customerId, productId); } for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) { String defaultErrorMessage = "The disbursal date is invalid."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(), entry.getArgs().get(0)); } } if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) { errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid", "Please specify source of funds."); } if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) { errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid", "Please specify required external id."); } if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) { errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid", "Please specify loan purpose."); } validateAdministrativeAndAdditionalFees(errors); if (this.repaymentScheduleIndependentOfCustomerMeeting) { if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) { errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid", "Please specify a valid recurring frequency for repayment day."); } if (this.weekly) { if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } else if (this.monthly) { if (this.monthlyDayOfMonthOptionSelected) { if (isInvalidDayOfMonthEntered()) { errors.rejectValue("repaymentDayOfMonth", "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid", "Please select a day of the month for repayment day."); } } else if (this.monthlyWeekOfMonthOptionSelected) { if (isInvalidWeekOfMonthSelection()) { errors.rejectValue("repaymentWeekOfMonth", "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid", "Please select a week of the month for repayment day."); } if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } } if (this.variableInstallmentsAllowed) { if (this.selectedFeeId != null) { for (Number feeId : this.selectedFeeId) { if (feeId != null) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } } int defaultFeeIndex = 0; if (this.defaultFeeId != null) { for (Number feeId : this.defaultFeeId) { if (feeId != null) { Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex]; if (feeSelectedForRemoval == null || !feeSelectedForRemoval) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } defaultFeeIndex++; } } } } if (errors.hasErrors()) { for (FieldError fieldError : errors.getFieldErrors()) { MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField()) .codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage()) .args(fieldError.getArguments()); messageContext.addMessage(builder.build()); } } }
From source file:org.opentestsystem.delivery.testreg.service.impl.ExternalStudentServiceImpl.java
private String validateStudent(Student student, StudentSecurity studentSecurity, String stateCode) { if (student.getStateAbbreviation().compareTo(stateCode) != 0) throw new UnauthorizedUserException("Attempted to modify student in state: " + student.getStateAbbreviation() + " endpoint received " + stateCode); String error = ""; List<FieldError> errors = fileUploadSecurityValidator.validateStudent(student, studentSecurity); if (errors.size() != 0) { for (FieldError fieldError : errors) { error += fieldError.getDefaultMessage() + "\n"; }//from w ww .j ava 2 s . c om } return error; }
From source file:org.opentestsystem.shared.web.AbstractRestController.java
/** * Catch validation exception and return customized error message */// w w w . j a v a 2 s. c o m @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public ResponseError handleMethodArgumentNotValidException(final MethodArgumentNotValidException except) { final List<FieldError> errors = except.getBindingResult().getFieldErrors(); final Map<String, List<String>> errorsByField = new TreeMap<String, List<String>>(); for (final FieldError error : errors) { if (errorsByField.get(error.getField()) == null) { errorsByField.put(error.getField(), new ArrayList<String>()); } final List<String> messageList = errorsByField.get(error.getField()); String rejectedValue = ""; if (error.getRejectedValue() == null) { rejectedValue = "null"; } else { rejectedValue = error.getRejectedValue().toString(); } final List<String> args = Lists.newArrayList(error.getField(), rejectedValue); if (error.getArguments() != null) { final Iterable<String> argsToAdd = Iterables.transform(Arrays.asList(error.getArguments()), TO_STRING_FUNCTION); args.addAll(Lists.newArrayList(argsToAdd)); } messageList.add(getLocalizedMessage(error.getDefaultMessage(), args.toArray(new String[args.size()]))); } // sort error messages for (final Map.Entry<String, List<String>> entry : errorsByField.entrySet()) { Collections.sort(entry.getValue()); } return new ResponseError(errorsByField); }
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);/* ww w. ja va2s.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);//from www.j a v a 2 s.c o 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; }