org.springframework.validation.ObjectError Java Examples

The following examples show how to use org.springframework.validation.ObjectError. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidationErrorTest.java    From waggle-dance with Apache License 2.0 7 votes vote down vote up
@Test
public void multipleBuilderErrors() {
  ObjectError objectError1 = new ObjectError("errorOne", "Description one");
  ObjectError objectError2 = new ObjectError("errorTwo", "Description two");

  List<ObjectError> objectErrors = Arrays.asList(objectError1, objectError2);

  when(errors.getErrorCount()).thenReturn(objectErrors.size());
  when(errors.getAllErrors()).thenReturn(objectErrors);

  ValidationError result = ValidationError.builder(errors).build();

  List<String> expected = Arrays.asList(objectError1.getDefaultMessage(), objectError2.getDefaultMessage());

  assertThat(result.getErrors(), is(expected));
  assertThat(result.getErrorMessage(), is("Validation failed: 2 error(s)"));
}
 
Example #2
Source File: LinksAdminController.java    From FlyCms with MIT License 6 votes vote down vote up
@ResponseBody
@PostMapping(value = "/update_links")
public DataVo updateFriendLink(@Valid Links links, BindingResult result) {
	DataVo data = DataVo.failure("操作失败");
       try {
           if (result.hasErrors()) {
               List<ObjectError> list = result.getAllErrors();
               for (ObjectError error : list) {
                   return DataVo.failure(error.getDefaultMessage());
               }
               return null;
           }
           if (!NumberUtils.isNumber(links.getId().toString())) {
               return DataVo.failure("友情链接ID参数错误!");
           }
           links.setLinkName(links.getLinkName().trim());
           links.setLinkUrl(links.getLinkUrl().trim());
           data = linksService.updateLinksById(links);
       } catch (Exception e) {
           data = DataVo.failure(e.getMessage());
           log.warn(e.getMessage());
       }
	return data;
}
 
Example #3
Source File: ExceptionServiceErrorMapper.java    From chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Maps an exception to an error.
 * 
 * @param ex
 * @return
 */
public static ServiceError mapException(Throwable ex) {
	ServiceError error = null;

       if (ex instanceof ServiceException) {
       	ServiceException servEx = (ServiceException)ex;
       	
       	error = servEx.error;
       } else if (ex instanceof MethodArgumentNotValidException) {
       	MethodArgumentNotValidException validationEx = (MethodArgumentNotValidException)ex;
       	
       	List<String> errors = Lists.newArrayList();
       	
       	for (ObjectError objError : validationEx.getBindingResult().getAllErrors()) {
       		errors.add(objError.getObjectName() + ":" + objError.getCode() + ":" + objError.getDefaultMessage());
       	}
       	
       	error = new ServiceError(VALIDATION_ERROR_CODE, Joiner.on("|").join(errors));
       } else {
       	error = new ServiceError(UNKNOWN_ERROR_CODE, ex.getMessage());
       }
       
       return error;
}
 
Example #4
Source File: ShareController.java    From FlyCms with MIT License 6 votes vote down vote up
@ResponseBody
@PostMapping(value = "/ucenter/share/share_update")
public DataVo editShare(@Valid Share share, BindingResult result){
    DataVo data = DataVo.failure("操作失败");
    if (share.getId() == null) {
        return DataVo.failure("内容id错误!");
    }
    Share shareinfo=shareService.findShareById(share.getId(),0);
    if (getUser().getUserId() != shareinfo.getUserId()) {
        return DataVo.failure("只能修改属于自己的分享内容!");
    }
    try {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                return DataVo.failure(error.getDefaultMessage());
            }
            return null;
        }
        share.setUserId(getUser().getUserId());
        data = shareService.updateShareById(share);
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example #5
Source File: EscapedErrors.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
private <T extends ObjectError> T escapeObjectError(@Nullable T source) {
	if (source == null) {
		return null;
	}
	String defaultMessage = source.getDefaultMessage();
	if (defaultMessage != null) {
		defaultMessage = HtmlUtils.htmlEscape(defaultMessage);
	}
	if (source instanceof FieldError) {
		FieldError fieldError = (FieldError) source;
		Object value = fieldError.getRejectedValue();
		if (value instanceof String) {
			value = HtmlUtils.htmlEscape((String) value);
		}
		return (T) new FieldError(
				fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(),
				fieldError.getCodes(), fieldError.getArguments(), defaultMessage);
	}
	else {
		return (T) new ObjectError(
				source.getObjectName(), source.getCodes(), source.getArguments(), defaultMessage);
	}
}
 
Example #6
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithAutowiredValidator() {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
			LocalValidatorFactoryBean.class);
	LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

	ValidPerson person = new ValidPerson();
	person.expectsAutowiredValidator = true;
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
	ctx.close();
}
 
Example #7
Source File: ProblemExceptionResponseGenerator.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void buildProblemErrorConstraintViolation(
    ObjectError objectError, Error.Builder builder) {
  String detail = null;
  String detailCode = null;

  String[] codes = objectError.getCodes();
  if (codes != null) {
    for (String code : codes) {
      String message = contextMessageSource.getMessage(code, objectError.getArguments());
      if (message != null && !message.equals('#' + code + '#')) {
        detail = message;
        detailCode = code;
        break;
      }
    }
  }

  if (detail == null) {
    detail = objectError.getDefaultMessage();
    if (detail == null) {
      detail = contextMessageSource.getMessage("org.molgenis.web.exception.ObjectError.generic");
    }
  }
  builder.setDetail(detail);
  builder.setErrorCode(detailCode != null ? detailCode : objectError.getCode());
}
 
Example #8
Source File: BaseController.java    From WeBASE-Transaction with Apache License 2.0 6 votes vote down vote up
/**
 * Parameters check message format.
 * 
 * @param bindingResult checkResult
 * @return
 */
private String getParamValidFaildMessage(BindingResult bindingResult) {
    List<ObjectError> errorList = bindingResult.getAllErrors();
    log.info("errorList:{}", JsonUtils.toJSONString(errorList));
    if (errorList == null) {
        log.warn("onWarning:errorList is empty!");
        return null;
    }

    ObjectError objectError = errorList.get(0);
    if (objectError == null) {
        log.warn("onWarning:objectError is empty!");
        return null;
    }
    return objectError.getDefaultMessage();
}
 
Example #9
Source File: TaskDefineController.java    From batch-scheduler with MIT License 6 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public String update(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    RetMsg retMsg = taskDefineService.update(parse(request));
    if (!retMsg.checkCode()) {
        response.setStatus(retMsg.getCode());
        return Hret.error(retMsg);
    }
    return Hret.success(retMsg);
}
 
Example #10
Source File: ShareAdminController.java    From FlyCms with MIT License 6 votes vote down vote up
@PostMapping("/category_edit_save")
@ResponseBody
public DataVo editCategory(@Valid ShareCategory shareCategory, BindingResult result){
    DataVo data = DataVo.failure("操作失败");
    try {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                return DataVo.failure(error.getDefaultMessage());
            }
            return null;
        }
        data = shareCategoryService.editShareCategory(shareCategory);
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example #11
Source File: PopupsArgumentResolver.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mav, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
    Popups popups = initializePopups(mav.getDefaultModel(), nativeWebRequest.getNativeRequest(HttpServletRequest.class));

    for (BindingResult result : getBindingResult(mav)) {
        for (ObjectError error : result.getAllErrors()) {
            Message message = asMessage(error);

            if (error instanceof FieldError) {
                popups.field(((FieldError) error).getField(), message);
            } else {
                popups.alert(message);
            }
        }
    }

    return popups;
}
 
Example #12
Source File: GlobalControllerAdvice.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleMethodArgumentNotValid(MethodArgumentNotValidException ex
) {
	List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
	List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
	List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
	String error;
	for (FieldError fieldError : fieldErrors) {
		error = fieldError.getField() + ", " + fieldError.getDefaultMessage();
		errors.add(error);
	}
	for (ObjectError objectError : globalErrors) {
		error = objectError.getObjectName() + ", " + objectError.getDefaultMessage();
		errors.add(error);
	}
	ErrorMessage errorMessage = new ErrorMessage(errors);

	//Object result=ex.getBindingResult();//instead of above can allso pass the more detailed bindingResult
	return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
}
 
Example #13
Source File: TdsErrorHandling.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ExceptionHandler(BindException.class)
public ResponseEntity<String> handle(BindException ex) {
  BindingResult validationResult = ex.getBindingResult();
  List<ObjectError> errors = validationResult.getAllErrors();
  Formatter f = new Formatter();
  f.format("Validation errors: ");
  for (ObjectError err : errors) {
    f.format(" %s%n", err.getDefaultMessage());
  }

  logger.warn(f.toString(), ex);

  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(MediaType.TEXT_PLAIN);
  return new ResponseEntity<>(f.toString(), responseHeaders, HttpStatus.BAD_REQUEST);
}
 
Example #14
Source File: WebExchangeBindExceptionHandler.java    From staccato with Apache License 2.0 6 votes vote down vote up
@Override
protected String getMessage(WebExchangeBindException ex) {
    List<ObjectError> errors = ex.getAllErrors();
    if (!errors.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        Iterator<ObjectError> it = errors.iterator();
        while (it.hasNext()) {
            sb.append(it.next().getDefaultMessage());
            if (it.hasNext()) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }
    return ex.getMessage();
}
 
Example #15
Source File: FuncionarioController.java    From ponto-inteligente-api with MIT License 6 votes vote down vote up
/**
 * Atualiza os dados de um funcionário.
 * 
 * @param id
 * @param funcionarioDto
 * @param result
 * @return ResponseEntity<Response<FuncionarioDto>>
 * @throws NoSuchAlgorithmException
 */
@PutMapping(value = "/{id}")
public ResponseEntity<Response<FuncionarioDto>> atualizar(@PathVariable("id") Long id,
		@Valid @RequestBody FuncionarioDto funcionarioDto, BindingResult result) throws NoSuchAlgorithmException {
	log.info("Atualizando funcionário: {}", funcionarioDto.toString());
	Response<FuncionarioDto> response = new Response<FuncionarioDto>();

	Optional<Funcionario> funcionario = this.funcionarioService.buscarPorId(id);
	if (!funcionario.isPresent()) {
		result.addError(new ObjectError("funcionario", "Funcionário não encontrado."));
	}

	this.atualizarDadosFuncionario(funcionario.get(), funcionarioDto, result);

	if (result.hasErrors()) {
		log.error("Erro validando funcionário: {}", result.getAllErrors());
		result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage()));
		return ResponseEntity.badRequest().body(response);
	}

	this.funcionarioService.persistir(funcionario.get());
	response.setData(this.converterFuncionarioDto(funcionario.get()));

	return ResponseEntity.ok(response);
}
 
Example #16
Source File: JobAdminController.java    From FlyCms with MIT License 6 votes vote down vote up
/**
 * 更新任务
 * @param job
 * @return
 */
@ResponseBody
@PostMapping(value = "/update_job")
public DataVo update(@Valid Job job, BindingResult result) {
    DataVo data = DataVo.failure("操作失败");
    try {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                return DataVo.failure(error.getDefaultMessage());
            }
            return null;
        }
        data = jobService.updateJobById(job);
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
        log.warn(e.getMessage());
    }
    return data;
}
 
Example #17
Source File: ResourceServerPropertiesTests.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
private BaseMatcher<BindException> getMatcher(String message, String field) {
	return new BaseMatcher<BindException>() {

		@Override
		public void describeTo(Description description) {

		}

		@Override
		public boolean matches(Object item) {
			BindException ex = (BindException) ((Exception) item).getCause();
			ObjectError error = ex.getAllErrors().get(0);
			boolean messageMatches = message.equals(error.getDefaultMessage());
			if (field == null) {
				return messageMatches;
			}
			String fieldErrors = ((FieldError) error).getField();
			return messageMatches && fieldErrors.equals(field);
		}

	};
}
 
Example #18
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithClassLevel() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
}
 
Example #19
Source File: GlobalControllerAdvice.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleMethodArgumentNotValid(MethodArgumentNotValidException ex
) {
	List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
	List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
	List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
	String error;
	for (FieldError fieldError : fieldErrors) {
		error = fieldError.getField() + ", " + fieldError.getDefaultMessage();
		errors.add(error);
	}
	for (ObjectError objectError : globalErrors) {
		error = objectError.getObjectName() + ", " + objectError.getDefaultMessage();
		errors.add(error);
	}
	ErrorMessage errorMessage = new ErrorMessage(errors);

	//Object result=ex.getBindingResult();//instead of above can allso pass the more detailed bindingResult
	return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
}
 
Example #20
Source File: ValidationProblem.java    From nakadi with MIT License 6 votes vote down vote up
private String buildErrorMessage() {
    final StringBuilder detailBuilder = new StringBuilder();

    for (final ObjectError error : errors.getAllErrors()) {
        if (error instanceof FieldError) {
            final String fieldName = CaseFormat.UPPER_CAMEL.
                    to(CaseFormat.LOWER_UNDERSCORE, ((FieldError) error).getField());

            detailBuilder.
                    append("Field \"").
                    append(fieldName).
                    append("\" ").
                    append(error.getDefaultMessage()).
                    append("\n");
        } else {
            detailBuilder.append(error.toString());
        }
    }

    return detailBuilder.toString();
}
 
Example #21
Source File: GlobalControllerAdvice.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleMethodArgumentNotValid(MethodArgumentNotValidException ex
) {
	List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
	List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
	List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
	String error;
	for (FieldError fieldError : fieldErrors) {
		error = fieldError.getField() + ", " + fieldError.getDefaultMessage();
		errors.add(error);
	}
	for (ObjectError objectError : globalErrors) {
		error = objectError.getObjectName() + ", " + objectError.getDefaultMessage();
		errors.add(error);
	}
	ErrorMessage errorMessage = new ErrorMessage(errors);

	//Object result=ex.getBindingResult();//instead of above can allso pass the more detailed bindingResult
	return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
}
 
Example #22
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleException_handles_WebExchangeBindException_as_expected() {
    // given
    BindingResult bindingResult = mock(BindingResult.class);

    ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError();
    ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError();
    ApiError notAFieldError = testProjectApiErrors.getGenericBadRequestApiError();
    List<ObjectError> errorsList = Arrays.asList(
        new FieldError("someObj", "someField", someFieldError.getName()),
        new FieldError("otherObj", "otherField", otherFieldError.getName()),
        new ObjectError("notAFieldObject", notAFieldError.getName())
    );
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    WebExchangeBindException ex = new WebExchangeBindException(null, bindingResult);

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    validateResponse(result, true, Arrays.asList(
        new ApiErrorWithMetadata(someFieldError, Pair.of("field", "someField")),
        new ApiErrorWithMetadata(otherFieldError, Pair.of("field", "otherField")),
        notAFieldError
    ));
    verify(bindingResult).getAllErrors();
}
 
Example #23
Source File: ContentModelServiceImplTest.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test(expected = ValidationConflictException.class)
public void shoudlFailDeletingContentModelWithDefaultModelListTemplate() {
    when(contentManager.getSmallEntityTypes()).thenReturn(mockedEntityTypes);
    when(contentManager.getListModel("BBB")).thenReturn("2");
    try {
        contentModelService.delete(2L);
    } catch (ValidationConflictException ex) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        assertThat(errors).isNotNull().hasSize(1);
        assertThat(errors.get(0).getCode()).isEqualTo(ContentModelValidator.ERRCODE_CONTENTMODEL_METADATA_REFERENCES);
        throw ex;
    }
}
 
Example #24
Source File: BindStatus.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Extract the error codes from the ObjectError list.
 */
private static String[] initErrorCodes(List<? extends ObjectError> objectErrors) {
	String[] errorCodes = new String[objectErrors.size()];
	for (int i = 0; i < objectErrors.size(); i++) {
		ObjectError error = objectErrors.get(i);
		errorCodes[i] = error.getCode();
	}
	return errorCodes;
}
 
Example #25
Source File: LoginController.java    From Resource with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping("login.jsp")
public RespResult login(@Valid LoginVO loginVO, BindingResult bindingResult, Model mode)
{
    if(bindingResult.hasErrors())
    {
        for (ObjectError error : bindingResult.getAllErrors())
        {
            return RespResult.failure(error.getDefaultMessage());
        }
    }
    return RespResult.success("验证成功");

}
 
Example #26
Source File: RestExceptionHandler.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
 * Hibernate validator Exception
 */
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

    BindingResult result = ex.getBindingResult();

    List<FieldError> fieldErrors = result.getFieldErrors();
    List<ObjectError> globalErrors = result.getGlobalErrors();
    ServiceError serviceError = ServiceError.FORM_VALIDATION_FAILED;

    Map<String, String> fields = new HashMap<>();

    globalErrors.forEach(
            error -> fields.put("global_" + error.getCode(), error.getDefaultMessage())
    );

    fieldErrors.forEach(
            error -> fields.put(error.getField() + "_" + error.getCode(), error.getDefaultMessage())
    );

    RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError, fields);

    try {
        log.warn(ObjectMapperUtils.writeValueAsString(restErrorResponse), ex);
    } catch (JsonProcessingException ignore) {
        log.warn(ex.getLocalizedMessage(), ex);
    }

    return new ResponseEntity<>(restErrorResponse, HttpStatus.valueOf(serviceError.getHttpStatus()));
}
 
Example #27
Source File: WebExchangeBindException.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Returns diagnostic information about the errors held in this object.
 */
@Override
public String getMessage() {
	MethodParameter parameter = getMethodParameter();
	Assert.state(parameter != null, "No MethodParameter");
	StringBuilder sb = new StringBuilder("Validation failed for argument at index ")
			.append(parameter.getParameterIndex()).append(" in method: ")
			.append(parameter.getExecutable().toGenericString())
			.append(", with ").append(this.bindingResult.getErrorCount()).append(" error(s): ");
	for (ObjectError error : this.bindingResult.getAllErrors()) {
		sb.append("[").append(error).append("] ");
	}
	return sb.toString();
}
 
Example #28
Source File: NewAccountControllerTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Test
public void create_ConfirmPasswordNotSpecified() {
	final Model model = createNiceMock(Model.class);
	final UserForm User = new UserForm();
	final BindingResult errors = createNiceMock(BindingResult.class);
	final String username = "usename";
	final String password = "pasword";
	final String confirmPassword = ""; //confirm password not specified
	List<ObjectError> errorList = new ArrayList<ObjectError>();

	User.setUsername(username);
	User.setPassword(password);
	User.setConfirmPassword(confirmPassword);

	errorList.add(new ObjectError("confirmPassword.required", "Confirm password required"));

	expect(errors.hasErrors()).andReturn(true).anyTimes();
	expect(errors.getAllErrors()).andReturn(errorList).anyTimes();
	replay(errors);

       replay(model);
	String result = newAccountController.create(User, errors, model, request, redirectAttributes);
	errorList = errors.getAllErrors();

	assertThat(errorList.size(), CoreMatchers.equalTo(1));
	assertThat(errorList.get(0).getDefaultMessage(), CoreMatchers.equalTo("Confirm password required"));
	assertThat(result, CoreMatchers.equalTo(ViewNames.NEW_ACCOUNT));
}
 
Example #29
Source File: EscapedErrors.java    From java-technology-stack with MIT License 5 votes vote down vote up
private <T extends ObjectError> List<T> escapeObjectErrors(List<T> source) {
	List<T> escaped = new ArrayList<>(source.size());
	for (T objectError : source) {
		escaped.add(escapeObjectError(objectError));
	}
	return escaped;
}
 
Example #30
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void extractAllErrorsFromWebExchangeBindException_returns_null_if_unexpected_exception_occurs() {
    // when
    List<ObjectError> result = listener.extractAllErrorsFromWebExchangeBindException(new RuntimeException());

    // then
    assertThat(result).isNull();
}