Example usage for org.springframework.validation FieldError getDefaultMessage

List of usage examples for org.springframework.validation FieldError getDefaultMessage

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getDefaultMessage.

Prototype

@Override
    @Nullable
    public String getDefaultMessage() 

Source Link

Usage

From source file:org.jasig.schedassist.web.register.Registration.java

/**
 * Validate schedule related fields./*  ww w. ja v  a2 s.  c om*/
 * 
 * Delegates to a {@link BlockBuilderFormBackingObject}.
 * @param context
 */
public void validateSetSchedule(final ValidationContext context) {
    MessageContext messages = context.getMessageContext();

    BlockBuilderFormBackingObject command = this.toBlockBuilderFormBackingObject();
    BlockBuilderFormBackingObjectValidator validator = new BlockBuilderFormBackingObjectValidator();
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(command, "registration");
    validator.validate(command, errors);

    if (errors.hasErrors()) {
        for (FieldError error : errors.getFieldErrors()) {
            messages.addMessage(new MessageBuilder().error().source(error.getField())
                    .defaultText(error.getDefaultMessage()).build());
        }
    } else {
        this.scheduleSet = true;
    }
}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectFormPostResult.java

private void addErrors(Locale locale, MessageSource messageSource, BindingResult bindingResult) {
    if (bindingResult != null && bindingResult.hasFieldErrors()) {
        Map<String, String> errorMap = new HashMap<String, String>();
        for (ObjectError objectError : bindingResult.getAllErrors()) {
            FieldError fieldError = (FieldError) objectError;
            String message = null;
            for (String code : fieldError.getCodes()) {
                message = MessageUtil.getMessage(code, null, locale); // , new Object[] {(fieldError.getObjectName() +"." + fieldError.getField()), fieldError.getRejectedValue()}
                if (StringUtils.isNotBlank(message)) {
                    break;
                }//  w  w w  . j  av a 2  s  .co m
            }
            errorMap.put(fieldError.getField(),
                    StringUtils.defaultIfBlank(message, fieldError.getDefaultMessage()));
        }
        if (errorMap.isEmpty()) {
            addResultProperty("success", true);
        } else {
            addResultProperty("errors", errorMap);
            addResultProperty("success", false);
        }
    } else {
        setSuccess(true);
    }

    //        if (bindingResult != null && bindingResult.hasFieldErrors()) {
    //            Map<String, List<String>> errorMap = new HashMap<String, List<String>>();
    //            for (FieldError fieldError : bindingResult.getFieldErrors()) {
    //                String message = fieldError.getDefaultMessage();
    //                if (messageSource != null) {
    //                    Locale loc = (locale != null ? locale : Locale.getDefault());
    //                    message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc);
    //                }
    //                List<String> fieldErrors = errorMap.get(fieldError.getField());
    //
    //                if (fieldErrors == null) {
    //                    fieldErrors = new ArrayList<String>();
    //                    errorMap.put(fieldError.getField(), fieldErrors);
    //                }
    //
    //                fieldErrors.add(message);
    //            }
    //            if (errorMap.isEmpty()) {
    //                addResultProperty("success", true);
    //            } else {
    //                addResultProperty("errors", errorMap);
    //                addResultProperty("success", false);
    //            }
    //        } else {
    //            setSuccess(true);
    //        }
}

From source file:tv.arte.resteventapi.web.errors.GlobalDefaultExceptionHandler.java

/**
 * Handle all exceptions of type {@link BindException} thrown by (or passing trough) the Controller's layer
 * /*from ww  w. j a v a 2  s .  c  o  m*/
 * @param response The HttpServletResponse
 * @param e Thrown RestEventApiValidationException
 * @return
 * @throws Exception
 */
@ExceptionHandler(value = BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ModelAndView springBindExceptionExceptionHandler(HttpServletRequest request, BindException e)
        throws Exception {

    RestEventApiStandardResponse<RestEventApiMessage> restEventApiStandardResponse = new RestEventApiStandardResponse<RestEventApiMessage>();
    Locale userLocale = request.getLocale();
    String descriprionNotAvailableDefaultMessage = RestEventApiError.PRE_DEFINED.RIA_ERR_G_DESC_NOT_AVAILABLE
            .getDefaultMessageText();

    for (ObjectError globalError : e.getGlobalErrors()) {
        restEventApiStandardResponse.addError(new RestEventApiMessage(globalError.getDefaultMessage(),
                this.messageSource.getMessage(globalError.getCode(), globalError.getArguments(),
                        descriprionNotAvailableDefaultMessage, userLocale)));
    }

    for (FieldError fieldError : e.getFieldErrors()) {

        String messageCode = null;
        String defaultMessageText = null;

        if (fieldError.isBindingFailure()) {
            messageCode = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getCode();
            defaultMessageText = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getDefaultMessageText();
        } else {
            //TODO: Find an appropriate way to search pre-defined RestEventAPiError
            messageCode = fieldError.getDefaultMessage();
            defaultMessageText = descriprionNotAvailableDefaultMessage;
        }

        restEventApiStandardResponse
                .addError(new FieldValidationError(messageCode, this.messageSource.getMessage(messageCode,
                        fieldError.getArguments(), defaultMessageText, userLocale), fieldError.getField()));

    }

    ModelAndView mav = new ModelAndView();
    mav.addObject(restEventApiStandardResponse);
    mav.setView(restEventApiDefaultErrorView);

    return mav;
}

From source file:tv.arte.resteventapi.web.errors.GlobalDefaultExceptionHandler.java

/**
 * Handle all exceptions of type {@link ImageRepositoryException} thrown by (or passing trough) the Controller's layer
 * /* w  ww .  ja  va 2 s.  c o  m*/
 * @param response The HttpServletResponse
 * @param e Thrown RestEventApiValidationException
 * @return
 * @throws Exception
 */
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ModelAndView restEventApiMethodArgumentNotValidExceptionHandler(HttpServletRequest request,
        MethodArgumentNotValidException e) throws Exception {
    RestEventApiStandardResponse<RestEventApiMessage> restEventApiStandardResponse = new RestEventApiStandardResponse<RestEventApiMessage>();
    Locale userLocale = request.getLocale();
    String descriprionNotAvailableDefaultMessage = RestEventApiError.PRE_DEFINED.RIA_ERR_G_DESC_NOT_AVAILABLE
            .getDefaultMessageText();

    for (ObjectError globalError : e.getBindingResult().getGlobalErrors()) {
        restEventApiStandardResponse.addError(new RestEventApiMessage(globalError.getDefaultMessage(),
                this.messageSource.getMessage(globalError.getCode(), globalError.getArguments(),
                        descriprionNotAvailableDefaultMessage, userLocale)));
    }

    for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {

        String messageCode = null;
        String defaultMessageText = null;

        if (fieldError.isBindingFailure()) {
            messageCode = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getCode();
            defaultMessageText = RestEventApiError.PRE_DEFINED.RIA_ERR_V_BINDING.getDefaultMessageText();
        } else {
            //TODO: Find an appropriate way to search pre-defined RestEventAPiError
            messageCode = fieldError.getDefaultMessage();
            defaultMessageText = descriprionNotAvailableDefaultMessage;
        }

        restEventApiStandardResponse
                .addError(new FieldValidationError(messageCode, this.messageSource.getMessage(messageCode,
                        fieldError.getArguments(), defaultMessageText, userLocale), fieldError.getField()));

    }

    ModelAndView mav = new ModelAndView();
    mav.addObject(restEventApiStandardResponse);
    mav.setView(restEventApiDefaultErrorView);

    return mav;
}

From source file:co.adun.mvnejb3jpa.web.controller.InitiateLeadController.java

@RequestMapping(value = "/ajaxPost", method = RequestMethod.POST, produces = "application/xml")
public @ResponseBody String doAjaxPost(@Valid @ModelAttribute("model") PageModel model, BindingResult result,
        HttpServletRequest request) {/*from w ww. j  a  v  a  2 s.  co m*/
    logger.info("InitiateLeadController doPost()" + model);

    LeadModel leadModel = (LeadModel) model;

    StringBuffer response = new StringBuffer();
    try {
        if (!result.hasErrors()) {
            List<LtLead> ltLeads = process(leadModel);

            ltLeads = leadService.save(ltLeads);

            response.append("<response status='success'>");
            response.append("<message code=''>");

            for (LtLead ltLead : ltLeads) {
                // TODO avoid DB fetch inside loop
                // TODO use entity transformer
                ltLead = leadService.getLead(ltLead.getId());
                LtSubject ltSubject = ltLead.getLtSubject();
                String name = ltSubject.getLastname() + ", " + ltSubject.getFirstname();
                String lsid = ltSubject.getLsid();
                response.append("<subject name='").append(name).append("' id='").append(lsid).append("' />");
            }

            response.append("</message>");

        } else {
            response.append("<response status='error'>");

            for (FieldError error : result.getFieldErrors()) {
                response.append("<error code='").append(error.getField()).append("' message='")
                        .append(error.getDefaultMessage()).append("' />");
            }
        }
    } catch (BusinessException e) {

        response.append("<response status='error'>");
        response.append("<error code='").append("").append("' message='").append(e.getMessage()).append("' />");
        logger.log(Level.SEVERE, e.getMessage(), e);

    } finally {
    }

    return response.append("</response>").toString();
}

From source file:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from w w w  . j av  a 2  s.c  o  m*/
public Form<T> bind(final Map<String, String> data, final String... allowedFields) {
    DataBinder dataBinder = null;
    Map<String, String> objectData = data;
    if (rootName == null) {
        dataBinder = new DataBinder(blankInstance());
    } else {
        dataBinder = new DataBinder(blankInstance(), rootName);
        objectData = new HashMap<String, String>();
        for (String key : data.keySet()) {
            if (key.startsWith(rootName + ".")) {
                objectData.put(key.substring(rootName.length() + 1), data.get(key));
            }
        }
    }
    if (allowedFields.length > 0) {
        dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(play.data.format.Formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    dataBinder.bind(new MutablePropertyValues(objectData));

    Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget());
    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = result.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                result.rejectValue(field,
                        violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
                        getArgumentsForConstraint(result.getObjectName(), field,
                                violation.getConstraintDescriptor()),
                        violation.getMessage());
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }

    if (result.hasErrors()) {
        Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
        for (FieldError error : result.getFieldErrors()) {
            String key = error.getObjectName() + "." + error.getField();
            System.out.println("Error field:" + key);
            if (key.startsWith("target.") && rootName == null) {
                key = key.substring(7);
            }
            List<Object> arguments = new ArrayList<>();
            for (Object arg : error.getArguments()) {
                if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
                    arguments.add(arg);
                }
            }
            if (!errors.containsKey(key)) {
                errors.put(key, new ArrayList<ValidationError>());
            }
            errors.get(key).add(new ValidationError(key,
                    error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments));
        }
        return new Form(rootName, backedType, data, errors, F.Option.None());
    } else {
        Object globalError = null;
        if (result.getTarget() != null) {
            try {
                java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
                globalError = v.invoke(result.getTarget());
            } catch (NoSuchMethodException e) {
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        if (globalError != null) {
            Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
            if (globalError instanceof String) {
                errors.put("", new ArrayList<ValidationError>());
                errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
            } else if (globalError instanceof List) {
                for (ValidationError error : (List<ValidationError>) globalError) {
                    List<ValidationError> errorsForKey = errors.get(error.key());
                    if (errorsForKey == null) {
                        errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>());
                    }
                    errorsForKey.add(error);
                }
            } else if (globalError instanceof Map) {
                errors = (Map<String, List<ValidationError>>) globalError;
            }

            if (result.getTarget() != null) {
                return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget()));
            } else {
                return new Form(rootName, backedType, data, errors, F.Option.None());
            }
        }
        return new Form(rootName, backedType, new HashMap<String, String>(data),
                new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget()));
    }
}

From source file:com.asual.summer.core.ErrorResolver.java

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception e) {//from  w  w w . j  av a  2 s .c o 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.gvnix.web.json.BindingResultSerializer.java

/**
 * Loads an object field error in errors map.
 * <p/>// w  ww . j a va  2s .  c om
 * This method identifies if referred object property is an array, an object
 * or a simple property to decide how to store the error message.
 * 
 * @param error
 * @param fieldNamePath
 * @param objectErrors
 */
@SuppressWarnings("unchecked")
private void loadObjectError(FieldError error, String fieldNamePath, Map<String, Object> objectErrors) {

    String propertyName;
    boolean isObject = false;
    boolean isList = false;

    // Get this property name and if is a object property
    if (StringUtils.contains(fieldNamePath, ".")) {
        isObject = true;
        propertyName = StringUtils.substringBefore(fieldNamePath, ".");
    } else {
        isObject = false;
        propertyName = fieldNamePath;
    }

    // Check if property is an array or a list
    isList = StringUtils.contains(propertyName, "[");

    // Process a list item property
    if (isList) {
        // Get property name
        String listPropertyName = StringUtils.substringBefore(propertyName, "[");

        // Get referred item index
        String index = StringUtils.substringBefore(StringUtils.substringAfter(propertyName, "["), "]");

        // Get item path
        String itemPath = StringUtils.substringAfter(fieldNamePath, ".");

        // Get container of list property errors
        Map<String, Object> listErrors = (Map<String, Object>) objectErrors.get(listPropertyName);

        if (listErrors == null) {
            // property has no errors yet: create a container for it
            listErrors = new HashMap<String, Object>();
            objectErrors.put(listPropertyName, listErrors);
        }

        // Get current item errors
        Map<String, Object> itemErrors = (Map<String, Object>) listErrors.get(index);

        if (itemErrors == null) {
            // item has no errors yet: create a container for it
            itemErrors = new HashMap<String, Object>();
            listErrors.put(index, itemErrors);
        }

        // Load error in item property path
        loadObjectError(error, itemPath, itemErrors);

    } else if (isObject) {
        // It's not a list but it has properties in it value

        // Get current property errors
        Map<String, Object> propertyErrors = (Map<String, Object>) objectErrors.get(propertyName);

        if (propertyErrors == null) {
            // item has no errors yet: create a container for it
            propertyErrors = new HashMap<String, Object>();
            objectErrors.put(propertyName, propertyErrors);
        }

        // Get error sub path
        String subFieldPath = StringUtils.substringAfter(fieldNamePath, ".");

        // Load error in container
        loadObjectError(error, subFieldPath, propertyErrors);

    } else {
        // standard property with no children value

        // Store error message in container
        objectErrors.put(propertyName, error.getDefaultMessage());
    }
}

From source file:com.att.pirates.controller.ProjectController.java

@RequestMapping(value = "/updateProjectInfo/{prismId}", method = RequestMethod.POST)
public String updateProjectInfo(@PathVariable("prismId") String prismId,
        @Valid @ModelAttribute("projectInfo") InsightProject projectInfo, BindingResult result) {
    if (result.hasErrors()) {
        logger.error("There are " + result.getErrorCount() + " errors..");
        FieldError er = result.getFieldError();
        logger.error("Field: " + er.getField() + " ErrorMsg: " + er.getDefaultMessage());
    } else {//  w  w  w  .  jav a 2  s. c o  m
        String es = HtmlUtils.htmlEscape(projectInfo.getProjectDescription());

        String status = projectInfo.getProjectStatus();
        String release = projectInfo.getReleaseName();
        String startdate = projectInfo.getProjectStartDate();
        String dueDate = projectInfo.getProjectDueDate();
        // lookup statusid and releaseid
        int statusId = DataService.getStatusIdByname(status);
        int releaseId = DataService.getReleaseIdByName(release);

        InsightProject prj = new InsightProject();
        prj.setPrismId(prismId);
        prj.setLeadPM(projectInfo.getLeadPM());
        prj.setProjectDescription(es);
        prj.setProjectDueDate(dueDate);
        prj.setProjectName(HtmlUtils.htmlEscape(projectInfo.getProjectName()));
        prj.setProjectStartDate(startdate);
        prj.setStatudId(statusId);
        prj.setProjectStatus(status);
        prj.setReleaseName(release);
        prj.setReleaseId(releaseId);

        boolean rc = DataService.updateProjectInfo(prj);
        if (!rc) {
            logger.error("DataService.updateProjectInfo(prj); failed");
        }
    }
    // prismId will be considered while expanding the placeholders
    // return "redirect:/impact_pirates/projects/index/{prismId}";
    return "redirect:/projects/index/{prismId}";
}

From source file:com.zb.app.web.controller.login.LoginController.java

/**
 * ,???,?//from  ww w.  j av  a2 s . c  o m
 * 
 * @param travelCompanyVO
 * @param travelMemberVO
 * @return
 */
@RequestMapping(value = "/doRegister.htm")
@TokenPolicy(remove = true, data = ",token,??!")
public ModelAndView doRegister(@Valid TravelCompanyVO travelCompanyVO, @Valid TravelMemberVO travelMemberVO,
        BindingResult bindingResult, ModelAndView mav) {
    Map<String, Object> model = new HashMap<String, Object>();
    if (bindingResult.hasErrors()) {
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            model.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return createErrorJsonMav("!", model);
    }

    // ?
    TravelCompanyDO travelCompanyDO = new TravelCompanyDO();
    BeanUtils.copyProperties(travelCompanyDO, travelCompanyVO);
    travelCompanyDO.setcState(0);
    travelCompanyDO.setcSpell(PinyinParser.converterToFirstSpell(travelCompanyDO.getcName()));
    companyService.insert(travelCompanyDO);

    // 
    TravelMemberDO travelMemberDO = new TravelMemberDO();
    BeanUtils.copyProperties(travelMemberDO, travelMemberVO);
    travelMemberDO.setmState(0);
    travelMemberDO.setmPassword(EncryptBuilder.getInstance().encrypt(travelMemberVO.getmPassword()));
    travelMemberDO.setcId(travelCompanyDO.getcId());
    travelMemberDO.setmUserName(StringUtils.lowerCase(travelMemberVO.getmUserName()));
    travelMemberDO.setmType(MemberTypeEnum.SUPERADMIN.getValue());
    memberService.insert(travelMemberDO);
    Map<String, String> map = new HashMap<String, String>();
    map.put("cName", travelCompanyDO.getcName());
    map.put("mUserName", travelMemberDO.getmUserName());
    map.put("mEmail", travelMemberDO.getmEmail());
    return createSuccessJsonMav("?!", map);
}