Example usage for org.springframework.validation FieldError getField

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

Introduction

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

Prototype

public String getField() 

Source Link

Document

Return the affected field of the object.

Usage

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

/**
 * Adds an "errors" property in the response if there are any errors in the
 * bindingResult. Sets the success flag to false if there are errors.
 *
 * @param locale//  w w w .  jav a2  s.c  o m
 * @param messageSource
 * @param bindingResult
 * @return this instance
 */
public ExtDirectResponseBuilder addErrors(Locale locale, MessageSource messageSource,
        final BindingResult bindingResult) {
    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", Boolean.TRUE);
        } else {
            addResultProperty("errors", errorMap);
            addResultProperty("success", Boolean.FALSE);
        }
    }
    return this;
}

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) {/*w w  w  . j av a 2s  . c  om*/
    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:jp.terasoluna.batch.functionsample.b009.SkipValidationErrorHandler.java

/**
 * ?O?W.<br>/* w w w.j  av  a  2s  .  c  o  m*/
 * @param dataValueObject DataValueObject
 * @param errors Errors
 * @return ?O
 */
protected String logEdit(DataValueObject dataValueObject, Errors errors) {
    StringBuilder sb = new StringBuilder();
    List<FieldError> fel = getFieldErrorList(errors);

    for (FieldError fe : fel) {
        sb.setLength(0);
        sb.append("ValidationError");
        sb.append(" dataCount:[");
        if (dataValueObject != null) {
            sb.append(dataValueObject.getDataCount());
        }
        sb.append("]");
        sb.append(" code:[");
        sb.append(fe.getCode());
        sb.append("]");
        sb.append(" objectName:[");
        sb.append(fe.getObjectName());
        sb.append("]");
        sb.append(" field:[");
        sb.append(fe.getField());
        sb.append("]");
        sb.append(" rejectedValue:[");
        sb.append(fe.getRejectedValue());
        sb.append("]");
    }
    return sb.toString();
}

From source file:org.jdal.ui.ViewSupport.java

/**
 * {@inheritDoc}/* w w w  . j ava2  s  . com*/
 */
public boolean validateView() {
    if (validator == null && !errors.hasErrors())
        return true;

    if (validator != null)
        validator.validate(getModel(), errors);

    if (errors.hasErrors()) {
        for (FieldError error : errors.getFieldErrors()) {
            for (ErrorProcessor ep : errorProcessors) {
                if (error instanceof ControlError) {
                    ControlError ce = (ControlError) error;
                    ep.processError(ce.getComponent(), error);
                } else {
                    Binder<?> b = binder.getBinder(error.getField());
                    if (b instanceof PropertyBinder) {
                        ep.processError(((PropertyBinder) b).getComponent(), error);
                    }
                }
            }
        }
        return false;
    }
    return 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
 * /*ww w .  j  a v  a 2s  .  c om*/
 * @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  w  w .  j a v  a 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:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "addRank", method = RequestMethod.POST)
public String addRank(@Valid @ModelAttribute RankModel newRank, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getField() + " ist falsch";
        }//from  w  w w .  j  av  a  2s  .  c  o  m
        model.addAttribute("errorMessage", errorMessage);
        return "forward:dienstgrade";
    }
    rankRepository.save(newRank);
    model.addAttribute("message", "Neuer Dienstgrad " + newRank.getDescription() + " hinzugefgt.");

    return "forward:dienstgrade";
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "addStatus", method = RequestMethod.POST)
public String addStatus(@Valid @ModelAttribute FireFighterStatusModel newStatus, BindingResult bindingResult,
        Model model) {/*from  www  . j a v a  2 s.  co  m*/
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getField() + " ist falsch";
        }
        model.addAttribute("errorMessage", errorMessage);
        return "forward:status";
    }
    statusRepository.save(newStatus);
    model.addAttribute("message", "Neuer Mitgliederstatus " + newStatus.getDescription() + " hinzugefgt.");

    return "forward:status";
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "addFunction", method = RequestMethod.POST)
public String addFunction(@Valid @ModelAttribute FireEngineAbbreviationModel newFireEngineAbbreviation,
        BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getField() + " ist falsch";
        }//w  ww .j  a  v  a  2 s . co  m
        model.addAttribute("errorMessage", errorMessage);
        return "forward:funktionen";
    }
    fireEngineAbbreviationRepository.save(newFireEngineAbbreviation);
    model.addAttribute("message",
            "Neue Fahrzeugfunktion " + newFireEngineAbbreviation.getDescription() + " hinzugefgt.");

    return "forward:feuerwehr";
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = "addFireFighter", method = RequestMethod.POST)
public String addFireFighter(@Valid @ModelAttribute FireFighterModel newFireFighter,
        BindingResult bindingResult, Model model, HttpServletRequest request) {

    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage = fieldError.getField() + " ist falsch";
        }//from  w ww  .  j a  v a 2 s  .c o  m
        model.addAttribute("errorMessage", errorMessage);
        return "forward:mitglieder";
    }
    if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        newFireFighter.setFireBrigade(getSessionFireBrigade());
    }
    fireFighterRepository.save(newFireFighter);
    model.addAttribute("message",
            "Mitglied " + newFireFighter.getName() + " " + newFireFighter.getSurname() + " hinzugefgt.");

    return "forward:mitglieder";
}