本文整理汇总了Java中javax.validation.ConstraintViolationException.getConstraintViolations方法的典型用法代码示例。如果您正苦于以下问题:Java ConstraintViolationException.getConstraintViolations方法的具体用法?Java ConstraintViolationException.getConstraintViolations怎么用?Java ConstraintViolationException.getConstraintViolations使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.validation.ConstraintViolationException
的用法示例。
在下文中一共展示了ConstraintViolationException.getConstraintViolations方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: jsr349ObjectInvalid
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
/**
* Check validation errors success for collections.
*/
@Test
public void jsr349ObjectInvalid() {
try {
final SystemUser userDto = new SystemUser();
userDto.setLogin("junit");
validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("jsr349Object"), Arrays.asList(new Object[] { null }));
Assert.fail("Expected validation errors");
} catch (final ConstraintViolationException cve) {
// Check all expected errors are there.
final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations();
Assert.assertNotNull(constraintViolations);
Assert.assertEquals(1, constraintViolations.size());
// Check expected errors
final ConstraintViolation<?> error1 = constraintViolations.iterator().next();
Assert.assertEquals(NotNull.class, error1.getConstraintDescriptor().getAnnotation().annotationType());
Assert.assertEquals("jsr349Object.p", error1.getPropertyPath().toString());
}
}
示例2: processValidationError
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
/**
* @param ex {@link ConstraintViolationException}
* @return Returns an object with a list of incorrect parameters.
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ValidationErrorDTO processValidationError(final ConstraintViolationException ex) {
final ValidationErrorDTO validationErrorDTO = new ValidationErrorDTO();
final Set<ConstraintViolation<?>> set = ex.getConstraintViolations();
for (Iterator<ConstraintViolation<?>> iterator = set.iterator();iterator.hasNext(); ) {
ConstraintViolation<?> next = iterator.next();
validationErrorDTO.getFieldErrors()
.add(new ErrorFieldDTO(((PathImpl)next.getPropertyPath()).getLeafNode().getName(),
next.getMessage()));
}
return validationErrorDTO;
}
示例3: handleConstraintViolation
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
private void handleConstraintViolation(ConstraintViolationException violationException){
Set<ConstraintViolation<?>> violationSet = violationException.getConstraintViolations();
String[] messages = new String[violationSet.size()];
int i = 0;
for(ConstraintViolation violation: violationSet){
messages[i] = violation.getMessage();
i++;
}
Gson gson = appContext.getGsonBuilder().create();
Map details = new HashMap<>();
details.put("messages",messages);
Map exception = new HashMap<>();
exception.put("type",ConstraintViolationException.class.getSimpleName());
exception.put("details",details);
String resp = gson.toJson(exception);
requestContext.getResponse().setStatus(500);
requestContext.getResponse().setContentType("text/json;charset=UTF8");
requestContext.echo(resp);
}
示例4: testPropertyNotNull
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@Test
public void testPropertyNotNull() {
Project project = new Project();
project.setId(1L);
project.setName(null); // violation
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("name", violation.getPropertyPath().toString());
Assert.assertNotNull(violation.getMessage());
Assert.assertTrue(violation.getMessage().contains("null"));
Assert.assertEquals("/data/attributes/name", violation.getErrorData().getSourcePointer());
}
}
示例5: testListAttribute
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@Test
public void testListAttribute() {
Project project = new Project();
project.setId(1L);
project.setName("test");
project.getKeywords().add("1");
project.getKeywords().add("2");
project.getKeywords().add("3");
project.getKeywords().add("4");
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.Size.message}", violation.getMessageTemplate());
Assert.assertEquals("keywords", violation.getPropertyPath().toString());
// message depends on local
Assert.assertNotNull(violation.getMessage());
Assert.assertTrue(violation.getMessage().contains("0"));
Assert.assertTrue(violation.getMessage().contains("3"));
Assert.assertEquals("/data/attributes/keywords", violation.getErrorData().getSourcePointer());
}
}
示例6: testNestedPropertyNotNull
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@Test
public void testNestedPropertyNotNull() {
ProjectData data = new ProjectData();
data.setValue(null); // violation
Project project = new Project();
project.setId(1L);
project.setName("test");
project.setData(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("data.value", violation.getPropertyPath().toString());
Assert.assertEquals("/data/attributes/data/value", violation.getErrorData().getSourcePointer());
}
}
示例7: jsr349CollectionInvalid
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
/**
* Check validation errors success for collections.
*/
@Test
public void jsr349CollectionInvalid() {
try {
final SystemUser userDto = new SystemUser();
userDto.setLogin("junit");
validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("jsr349Collection"),
Arrays.asList(Arrays.asList(userDto, userDto, userDto)));
Assert.fail("Expected validation errors");
} catch (final ConstraintViolationException cve) {
// Check all expected errors are there.
final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations();
Assert.assertNotNull(constraintViolations);
Assert.assertEquals(1, constraintViolations.size());
// Check expected errors
final ConstraintViolation<?> error1 = constraintViolations.iterator().next();
Assert.assertEquals(Size.class, error1.getConstraintDescriptor().getAnnotation().annotationType());
Assert.assertEquals("jsr349Collection.params", error1.getPropertyPath().toString());
}
}
示例8: objectInvalid
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
/**
* Check not valid parameter operation failed.
*/
@Test
public void objectInvalid() {
final SystemUser userDto = new SystemUser();
userDto.setLogin("");
try {
validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("object"), Arrays.asList(userDto));
Assert.fail("Expected validation errors");
} catch (final ConstraintViolationException cve) {
// Check all expected errors are there.
final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations();
Assert.assertNotNull(constraintViolations);
Assert.assertEquals(1, constraintViolations.size());
// Check expected errors
final ConstraintViolation<?> error1 = constraintViolations.iterator().next();
Assert.assertEquals(NotEmpty.class, error1.getConstraintDescriptor().getAnnotation().annotationType());
Assert.assertEquals("", error1.getInvalidValue());
Assert.assertEquals("login", error1.getPropertyPath().toString());
}
}
示例9: jsr349SimpleInvalid
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@Test
public void jsr349SimpleInvalid() {
try {
validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("jsr349Simple"), Arrays.asList(new Object[] { null }));
Assert.fail("Expected validation errors");
} catch (final ConstraintViolationException cve) {
// Check all expected errors are there.
final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations();
Assert.assertNotNull(constraintViolations);
Assert.assertEquals(1, constraintViolations.size());
// Check expected errors
final ConstraintViolation<?> error1 = constraintViolations.iterator().next();
Assert.assertEquals(NotNull.class, error1.getConstraintDescriptor().getAnnotation().annotationType());
Assert.assertEquals("jsr349Simple.param", error1.getPropertyPath().toString());
}
}
示例10: toResponse
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@Override
public Response toResponse(ConstraintViolationException ex) {
ResultStash.Builder builder = ResultStash.builder().setStatus(Response.Status.PRECONDITION_FAILED);
for (ConstraintViolation<?> v : ex.getConstraintViolations()) {
// Add all violations to the response.
String value = ObjectUtils.ifNotNull(v.getInvalidValue(), Object::toString, "NULL");
builder.addFieldError(v.getMessage(), v.getMessageTemplate(), printPropertyPath(v.getPropertyPath()), value);
}
return builder.buildResponse();
}
示例11: toErrorResponse
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@Override
public ErrorResponse toErrorResponse(ConstraintViolationException cve) {
LOGGER.warn("a ConstraintViolationException occured", cve);
List<ErrorData> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
ErrorDataBuilder builder = ErrorData.builder();
builder = builder.addMetaField(META_TYPE_KEY, META_TYPE_VALUE);
builder = builder.setStatus(String.valueOf(HttpStatus.UNPROCESSABLE_ENTITY_422));
builder = builder.setDetail(violation.getMessage());
builder = builder.setCode(toCode(violation));
if (violation.getMessageTemplate() != null) {
builder = builder.addMetaField(META_MESSAGE_TEMPLATE, violation.getMessageTemplate());
}
// for now we just provide root resource validation information
// depending on bulk update spec, we might also provide the leaf information in the future
if (violation.getRootBean() != null) {
ResourceRef resourceRef = resolvePath(violation);
builder = builder.addMetaField(META_RESOURCE_ID, resourceRef.getRootResourceId());
builder = builder.addMetaField(META_RESOURCE_TYPE, resourceRef.getRootResourceType());
builder = builder.setSourcePointer(resourceRef.getRootSourcePointer());
}
ErrorData error = builder.build();
errors.add(error);
}
return ErrorResponse.builder().setStatus(HttpStatus.UNPROCESSABLE_ENTITY_422).setErrorData(errors).build();
}
示例12: constraintViolationExceptionHandler
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public ErrorRes constraintViolationExceptionHandler(HttpServletResponse response, ConstraintViolationException e) {
response.setStatus(400);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
if (!violations.isEmpty()) {
ConstraintViolation<?> violation = violations.iterator().next();
return new ErrorRes(-1, violation.getPropertyPath().toString() + violation.getMessage());
}
return new ErrorRes();
}
示例13: handleConstraintViolationException
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
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();
}
示例14: handleException
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler({ConstraintViolationException.class})
public Map<String, String> handleException(ConstraintViolationException e) {
StringBuilder message = new StringBuilder();
for (ConstraintViolation<?> s : e.getConstraintViolations()) {
message.append(s.getMessage()).append(" ");
}
log.warn("参数校验失败: {}", message.toString());
return ImmutableMap.of("code", "1911001", "message", message.toString());
}
示例15: toResponse
import javax.validation.ConstraintViolationException; //导入方法依赖的package包/类
@Override
public Response toResponse(ConstraintViolationException exception) {
logger.info(String.format("%s. Returning %s response.", exception, Response.Status.BAD_REQUEST));
if (logger.isDebugEnabled()) {
logger.debug(StringUtils.EMPTY, exception);
}
// start with the overall message which will be something like "Cannot create xyz"
final StringBuilder errorMessage = new StringBuilder(exception.getMessage()).append(" - ");
boolean first = true;
for (final ConstraintViolation violation : exception.getConstraintViolations()) {
if (!first) {
errorMessage.append(", ");
}
first = false;
// lastNode should end up as the field that failed validation
Path.Node lastNode = null;
for (final Path.Node node : violation.getPropertyPath()) {
lastNode = node;
}
// append something like "xyz must not be..."
errorMessage.append(lastNode.getName()).append(" ").append(violation.getMessage());
}
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage.toString()).type("text/plain").build();
}