Example usage for org.springframework.validation BindingResult getFieldErrors

List of usage examples for org.springframework.validation BindingResult getFieldErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getFieldErrors.

Prototype

List<FieldError> getFieldErrors();

Source Link

Document

Get all errors associated with a field.

Usage

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

@RequestMapping(value = "editFireEngine", method = RequestMethod.POST)
public String editFireEngine(@Valid @ModelAttribute FireEngineModel changedFireEngine,
        BindingResult bindingResult, Model model, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage = fieldError.getField() + " is invalid";
        }//  w w w.  java2  s. c  o m
        model.addAttribute("errorMessage", errorMessage);
        return "forward:fahrzeuge";
    }

    if (changedFireEngine.getActive() == null) {
        changedFireEngine.setActive(false);
    }

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireEngineModel fireEngine = fireEngineRepository.findById(changedFireEngine.getId());

        if (fireEngine == null) {
            model.addAttribute("errorMessage", "Diese Fahrzeug kann nicht bearbeitet werden!");
        } else {
            fireEngine.setModel(changedFireEngine.getModel());
            fireEngine.setLicensePlate(changedFireEngine.getLicensePlate());
            fireEngine.setPerformance(changedFireEngine.getPerformance());
            fireEngine.setBuildYear(changedFireEngine.getBuildYear());
            fireEngine.setActive(changedFireEngine.getActive());
            fireEngine.setAbbreviation(changedFireEngine.getAbbreviation());
            fireEngine.setFireBrigade(changedFireEngine.getFireBrigade());
            fireEngineRepository.save(fireEngine);
            model.addAttribute("message", "Fahrzeug " + changedFireEngine.getModel() + " " + "wurde gendert.");
        }
        return "forward:fahrzeuge";

    } else {
        FireEngineModel fireEngine = fireEngineRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                changedFireEngine.getId());

        if (fireEngine == null) {
            model.addAttribute("errorMessage", "Dieses Fahrzeug kann nicht bearbeitet werden!");
            System.out.println("Falsches Fahrzeug!");
        } else {
            fireEngine.setModel(changedFireEngine.getModel());
            fireEngine.setLicensePlate(changedFireEngine.getLicensePlate());
            fireEngine.setPerformance(changedFireEngine.getPerformance());
            fireEngine.setBuildYear(changedFireEngine.getBuildYear());
            fireEngine.setActive(changedFireEngine.getActive());
            fireEngine.setAbbreviation(changedFireEngine.getAbbreviation());
            fireEngine.setFireBrigade(getSessionFireBrigade());
            fireEngineRepository.save(fireEngine);
            model.addAttribute("message", "Fahrzeug " + changedFireEngine.getModel() + " " + "wurde gendert.");
        }
        return "forward:fahrzeuge";
    }
}

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

@RequestMapping(value = "editFireFighter", method = RequestMethod.POST)
public String editFireFighter(@Valid @ModelAttribute FireFighterModel changedFireFighter,
        BindingResult bindingResult, Model model, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage = fieldError.getField() + " ist ungltig!";
        }/*from   ww w.  ja  v a  2s .c  o m*/
        model.addAttribute("errorMessage", errorMessage);
        return "forward:mitglieder";
    }

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        FireFighterModel fireFighter = fireFighterRepository.findById(changedFireFighter.getId());

        if (fireFighter == null) {
            model.addAttribute("errorMessage", "Dieses Mitglied kann nicht bearbeitet werden!");
        } else {
            fireFighter.setTitle(changedFireFighter.getTitle());
            fireFighter.setName(changedFireFighter.getName());
            fireFighter.setSurname(changedFireFighter.getSurname());
            fireFighter.setRank(changedFireFighter.getRank());
            fireFighter.setFireBrigade(changedFireFighter.getFireBrigade());
            fireFighter.setFireFighterStatus(changedFireFighter.getFireFighterStatus());
            fireFighter.setStreetName(changedFireFighter.getStreetName());
            fireFighter.setPostalCode(changedFireFighter.getPostalCode());
            fireFighter.setPostTown(changedFireFighter.getPostTown());
            fireFighter.setGender(changedFireFighter.getGender());
            fireFighter.setDayOfBirth(changedFireFighter.getDayOfBirth());
            fireFighterRepository.save(fireFighter);
            model.addAttribute("message", "Mitglied " + changedFireFighter.getName() + " "
                    + changedFireFighter.getSurname() + " " + "wurde gendert.");
        }
        return "forward:mitglieder";

    } else {
        FireFighterModel fireFighter = fireFighterRepository.findByFireBrigadeAndId(getSessionFireBrigade(),
                changedFireFighter.getId());

        if (fireFighter == null) {
            model.addAttribute("errorMessage", "Dieses Mitglied kann nicht bearbeitet werden!");
            System.out.println("Falsches Mitglied!");
        } else {
            fireFighter.setTitle(changedFireFighter.getTitle());
            fireFighter.setName(changedFireFighter.getName());
            fireFighter.setSurname(changedFireFighter.getSurname());
            fireFighter.setRank(changedFireFighter.getRank());
            fireFighter.setFireBrigade(getSessionFireBrigade());
            fireFighter.setFireFighterStatus(changedFireFighter.getFireFighterStatus());
            fireFighter.setStreetName(changedFireFighter.getStreetName());
            fireFighter.setPostalCode(changedFireFighter.getPostalCode());
            fireFighter.setPostTown(changedFireFighter.getPostTown());
            fireFighter.setGender(changedFireFighter.getGender());
            fireFighter.setDayOfBirth(changedFireFighter.getDayOfBirth());
            fireFighterRepository.save(fireFighter);
            model.addAttribute("message", "Mitglied " + changedFireFighter.getName() + " "
                    + changedFireFighter.getSurname() + " " + "wurde gendert.");
        }
        return "forward:mitglieder";
    }
}

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

@RequestMapping(value = "addFireEngine", method = RequestMethod.POST)
public String addFireEngine(@Valid @ModelAttribute FireEngineModel newFireEngine, BindingResult bindingResult,
        Model model, HttpServletRequest request) {
    System.out.println(newFireEngine);
    if (bindingResult.hasErrors()) {
        String errorMessage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage = fieldError.getField() + " ist falsch";
        }//from  www  .  ja va  2 s.  com
        model.addAttribute("errorMessage", errorMessage);
        return "forward:fahrzeuge";
    }
    if (newFireEngine.getActive() == null) {
        newFireEngine.setActive(false);
    }

    if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        newFireEngine.setFireBrigade(getSessionFireBrigade());
    }
    fireEngineRepository.save(newFireEngine);
    model.addAttribute("message", "Fahrzeug " + newFireEngine.getModel() + " hinzugefgt.");

    return "forward:fahrzeuge";
}

From source file:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*w  w w. j a  va2  s  . c om*/
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.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java

private void parseResult(BindingResult result, ModelMap map) {

    if (result.getFieldErrors().size() > 0) {
        List<String> errorMsgList = new ArrayList<String>();
        for (FieldError fieldError : result.getFieldErrors()) {
            String fieldName = fieldError.getField();
            if (fieldName.contains(".")) {
                fieldName = fieldName.substring(fieldName.lastIndexOf(".") + 1);
            }//w  ww  .j av a  2 s . com
            errorMsgList.add(fieldName + " field value '" + fieldError.getRejectedValue() + "' is not valid.");
        }

        map.addAttribute("errorMsgList", errorMsgList);
        map.addAttribute("errormsg", "true");
    }
    if (result.hasGlobalErrors()) {
        List<ObjectError> errorList = result.getGlobalErrors();
        if (errorList.size() > 0) {
            List<String> globalErrors = new ArrayList<String>();
            for (ObjectError error : errorList) {
                globalErrors.add(error.getCode());

            }
            map.addAttribute("globalErrors", globalErrors);
            map.addAttribute("errormsg", "true");
        }

    }
}

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) {/*  ww  w. j  a va2s . 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:com.citrix.cpbm.portal.fragment.controllers.AbstractBillingController.java

@RequestMapping(value = "/record_deposit", method = RequestMethod.POST)
@ResponseBody/*from w  w  w. j a v a  2 s . co m*/
public DepositRecordForm recordDeposit(@RequestParam(value = "tenant", required = false) String tenantParam,
        @Valid @ModelAttribute("depositRecordForm") DepositRecordForm depositRecordForm, BindingResult result,
        ModelMap map, HttpServletResponse response) {
    logger.debug("###Entering in recordDeposit method @POST");

    setPage(map, Page.USAGE_BILLING_RECORD_DEPOSIT);
    map.addAttribute("showUserProfile", true);

    Tenant tenant = tenantService.get(tenantParam);
    map.addAttribute("tenant", tenant);
    map.addAttribute("depositForm", depositRecordForm);
    DepositRecordValidator depositRecordValidator = new DepositRecordValidator();
    depositRecordValidator.validate(depositRecordForm, result);
    if (result.hasErrors()) {
        map.addAttribute("depositRecordForm", depositRecordForm);
        List<FieldError> l = result.getFieldErrors();
        for (FieldError f : l) {
            if (f.getCode().equals("js.deposit.record.validationReceivedOn")) {
                throw new AjaxFormValidationException(result);
            }
        }
    }

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date recievedOn = null;
        try {
            recievedOn = sdf.parse(depositRecordForm.getReceivedOn());
        } catch (ParseException e) {
        }
        tenantService.recordDeposit(tenant,
                new DepositRecord(
                        tenant, recievedOn, tenant.getAccountType()
                                .getInitialDeposit(tenant.getCurrency().getCurrencyCode()).doubleValue(),
                        getCurrentUser()));

    } catch (HibernateOptimisticLockingFailureException ex) {
        logger.error(ex);
        tenantService.refresh(tenant);
        throw new InvalidAjaxRequestException(ex.getMessage());
    }
    response.setStatus(HttpStatus.OK.value());
    logger.debug("###Exiting recordDeposit method @POST");

    return depositRecordForm;
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testRegisterInvalidFirstName() throws Exception {
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    AccountType accountType = accountTypeDAO.getAccountTypeByName("RETAIL");

    UserRegistration registration = new UserRegistration();
    // Creating user object for registration
    final String INVALIDFIRSTNAME = "!@#$%12345";
    User user = new User(INVALIDFIRSTNAME, "test", "test@test.com", "test1234", VALID_PASSWORD, VALID_PHONE,
            VALID_TIMEZONE, null, null, null);
    BindingResult result = setUpRegistrationForGivenUser(user, registration, accountType);

    beforeRegisterCall(mockRequest, registration);
    int beforeUserCount = userDAO.count();
    String view = controller.userInfo(registration, result, map, null, status, mockRequest);
    Assert.assertTrue(result.hasErrors());
    Assert.assertEquals("register.userinfo", view);
    List<FieldError> fieldErrorList = result.getFieldErrors();
    Assert.assertEquals("javax.validation.constraints.Pattern.message", fieldErrorList.get(0).getCode());
    int afterUserCount = userDAO.count();
    Assert.assertEquals(afterUserCount, beforeUserCount);
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testRegisterInvalidLastName() throws Exception {
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    AccountType accountType = accountTypeDAO.getAccountTypeByName("RETAIL");

    UserRegistration registration = new UserRegistration();
    // Creating user object for registration
    final String INVALIDLASTNAME = "!@#$%12345";
    User user = new User("test", INVALIDLASTNAME, "test@test.com", "test1234", VALID_PASSWORD, VALID_PHONE,
            VALID_TIMEZONE, null, null, null);
    BindingResult result = setUpRegistrationForGivenUser(user, registration, accountType);

    beforeRegisterCall(mockRequest, registration);
    int beforeUserCount = userDAO.count();
    String view = controller.userInfo(registration, result, map, null, status, mockRequest);
    Assert.assertTrue(result.hasErrors());
    Assert.assertEquals("register.userinfo", view);
    List<FieldError> fieldErrorList = result.getFieldErrors();
    Assert.assertEquals("javax.validation.constraints.Pattern.message", fieldErrorList.get(0).getCode());
    int afterUserCount = userDAO.count();
    Assert.assertEquals(afterUserCount, beforeUserCount);
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testRegisterInvalidUsernameLength() throws Exception {
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    AccountType accountType = accountTypeDAO.getAccountTypeByName("RETAIL");

    UserRegistration registration = new UserRegistration();
    // Creating user and tenant objects for registration
    final String USERNAME = "abcd";
    User user = new User("test", "test", "test@test.com", USERNAME, VALID_PASSWORD, VALID_PHONE, VALID_TIMEZONE,
            null, null, null);/*ww  w  .ja  v a  2 s  .c  om*/
    BindingResult result = setUpRegistrationForGivenUser(user, registration, accountType);

    beforeRegisterCall(mockRequest, registration);
    int beforeUserCount = userDAO.count();

    String view = controller.userInfo(registration, result, map, null, status, mockRequest);
    Assert.assertTrue(result.hasErrors());
    Assert.assertEquals("register.userinfo", view);
    List<FieldError> fieldErrorList = result.getFieldErrors();
    int errorMessage = 0;
    for (FieldError fieldError : fieldErrorList) {
        if ("javax.validation.constraints.Size.message".equals(fieldError.getCode())) {
            errorMessage++;
        } else if ("javax.validation.constraints.MinimumSize.message".equals(fieldError.getCode())) {
            errorMessage++;
        }
    }
    Assert.assertTrue(errorMessage == 2);
    int afterUserCount = userDAO.count();
    Assert.assertEquals(afterUserCount, beforeUserCount);
}