Example usage for org.springframework.validation BindingResult getFieldErrorCount

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

Introduction

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

Prototype

int getFieldErrorCount();

Source Link

Document

Return the number of errors associated with a field.

Usage

From source file:com.pw.ism.controllers.CommunicationController.java

@RequestMapping(value = "/newmessage", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
public ResponseEntity<String> newReport(@Valid @RequestBody AsiNetworkReport report,
        BindingResult bindingResults) {

    if (bindingResults.hasErrors()) {
        LOGGER.info("JSON not correct, BADREQUEST! Count: {}", bindingResults.getFieldErrorCount());
        return new ResponseEntity<>("NOK!", HttpStatus.BAD_REQUEST);
    } else {//w ww  .  ja v  a 2 s  .  co  m
        LOGGER.info("new post for message, customer: {}, network: {}, text: {}, sensor: {}", new Object[] {
                report.getCustomer(), report.getNetwork(), report.getText(), report.getSensor() });
        Message message = new Message(report.getCustomer(), report.getNetwork(),
                "Sensor ID: " + report.getSensor() + " Message: " + report.getText());
        messageRepository.save(message);
        return new ResponseEntity<>("OK", HttpStatus.OK);
    }

}

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.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenPUTWithWrongParams_returnBadRequest() throws Exception {
    BindingResult bindingResult;
    MvcResult result;// w  ww . j av a  2s .co 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   www. j a v a  2  s.  c o  m

    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:fragment.web.RegistrationControllerTest.java

@Test
public void testRegisterNotAcceptedTerms() throws Exception {
    MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    AccountType disposition = accountTypeDAO.getOnDemandPostPaidAccountType();
    BindingResult result = setupRegistration(disposition, registration);
    beforeRegisterCall(mockRequest, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, mockRequest);
    Assert.assertEquals("register.moreuserinfo", view);
    Assert.assertFalse(status.isComplete());
    Assert.assertTrue(result.hasFieldErrors());
    Assert.assertTrue(result.getFieldErrorCount() == 1);
    Assert.assertEquals("AssertTrue", result.getFieldError("acceptedTerms").getCode());
}