List of usage examples for org.springframework.validation Errors getFieldErrors
List<FieldError> getFieldErrors();
From source file:alfio.util.Validator.java
public static ValidationResult evaluateValidationResult(Errors errors) { if (errors.hasFieldErrors()) { return ValidationResult.failed(errors.getFieldErrors().stream() .map(ValidationResult.ErrorDescriptor::fromFieldError).collect(Collectors.toList())); }//from w w w. j av a 2 s.c om return ValidationResult.success(); }
From source file:de.extra.client.core.util.impl.ExtraValidator.java
private String convertToString(final Errors errors) { final List<FieldError> fieldErrors = errors.getFieldErrors(); final StringBuilder stringBuilder = new StringBuilder(fieldErrors.size() + " Konfigurationsfehler: "); final String sep = ";"; for (final FieldError fieldError : fieldErrors) { stringBuilder.append(fieldError.getObjectName()); stringBuilder.append(".").append(fieldError.getField()); stringBuilder.append(" ").append(fieldError.getDefaultMessage()); stringBuilder.append(sep);/* www. java 2s . c om*/ } return stringBuilder.toString(); }
From source file:gex.jaxrs.provider.support.SpringErrorsExtractor.java
public List<String> extractError(Errors errors, MessageSource messageSource) { notNull(errors, "The errors can not be null"); notNull(messageSource, "The messageSource can not be null"); return errors.getFieldErrors().stream().map(fieldError -> { return of(fieldError.getCodes()).map(code -> { log.debug("Searching code: '{}' with arguments '{}' and locale '{}'", code, fieldError.getArguments(), getLocale()); return messageSource.getMessage(code, fieldError.getArguments(), "", getLocale()); }).filter(StringUtils::hasText).findFirst().orElseGet(() -> { log.debug("Searching code: '{}' with arguments '{}', defaultMessage '{}' and locale '{}'", fieldError.getCode(), fieldError.getArguments(), fieldError.getDefaultMessage(), getLocale());/* www.j a v a 2 s . c o m*/ return messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), fieldError.getDefaultMessage(), getLocale()); }); }).collect(toList()); }
From source file:it.f2informatica.core.validator.utils.ValidationResponseHandlerImpl.java
@Override public ValidationResponse validationFail(Errors errors, Locale locale) { ValidationResponse validationResponse = new ValidationResponse(); validationResponse.setStatus(ValidationStatus.FAILED); validationResponse.setErrorMessages(resolver.resolveErrorCodes(errors.getFieldErrors(), locale)); return validationResponse; }
From source file:org.ualerts.fixed.web.controller.AbstractFormController.java
private Map<String, List<String>> getFieldErrors(Errors errors) { if (!errors.hasFieldErrors()) return null; Map<String, List<String>> fieldErrors = new HashMap<String, List<String>>(); for (FieldError error : errors.getFieldErrors()) { if (!fieldErrors.containsKey(error.getField())) fieldErrors.put(error.getField(), new ArrayList<String>()); fieldErrors.get(error.getField()).add(getMessage(error.getCode())); }/*from ww w . ja va 2 s.c om*/ return fieldErrors; }
From source file:org.openmrs.web.controller.program.PatientProgramFormController.java
private String validateWithErrorCodes(Object obj) { Errors errors = new BindException(obj, ""); Context.getAdministrationService().validate(obj, errors); if (errors.hasErrors()) { StringBuilder message = new StringBuilder(); for (FieldError error : errors.getFieldErrors()) { message.append(Context.getMessageSourceService().getMessage(error.getCode())).append("<br />"); }//from w w w . jav a 2 s. c o m return message.toString(); } return null; }
From source file:by.creepid.docgeneration.validation.RegValidator.java
@Override public void validate(FacesContext context, UIComponent component, Object value) { Locale locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale(); WebUtils.clearFacesMessages(context); FirmReg firmReg = (FirmReg) WebUtils.findBean("reg"); System.out.println(firmReg.toString()); Errors errors = new BeanPropertyBindingResult(firmReg, "reg"); firmRegValidator.validate(firmReg, errors); if (errors != null && errors.hasErrors()) { String message = messageSource.getMessage("error.validation", null, locale); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null)); List<FieldError> fieldErrors = errors.getFieldErrors(); for (FieldError fieldError : fieldErrors) { message = messageSource.getMessage(fieldError, locale); System.out.println(//ww w. ja v a 2s . c o m fieldError.getField() + " " + fieldError.getCode() + " " + fieldError.getObjectName()); context.addMessage(fieldError.getField(), new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message)); } } }
From source file:com.acc.controller.BaseController.java
protected ValidationErrorData handleValidationErrorInternal(final String errorClass, final String errorMsg, final Errors errors) { final Locale currentLocale = commerceCommonI18NService.getCurrentLocale(); final ValidationErrorData validationErrorData = new ValidationErrorData(); validationErrorData.setClassName(errorClass); validationErrorData.setMessage(errorMsg); final List<String> validationErrors = new ArrayList<String>(); for (final ObjectError error : errors.getGlobalErrors()) { final String validationError = getMessage(error.getCode(), error.getArguments(), currentLocale); validationErrors.add(validationError); }/*from ww w.java2 s . com*/ for (final FieldError error : errors.getFieldErrors()) { final String validationError = createValidationError(error.getField(), getMessage(error.getCode(), error.getArguments(), currentLocale)); validationErrors.add(validationError); } validationErrorData.setValidationErrors(validationErrors); return validationErrorData; }
From source file:org.openmrs.module.uiframework.FragmentActionController.java
/** * @param path should be of the form "provider/optional/subdirectories/fragmentName/actionName" * @param returnFormat/*w w w . j a v a 2 s . com*/ * @param successUrl * @param failureUrl * @param request * @param model * @param response * @return * @throws Exception */ public String handlePath(String path, String returnFormat, String successUrl, String failureUrl, HttpServletRequest request, Model model, HttpServletResponse response) throws Exception { // handle the case where the url has two slashes, e.g. host/openmrs//emr/radiology/order.action if (path.startsWith("/")) { path = path.substring(1); } int firstSlash = path.indexOf("/"); int lastSlash = path.lastIndexOf("/"); if (firstSlash < 0 || lastSlash < 0) { throw new IllegalArgumentException( "fragment action request must have at least provider/fragmentName/actionName, but this does not: " + request.getRequestURI()); } String providerName = path.substring(0, firstSlash); String fragmentName = path.substring(firstSlash + 1, lastSlash); String action = path.substring(lastSlash + 1); if (returnFormat == null) { String acceptHeader = request.getHeader("Accept"); if (StringUtils.isNotEmpty(acceptHeader)) { if (acceptHeader.startsWith("application/json")) { returnFormat = "json"; } } } Object resultObject; try { resultObject = fragmentFactory.invokeFragmentAction(providerName, fragmentName, action, request); // Default status code for failures is 400 (BAD REQUEST), successes is 200 (OK) response.setStatus((resultObject instanceof FailureResult) ? 400 : 200); } catch (Exception ex) { // Look for specific exceptions down the chain Exception specificEx = null; // It's possible that the underlying exception is that the user was logged out or lacks privileges if ((specificEx = ExceptionUtil.findExceptionInChain(ex, APIAuthenticationException.class)) != null) { resultObject = new FailureResult("#APIAuthenticationException#" + specificEx.getMessage()); response.setStatus(403); // 403 (FORBIDDEN) } else if ((specificEx = ExceptionUtil.findExceptionInChain(ex, ContextAuthenticationException.class)) != null) { resultObject = new FailureResult("#APIAuthenticationException#" + specificEx.getMessage()); response.setStatus(403); // 403 (FORBIDDEN) } else { // We don't know how to handle other types of exceptions log.error("error", ex); // TODO figure how to return UiFrameworkExceptions that result from // missing controllers or methods with status 404 (NOT FOUND) throw new UiFrameworkException("Error invoking fragment action", ex); } } if (!StringUtils.isEmpty(returnFormat)) { // this is an ajax request, so we need to return an object // turn the non-object result types into ObjectResults if (resultObject == null) { resultObject = new SuccessResult(); } else if (resultObject instanceof SuccessResult) { SuccessResult success = (SuccessResult) resultObject; resultObject = SimpleObject.create("success", "true", "message", success.getMessage()); } else if (resultObject instanceof FailureResult) { FailureResult failure = (FailureResult) resultObject; resultObject = SimpleObject.create("failure", "true", "globalErrors", failure.getGlobalErrors(), "fieldErrors", failure.getFieldErrorMap()); } else if (resultObject instanceof ObjectResult) { resultObject = ((ObjectResult) resultObject).getWrapped(); } // Convert result to JSON or plain text depending on requested format Object result; if (returnFormat.equals("json")) { result = toJson(resultObject); } else { result = resultObject.toString(); } model.addAttribute("html", result); return SHOW_HTML_VIEW; } else { // this is a regular post, so we will return a page if (successUrl == null) successUrl = getSuccessUrl(request); if (failureUrl == null) failureUrl = getFailureUrl(request, successUrl); successUrl = removeContextPath(successUrl); failureUrl = removeContextPath(failureUrl); if (resultObject == null || resultObject instanceof SuccessResult) { if (resultObject != null) { SuccessResult result = (SuccessResult) resultObject; if (result.getMessage() != null) request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, result.getMessage()); } return "redirect:/" + successUrl; } else if (resultObject instanceof FailureResult) { // TODO harmonize this with the return-type version FailureResult failureResult = (FailureResult) resultObject; String errorMessage = null; if (failureResult.getSingleError() != null) { errorMessage = failureResult.getSingleError(); } else if (failureResult.getErrors() != null) { Errors errors = failureResult.getErrors(); StringBuilder sb = new StringBuilder(); sb.append("<ul>"); for (ObjectError err : errors.getGlobalErrors()) { sb.append("<li>" + UiFrameworkUtil.getMessage(err) + "</li>"); } for (FieldError err : errors.getFieldErrors()) { sb.append("<li>" + err.getField() + ": " + UiFrameworkUtil.getMessage(err) + "</li>"); } sb.append("</ul>"); errorMessage = sb.toString(); } request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, errorMessage); return redirectHelper(failureUrl, model); } else if (resultObject instanceof ObjectResult) { // the best we can do is just display a formatted version of the wrapped object String formatted = new FormatterImpl(messageSource, administrationService) .format(((ObjectResult) resultObject).getWrapped(), Context.getLocale()); model.addAttribute("html", formatted); return SHOW_HTML_VIEW; } else { throw new RuntimeException( "Don't know how to handle fragment action result type: " + resultObject.getClass()); } } }