Example usage for org.springframework.validation BindingResult hasGlobalErrors

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

Introduction

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

Prototype

boolean hasGlobalErrors();

Source Link

Document

Are there any global errors?

Usage

From source file:com.mitchellbosecke.pebble.spring.extension.function.bindingresult.HasGlobalErrorsFunction.java

@Override
public Object execute(Map<String, Object> args) {
    String formName = (String) args.get(PARAM_FORM_NAME);

    EvaluationContext context = (EvaluationContext) args.get("_context");
    BindingResult bindingResult = this.getBindingResult(formName, context);

    if (bindingResult != null) {
        return bindingResult.hasGlobalErrors();
    } else {//from w ww  . j a v a2s . c  o  m
        return false;
    }
}

From source file:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String update(Model model, @Valid @ModelAttribute("appointment") AppointmentDTO appointmentDTO,
        BindingResult bindingResult, UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("proceduresOptions", Procedure.values());
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }//ww  w.j  a  v  a  2s .c  o m

        if (bindingResult.hasGlobalErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError er : bindingResult.getGlobalErrors()) {
                sb.append(er.getDefaultMessage());
                sb.append('\n');
            }

            model.addAttribute("globalError", sb);
        }

        return "appointments/edit";
    }
    Long id = appointmentDTO.getId();
    try {
        facade.updateAppointment(appointmentDTO);

        redirectAttributes.addFlashAttribute("alert_success", "Appointment #" + id + " was edited.");
        return "redirect:"
                + uriBuilder.path("/appointments/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile editing: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Appointment #" + id + " was not edited.");
        return "redirect:/";
    }
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenGETBindError_returnBadRequest() throws Exception {
    when(singleJPAEntityService.findOne(TestEntity.class, 1l)).thenReturn(baseEntity);

    MvcResult result = mvc.perform(get("/entity/a")).andExpect(status().isBadRequest())
            .andExpect(view().name("errors/badrequest")).andReturn();

    BindingResult bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(),
            BindingResult.MODEL_KEY_PREFIX + "testEntityController", BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
}

From source file:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/new", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String createAppointment(Model model,
        @Valid @ModelAttribute("appointment") AppointmentDTO appointmentDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("proceduresOptions", Procedure.values());

        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }// w ww  .  ja v  a 2 s. c  o m

        if (bindingResult.hasGlobalErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError er : bindingResult.getGlobalErrors()) {
                sb.append(er.getDefaultMessage());
                sb.append('\n');
            }

            model.addAttribute("globalError", sb);
        }

        return "appointments/create";
    }
    try {
        appointmentDTO = facade.createAppointment(appointmentDTO);
        Long id = appointmentDTO.getId();

        redirectAttributes.addFlashAttribute("alert_success", "Appointment #" + id + " was created.");
        return "redirect:"
                + uriBuilder.path("/appointments/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile creating: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Appointment was not created.");
        return "redirect:/";
    }
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenPUTWithWrongParams_returnBadRequest() throws Exception {
    BindingResult bindingResult;
    MvcResult result;//from  ww w .  j  a  v  a  2  s. c o  m

    result = mvc.perform(put("/entity/1")
            //Not posting firstName a @NotNull param
            .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(firstName), notNullValue());

    result = mvc.perform(put("/entity/1").param(firstName, firstName)
            //Not posting lastName a different @NotNull param
            .param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(lastName), notNullValue());
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenPOSTWithWrongParams_returnBadRequest() throws Exception {
    BindingResult bindingResult;
    MvcResult result;/*from ww w  .  j  a v a2  s .com*/

    result = mvc.perform(post("/entity").param("id", "1")//@Id should be null on POSTs
            .param(firstName, firstName).param(lastName, lastName).param(testDateKey, testDate))
            .andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    assertThat(bindingResult.getFieldError("id"), notNullValue());

    result = mvc.perform(post("/entity")
            //Not posting firstName a @NotNull param
            .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(firstName), notNullValue());

    result = mvc.perform(post("/entity").param(firstName, firstName)
            //Not posting lastName a different @NotNull param
            .param(testDateKey, testDate)).andExpect(status().isBadRequest())
            .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue())))
            .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit"))
            .andReturn();

    bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME,
            BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
    assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class));
    //Missing params should be binded to its own field name
    assertThat(bindingResult.getFieldError(lastName), notNullValue());
}

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  w  w.  j a va2 s . c  o m*/
            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:fragment.web.RegistrationControllerTest.java

@Test
public void testRegisterPostCaptchaFail() throws Exception {
    MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/signup");
    mockRequest.setRemoteAddr("1.1.1.1");
    User user = new User("test", "test", "testtest.com", "testuser", VALID_PASSWORD, VALID_PHONE,
            VALID_TIMEZONE, null, null, getRootUser());
    user.setAddress(randomAddress());/*from w  w  w.  ja  v a 2 s .c om*/
    Tenant newTenant = new Tenant("New Co", accountTypeDAO.getDefaultRegistrationAccountType(), null,
            randomAddress(), true, currencyValueService.locateBYCurrencyCode("USD"), null);
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setUser((com.citrix.cpbm.access.User) CustomProxy.newInstance(user));
    registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(newTenant));
    BindingResult result = new BindException(registration, "registration");
    beforeRegisterCall(mockRequest, registration);
    String view = controller.register(registration, result, "abc", "CAPTCHA_FAIL", map, "1", status,
            mockRequest);
    Assert.assertEquals("register.moreuserinfo", view);
    Assert.assertFalse(status.isComplete());
    Assert.assertTrue(result.hasGlobalErrors());
    Assert.assertTrue(result.getGlobalErrorCount() == 1);
    Assert.assertEquals("errors.registration.captcha", result.getGlobalError().getCode());
    Assert.assertEquals("captcha.error", map.get("registrationError"));
}