Java Code Examples for javax.validation.ConstraintViolationException#getConstraintViolations()
The following examples show how to use
javax.validation.ConstraintViolationException#getConstraintViolations() .
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: ValidationEndToEndTest.java From crnk-framework with Apache License 2.0 | 6 votes |
@Test public void testListElementAttributeNotNull() { ProjectData data = new ProjectData(); data.setValue(null); // violation Project project = new Project(); project.setId(1L); project.setName("test"); project.getDataList().add(data); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("dataList[0].value", violation.getPropertyPath().toString()); Assert.assertNotNull(violation.getMessage()); Assert.assertEquals("/data/attributes/data-list/0/value", violation.getErrorData().getSourcePointer()); } }
Example 2
Source File: ConstraintViolationExceptionHandler.java From spring-rest-exception-handler with Apache License 2.0 | 6 votes |
@Override public ValidationErrorMessage createBody(ConstraintViolationException ex, HttpServletRequest req) { ErrorMessage tmpl = super.createBody(ex, req); ValidationErrorMessage msg = new ValidationErrorMessage(tmpl); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { Node pathNode = findLastNonEmptyPathNode(violation.getPropertyPath()); // path is probably useful only for properties (fields) if (pathNode != null && pathNode.getKind() == ElementKind.PROPERTY) { msg.addError(pathNode.getName(), convertToString(violation.getInvalidValue()), violation.getMessage()); // type level constraints etc. } else { msg.addError(violation.getMessage()); } } return msg; }
Example 3
Source File: ValidationEndToEndTest.java From crnk-framework with Apache License 2.0 | 6 votes |
@Test public void testPropertyOnRelationId() { ResourceRepository<Schedule, Serializable> scheduleRepo = client.getRepositoryForType(Schedule.class); Project project = new Project(); project.setId(2L); project.setName("test"); Schedule schedule = new Schedule(); schedule.setId(1L); schedule.setName("test"); schedule.setProjectId(null); try { scheduleRepo.create(schedule); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("project", violation.getPropertyPath().toString()); Assert.assertEquals("/data/relationships/project", violation.getErrorData().getSourcePointer()); } }
Example 4
Source File: GlobalControllerAdvice.java From springdoc-openapi with Apache License 2.0 | 6 votes |
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(code = HttpStatus.BAD_REQUEST) public ResponseEntity<ErrorMessage> handleConstraintViolatedException(ConstraintViolationException ex ) { Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations(); List<String> errors = new ArrayList<>(constraintViolations.size()); String error; for (ConstraintViolation constraintViolation : constraintViolations) { error = constraintViolation.getMessage(); errors.add(error); } ErrorMessage errorMessage = new ErrorMessage(errors); return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST); }
Example 5
Source File: GlobalControllerAdvice.java From springdoc-openapi with Apache License 2.0 | 6 votes |
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(code = HttpStatus.BAD_REQUEST) public ResponseEntity<ErrorMessage> handleConstraintViolatedException(ConstraintViolationException ex ) { Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations(); List<String> errors = new ArrayList<>(constraintViolations.size()); String error; for (ConstraintViolation constraintViolation : constraintViolations) { error = constraintViolation.getMessage(); errors.add(error); } ErrorMessage errorMessage = new ErrorMessage(errors); return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST); }
Example 6
Source File: BookResource.java From quarkus-quickstarts with Apache License 2.0 | 5 votes |
@Path("/service-method-validation") @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Result tryMeServiceMethodValidation(Book book) { try { bookService.validateBook(book); return new Result("Book is valid! It was validated by service method validation."); } catch (ConstraintViolationException e) { return new Result(e.getConstraintViolations()); } }
Example 7
Source File: ConstraintViolationExceptionHandler.java From minnal with Apache License 2.0 | 5 votes |
@Override public Response toResponse(ConstraintViolationException exception) { ConstraintViolationException ex = (ConstraintViolationException) exception; List<FieldError> errors = new ArrayList<FieldError>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue())); } Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", errors); return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build(); }
Example 8
Source File: ConstraintViolationExceptionMapper.java From devicehive-java-server with Apache License 2.0 | 5 votes |
@Override public Response toResponse(ConstraintViolationException exception) { Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations(); StringBuilder errors = new StringBuilder(); constraintViolations.forEach(exc -> errors.append(exc.getMessage())); return ResponseFactory.response(BAD_REQUEST, new ErrorResponse(BAD_REQUEST.getStatusCode(), errors.toString())); }
Example 9
Source File: ConstraintValidationExceptionMapper.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
private String prepareMessage(ConstraintViolationException exception) { StringBuilder message = new StringBuilder(); for (ConstraintViolation<?> cv : exception.getConstraintViolations()) { message.append(cv.getMessage()); } return message.toString(); }
Example 10
Source File: JaxrsEndPointValidationInterceptor.java From quarkus with Apache License 2.0 | 5 votes |
@AroundInvoke @Override public Object validateMethodInvocation(InvocationContext ctx) throws Exception { try { return super.validateMethodInvocation(ctx); } catch (ConstraintViolationException e) { throw new ResteasyViolationExceptionImpl(e.getConstraintViolations(), getAccept(ctx.getMethod())); } }
Example 11
Source File: RestExceptionHandler.java From plumemo with Apache License 2.0 | 5 votes |
/** * validation 异常处理 * * @param request 请求体 * @param e ConstraintViolationException * @return HttpResult */ @ExceptionHandler(ConstraintViolationException.class) @ResponseBody public Result onConstraintViolationException(HttpServletRequest request, ConstraintViolationException e) { Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations(); if (!CollectionUtils.isEmpty(constraintViolations)) { String errorMessage = constraintViolations .stream() .map(ConstraintViolation::getMessage) .collect(Collectors.joining(";")); return Result.createWithErrorMessage(errorMessage, ErrorEnum.PARAM_ERROR.getCode()); } return Result.createWithErrorMessage(e.getMessage(), ErrorEnum.PARAM_ERROR.getCode()); }
Example 12
Source File: RestExceptionAdvice.java From EasyChatServer with Apache License 2.0 | 5 votes |
@ExceptionHandler(ConstraintViolationException.class) public Result<?> handler(ConstraintViolationException e) { Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations(); List<String> fieldList = new ArrayList<>(); if (log.isDebugEnabled()) { constraintViolations.forEach(f -> { fieldList.add(f.getPropertyPath().toString()); log.debug("field format error: " + toString()); }); } return Result.fail(ResultCode.PARAM_INVALID, fieldList); }
Example 13
Source File: ApiExceptionHandler.java From tutorials with MIT License | 5 votes |
@SuppressWarnings("rawtypes") @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<ErrorResponse> handle(ConstraintViolationException e) { ErrorResponse errors = new ErrorResponse(); for (ConstraintViolation violation : e.getConstraintViolations()) { ErrorItem error = new ErrorItem(); error.setCode(violation.getMessageTemplate()); error.setMessage(violation.getMessage()); errors.addError(error); } return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); }
Example 14
Source File: RpcExceptionMapper.java From dubbox with Apache License 2.0 | 5 votes |
protected Response handleConstraintViolationException(ConstraintViolationException cve) { ViolationReport report = new ViolationReport(); for (ConstraintViolation cv : cve.getConstraintViolations()) { report.addConstraintViolation(new RestConstraintViolation( cv.getPropertyPath().toString(), cv.getMessage(), cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); } // TODO for now just do xml output return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build(); }
Example 15
Source File: GlobalExceptionHandler.java From BigDataPlatform with GNU General Public License v3.0 | 5 votes |
@ExceptionHandler(ValidationException.class) @ResponseBody public Object badArgumentHandler(ValidationException e) { logger.error(e.getMessage(), e); if (e instanceof ConstraintViolationException) { ConstraintViolationException exs = (ConstraintViolationException) e; Set<ConstraintViolation<?>> violations = exs.getConstraintViolations(); for (ConstraintViolation<?> item : violations) { String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage(); return ResponseUtil.fail(402, message); } } return ResponseUtil.badArgumentValue(); }
Example 16
Source File: RpcExceptionMapper.java From dubbox-hystrix with Apache License 2.0 | 5 votes |
protected Response handleConstraintViolationException(ConstraintViolationException cve) { ViolationReport report = new ViolationReport(); for (ConstraintViolation cv : cve.getConstraintViolations()) { report.addConstraintViolation(new RestConstraintViolation( cv.getPropertyPath().toString(), cv.getMessage(), cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); } // TODO for now just do xml output return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build(); }
Example 17
Source File: ValidationResponse.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
public ValidationResponse(final ConstraintViolationException cause) { super(false, new ArrayList<>()); //noinspection ThrowableResultOfMethodCallIgnored checkNotNull(cause); Set<ConstraintViolation<?>> violations = cause.getConstraintViolations(); if (violations != null && !violations.isEmpty()) { for (ConstraintViolation<?> violation : violations) { List<String> entries = new ArrayList<>(); // iterate path to get the full path Iterator<Node> it = violation.getPropertyPath().iterator(); while (it.hasNext()) { Node node = it.next(); if (ElementKind.PROPERTY == node.getKind() || (ElementKind.PARAMETER == node.getKind() && !it.hasNext())) { if (node.getKey() != null) { entries.add(node.getKey().toString()); } entries.add(node.getName()); } } if (entries.isEmpty()) { if (messages == null) { messages = new ArrayList<>(); } messages.add(violation.getMessage()); } else { if (errors == null) { errors = new HashMap<>(); } errors.put(Joiner.on('.').join(entries), violation.getMessage()); } } } else if (cause.getMessage() != null) { messages = new ArrayList<>(); messages.add(cause.getMessage()); } }
Example 18
Source File: InstallationDaoTest.java From aerogear-unifiedpush-server with Apache License 2.0 | 5 votes |
@Test public void shouldValidateDeviceId() { // given final Installation installation = new Installation(); installation.setDeviceToken("invalid"); final iOSVariant variant = new iOSVariant(); variant.setName("iOS Variant Name"); variant.setPassphrase("12"); variant.setProduction(false); variant.setCertificate("12".getBytes()); entityManager.persist(variant); installation.setVariant(variant); // when installationDao.create(installation); try { entityManager.flush(); fail("ConstraintViolationException should have been thrown"); } catch (ConstraintViolationException violationException) { // then final Set<ConstraintViolation<?>> constraintViolations = violationException .getConstraintViolations(); assertThat(constraintViolations).isNotEmpty(); assertThat(constraintViolations.size()).isEqualTo(1); assertThat(constraintViolations.iterator().next().getMessage()).isEqualTo( "Device token is not valid for this device type"); } }
Example 19
Source File: ValidationEndToEndTest.java From crnk-framework with Apache License 2.0 | 5 votes |
@Test public void testSetElementAttributeNotNull() { Project project = new Project(); project.setId(1L); project.setName("test"); // ProjectData corrupedElement = null; for (int i = 0; i < 11; i++) { ProjectData data = new ProjectData(); if (i != 3) { data.setValue(Integer.toString(i)); // corrupedElement = data; } project.getDataSet().add(data); } try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertTrue(violation.getPropertyPath().toString().startsWith("dataSet[")); Assert.assertTrue(violation.getPropertyPath().toString().endsWith("].value")); Assert.assertTrue(violation.getErrorData().getSourcePointer().startsWith("/data/attributes/dataSet/")); // TODO attempt to preserver order in Crnk by comparing incoming request, sourcePointer and server Set // or use of order preserving sets // List<ProjectData> list = new ArrayList<>(project.getDataSet()); // int index = list.indexOf(corrupedElement); // Assert.assertEquals(violation.getErrorData().getSourcePointer(), "/data/attributes/dataSet/" + index + // "/value"); } }
Example 20
Source File: ControllerAdviceHandler.java From common-project with Apache License 2.0 | 5 votes |
@ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.OK) public Object handle(Exception exception) { logger.error("错误信息 ==== "+exception.getMessage()); if (exception instanceof BindException) { BindException bindException = (BindException) exception; List<FieldError> fieldErrors = bindException.getFieldErrors(); for (FieldError fieldError : fieldErrors) { return ResponseMessage.error(10010,fieldError.getField() + fieldError.getDefaultMessage()); } } if (exception instanceof ConstraintViolationException) { ConstraintViolationException exs = (ConstraintViolationException) exception; Set<ConstraintViolation<?>> violations = exs.getConstraintViolations(); for (ConstraintViolation<?> violation : violations) { return ResponseMessage.error(10010,violation.getPropertyPath() + violation.getMessage()); } } if (exception instanceof HandlerException) { HandlerException handlerException = (HandlerException) exception; return new ResponseMessage(handlerException.getCode(), handlerException.getErrorInfo()); } if (exception instanceof MissingServletRequestParameterException) { MissingServletRequestParameterException missingServletRequestParameterException = (MissingServletRequestParameterException) exception; return ResponseMessage.error(10010, "请求参数" + missingServletRequestParameterException.getParameterName() + "不能为空"); } if (exception instanceof FileUploadException) { FileUploadException fileUploadException = (FileUploadException) exception; return ResponseMessage.error(10010, fileUploadException.getMessage()); } return ResponseMessage.error(0, "服务异常"); }