List of usage examples for org.springframework.validation ObjectError getCodes
@Override
@Nullable
public String[] getCodes()
From source file:jetx.ext.springmvc.SpringMvcFunctions.java
/** * ??/*from ww w . j a va2s.c om*/ */ public static List<String> globalErrors(JetPageContext ctx) { Errors errors = FunctionUtils.findErrors(ctx.getContext()); if (errors == null) { return EMPTY_STRING_LIST; } List<ObjectError> oes = errors.getGlobalErrors(); List<String> msgs = new ArrayList<String>(0); for (ObjectError oe : oes) { String[] codes = oe.getCodes(); String defaultMsg = oe.getDefaultMessage(); Object[] args = oe.getArguments(); Locale locale = getLocale(ctx); MessageSource ms = getMessageSource(ctx); if (codes == null || codes.length == 0 || ms == null) { msgs.add(defaultMsg); } else { String msg = null; for (int i = 0; i < codes.length; i++) { try { msg = ms.getMessage(codes[i], args, locale); } catch (NoSuchMessageException e) { // } if (msg == null) { msg = defaultMsg; } } msgs.add(msg); } } return Collections.unmodifiableList(msgs); }
From source file:org.opentides.util.CrudUtil.java
/** * Converts the binding error messages to list of MessageResponse * //from w ww. ja v a 2 s . co m * @param bindingResult */ public static List<MessageResponse> convertErrorMessage(BindingResult bindingResult, Locale locale, MessageSource messageSource) { List<MessageResponse> errorMessages = new ArrayList<MessageResponse>(); if (bindingResult.hasErrors()) { for (ObjectError error : bindingResult.getAllErrors()) { MessageResponse message = null; if (error instanceof FieldError) { FieldError ferror = (FieldError) error; message = new MessageResponse(MessageResponse.Type.error, error.getObjectName(), ferror.getField(), error.getCodes(), error.getArguments()); } else message = new MessageResponse(MessageResponse.Type.error, error.getObjectName(), null, error.getCodes(), error.getArguments()); message.setMessage(messageSource.getMessage(message, locale)); errorMessages.add(message); } } return errorMessages; }
From source file:technology.tikal.gae.service.template.RestControllerTemplate.java
@ExceptionHandler(NotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST)//from w ww . ja va2 s . c o m public BasicErrorMessage handleException(NotValidException ex, HttpServletRequest request, HttpServletResponse response) { response.setHeader("Content-Type", "application/json;charset=UTF-8"); BasicErrorMessage result = new BasicErrorMessage(); BindingResult detail = ex.getDetails(); String[] msg = new String[detail.getAllErrors().size()]; String[][] code = new String[detail.getAllErrors().size()][]; String[][] args = new String[detail.getAllErrors().size()][]; int index = 0; Locale locale = LocaleContextHolder.getLocale(); for (ObjectError x : detail.getAllErrors()) { Object[] tmpArgs = resolveArgumentMessage(x.getCodes(), x.getArguments()); msg[index] = getValidationMessage(x.getDefaultMessage(), x.getCodes(), tmpArgs, locale); code[index] = x.getCodes(); String[] tmp = new String[tmpArgs.length]; args[index] = tmp; int j = 0; for (Object y : tmpArgs) { args[index][j] = y.toString(); j = j + 1; } index = index + 1; } result.setType(ex.getClass().getSimpleName()); result.setMessage(msg); result.setCode(code); result.setArguments(args); return result; }
From source file:com.asual.summer.core.ErrorResolver.java
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {/*from ww w .j a v a 2 s.co m*/ if (e instanceof BindException) { BindException be = (BindException) e; Map<String, Map<String, Object>> errors = new HashMap<String, Map<String, Object>>(); for (FieldError fe : (List<FieldError>) be.getFieldErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = fe.getArguments(); String key = fe.isBindingFailure() ? fe.getCodes()[2].replaceFirst("typeMismatch", "conversion") : "validation." + fe.getCodes()[2]; String message = ResourceUtils.getMessage(key, args); if (message == null) { if (!fe.isBindingFailure()) { if (key.split("\\.").length > 3) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } } else if (fe.isBindingFailure() && key.split("\\.").length > 2) { message = ResourceUtils.getMessage( key.substring(0, key.indexOf(".")) + key.substring(key.lastIndexOf(".")), args); } else { message = fe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", fe.getRejectedValue()); errors.put(fe.getField(), error); } for (ObjectError oe : (List<ObjectError>) be.getGlobalErrors()) { Map<String, Object> error = new HashMap<String, Object>(); Object[] args = oe.getArguments(); String key = "global" + (oe.getCodes() != null ? "." + oe.getCodes()[2] : ""); String message = ResourceUtils.getMessage(key, args); if (message == null) { if (key.split("\\.").length > 3) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args); } if (message == null && key.split("\\.").length > 2) { message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args); } if (message == null) { message = oe.getDefaultMessage(); } } error.put("message", message != null ? message : "Error (" + key + ")"); error.put("value", oe.getObjectName()); errors.put(oe.getObjectName(), error); } String form = (String) RequestUtils.getParameter("_form"); if (form != null) { if (request.getAttribute(ERRORS) == null) { request.setAttribute(ERRORS, errors); request.setAttribute(be.getObjectName(), be.getTarget()); return new ModelAndView(new InternalResourceView( form.concat(form.contains("?") ? "&" : "?").concat("_error=true"))); } } else { List<String> pairs = new ArrayList<String>(); for (String key : errors.keySet()) { pairs.add(key + "=" + errors.get(key).get("message")); } try { response.sendError(HttpServletResponse.SC_BAD_REQUEST, StringUtils.join(pairs, ";")); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } } } return null; }
From source file:org.openmrs.web.controller.patient.MergePatientsFormController.java
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws Exception { //ModelAndView view = super.processFormSubmission(request, response, object, errors); log.debug("Number of errors: " + errors.getErrorCount()); for (Object o : errors.getAllErrors()) { ObjectError e = (ObjectError) o; log.debug("Error name: " + e.getObjectName()); log.debug("Error code: " + e.getCode()); log.debug("Error message: " + e.getDefaultMessage()); log.debug("Error args: " + Arrays.toString(e.getArguments())); log.debug("Error codes: " + e.getCodes()); }//from w w w . jav a 2 s . c om // call onSubmit manually so that we don't have to call // super.processFormSubmission() return onSubmit(request, response, object, errors); }
From source file:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java
/** * Creates {@link org.agatom.springatom.cmp.wizards.data.result.FeedbackMessage#newError()} message out of {@link org.springframework.validation.ObjectError}. * Runs through {@link org.springframework.validation.ObjectError#getCodes()}} and loops until it locates a valid message (i.e. localized one). In first place * it tries to resolve such message out of {@link org.springframework.validation.ObjectError#getCode()}. If both attempts fails {@link org.springframework.validation.ObjectError#getDefaultMessage()} * is used to create feedback// w ww . j a v a 2s .c o m * * @param objectError current object error * @param locale current locale * * @return new feedback message */ private FeedbackMessage getBindErrorFM(final ObjectError objectError, final Locale locale) { final FeedbackMessage message = FeedbackMessage.newError(); final String[] codes = objectError.getCodes(); boolean found = false; String msg = this.messageSource.getMessage(objectError.getCode(), locale); if (msg.equals(objectError.getCode())) { for (final String code : codes) { msg = this.messageSource.getMessage(code, locale); if (!msg.equals(code)) { msg = this.messageSource.getMessage(code, objectError.getArguments(), locale); found = true; } if (found) { break; } } } else { found = true; } if (!found) { msg = objectError.getDefaultMessage(); } message.setMessage(msg); return message; }
From source file:au.org.ala.biocache.web.OccurrenceController.java
/** * Constructs an error message to be displayed. The error message is based on validation checks that * were performed and stored in the supplied result. * * TODO: If we decide to perform more detailed validations elsewhere it maybe worth providing this in a * util or service class.//from w ww.j a v a 2s. c om * * @param result The result from the validation. * @return A string representation that can be displayed in a browser. */ private String getValidationErrorMessage(BindingResult result) { StringBuilder sb = new StringBuilder(); List<ObjectError> errors = result.getAllErrors(); for (ObjectError error : errors) { logger.debug("Code: " + error.getCode()); logger.debug(StringUtils.join(error.getCodes(), "@#$^")); String code = (error.getCodes() != null && error.getCodes().length > 0) ? error.getCodes()[0] : null; logger.debug("The code in use:" + code); sb.append(messageSource.getMessage(code, null, error.getDefaultMessage(), null)).append("<br/>"); } return sb.toString(); }
From source file:org.springframework.web.struts.SpringBindingActionForm.java
/** * Find the most specific message key for the given error. * @param error the ObjectError to find a message key for * @return the most specific message key found *//*from ww w .ja va2s .com*/ private String findEffectiveMessageKey(ObjectError error) { if (this.messageResources != null) { String[] possibleMatches = error.getCodes(); for (int i = 0; i < possibleMatches.length; i++) { if (logger.isDebugEnabled()) { logger.debug("Looking for error code '" + possibleMatches[i] + "'"); } if (this.messageResources.isPresent(this.locale, possibleMatches[i])) { if (logger.isDebugEnabled()) { logger.debug("Found error code '" + possibleMatches[i] + "' in resource bundle"); } return possibleMatches[i]; } } } if (logger.isDebugEnabled()) { logger.debug("Could not find a suitable message error code, returning default message"); } return null; }