本文整理汇总了Java中javax.validation.ConstraintViolationException类的典型用法代码示例。如果您正苦于以下问题:Java ConstraintViolationException类的具体用法?Java ConstraintViolationException怎么用?Java ConstraintViolationException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ConstraintViolationException类属于javax.validation包,在下文中一共展示了ConstraintViolationException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testMaxAnnotationValidationToReponse
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
@Test
public void testMaxAnnotationValidationToReponse(){
val invalidVal = new ClassWithMinMaxAnnotation("12345678911");
Response response = uut.toResponse(new ConstraintViolationException(validator.validate(invalidVal)));
JSONObject responseEntityJson = new JSONObject(response.getEntity());
assertThat(response.getStatus()).isEqualTo(400);
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("code").toString()
).isEqualTo("MAXLENGTH");
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("path").toString()
).isEqualTo("#/annotatedVar");
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("limit")
).isEqualTo(MAX_VAL);
}
示例2: invoke
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation invocation) throws Throwable {
Class<?>[] groups = determineValidationGroups(invocation);
if (forExecutablesMethod != null) {
Object executableValidator = ReflectionUtils.invokeMethod(forExecutablesMethod, this.validator);
Set<ConstraintViolation<?>> result = (Set<ConstraintViolation<?>>)
ReflectionUtils.invokeMethod(validateParametersMethod, executableValidator,
invocation.getThis(), invocation.getMethod(), invocation.getArguments(), groups);
if (!result.isEmpty()) {
throw new ConstraintViolationException(result);
}
Object returnValue = invocation.proceed();
result = (Set<ConstraintViolation<?>>)
ReflectionUtils.invokeMethod(validateReturnValueMethod, executableValidator,
invocation.getThis(), invocation.getMethod(), returnValue, groups);
if (!result.isEmpty()) {
throw new ConstraintViolationException(result);
}
return returnValue;
}
else {
return HibernateValidatorDelegate.invokeWithinValidation(invocation, this.validator, groups);
}
}
示例3: main
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml"});
context.start();
IValidationService validationService = (IValidationService)context.getBean("validationService");
// Error
try {
ValidationParameter parameter = new ValidationParameter();
validationService.save(parameter);
System.out.println("Validation ERROR");
} catch (RpcException e) { // 抛出的是RpcException
ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
// 里面嵌了一个ConstraintViolationException
Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
// 可以拿到一个验证错误详细信息的集合
System.out.println(violations);
}
}
示例4: getResponseProcessor
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
private ResponseProcessor getResponseProcessor(final Exception e) {
if (e instanceof ConstraintViolationException) {
if(AnnotationUtils.findAnnotation(e.getClass(), BusinessConstraintValidator.class) != null) {
return this.getBusinessConstraintValidatorRP();
}
return this.getConstraintValidatorRP();
}
if (AnnotationUtils.findAnnotation(e.getClass(), MultiBusinessException.class) != null) {
return this.getMultiBusinessExceptionRP();
}
return this.getBusinessExceptionRP();
}
示例5: 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;
}
示例6: testPropertyOnRelation
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
@Test
public void testPropertyOnRelation() {
Task task = new Task();
task.setId(1L);
task.setName("test");
taskRepo.create(task);
task.setName(null);
Project project = new Project();
project.setId(2L);
project.setName("test");
project.getTasks().add(task);
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("tasks[0]", violation.getPropertyPath().toString());
Assert.assertEquals("/data/relationships/tasks/0", violation.getErrorData().getSourcePointer());
}
}
示例7: 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());
}
}
示例8: validate
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
Class<?> methodClass = null;
try {
methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
}
Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
Method method = clazz.getMethod(methodName, parameterTypes);
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
if (methodClass != null) {
violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
} else {
violations.addAll(validator.validate(parameterBean, Default.class, clazz));
}
}
for (Object arg : arguments) {
validate(violations, arg, clazz, methodClass);
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
示例9: validate
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName);
Class<?> methodClass = null;
try {
methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
}
Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
Method method = clazz.getMethod(methodName, parameterTypes);
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
if (methodClass != null) {
violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
} else {
violations.addAll(validator.validate(parameterBean, Default.class, clazz));
}
}
for (Object arg : arguments) {
validate(violations, arg, clazz, methodClass);
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
示例10: testSizeMaxValidationToReponse
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
@Test
public void testSizeMaxValidationToReponse(){
val invalidVal = new ClassWithSizeAnnotation("12345678911");
Response response = uut.toResponse(new ConstraintViolationException(validator.validate(invalidVal)));
JSONObject responseEntityJson = new JSONObject(response.getEntity());
assertThat(response.getStatus()).isEqualTo(400);
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("code").toString()
).isEqualTo("MAXLENGTH");
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("path").toString()
).isEqualTo("#/annotatedVar");
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("limit")
).isEqualTo(MAX_VAL);
}
示例11: testResourceObjectValidation
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
@Test
public void testResourceObjectValidation() {
Project project = new Project();
project.setId(1L);
project.setName(ComplexValidator.INVALID_NAME);
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("{complex.message}", violation.getMessageTemplate());
Assert.assertEquals("", violation.getPropertyPath().toString());
Assert.assertEquals("", violation.getErrorData().getSourcePointer());
}
}
示例12: testNotNullAnnotationValidationToReponse
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
@Test
public void testNotNullAnnotationValidationToReponse(){
val invalidVal = new ClassWithNotNullAnnotation(null);
Response response = uut.toResponse(new ConstraintViolationException(validator.validate(invalidVal)));
JSONObject responseEntityJson = new JSONObject(response.getEntity());
assertThat(response.getStatus()).isEqualTo(400);
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("code").toString()
).isEqualTo("REQUIRED");
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.get("path").toString()
).isEqualTo("#/annotatedVar");
assertThat(responseEntityJson
.getJSONArray("errors")
.getJSONObject(0)
.has("limit")
).isFalse();
}
示例13: validate
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
/**
* Validates the {@code request} based on its type and returns it or throws a {@code ValidationException}
* if any {@link ConstraintViolation} is found.
*
* @param request the request object to validate
* @param <T> request type param
* @return The validated request(the same object passed as {@code request})
* @throws ValidationException if any {@link ConstraintViolation} is found
*/
public static <T extends SafechargeBaseRequest> T validate(T request) throws ValidationException {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(request);
if (constraintViolations != null && !constraintViolations.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
sb.append(constraintViolation.getMessage())
.append(" ");
}
String errorMessage = sb.toString();
if (logger.isDebugEnabled()) {
logger.debug(errorMessage);
}
throw new ConstraintViolationException(constraintViolations);
}
return request;
}
示例14: editarEventoTipoUsuario
import javax.validation.ConstraintViolationException; //导入依赖的package包/类
public void editarEventoTipoUsuario(Evento evento, List<Categoria> categoriasEvento, Usuario usuarioQueEdita) throws AgendamlgException, AgendamlgNotFoundException {
try {
// Se obtiene una lista de Categorias "de verdad"
// No es necesario ya que sobre estos objetos no se invoca
// una propiedad como la de getEventoList, de ser asi si habria que hacer este paso
// como pasa en Evento, que el evento que llega desde el cliente tiene
// categoriaList a null y es por ello que hay que obtener desde el entity manager
// un evento "de verdad"
if (evento.getTipo() < 1 || evento.getTipo() > 3) {
throw AgendamlgException.tipoInvalido(evento.getTipo());
}
if (usuarioQueEdita.getTipo() == 3 || evento.getCreador().getId().equals(usuarioQueEdita.getId())) {
this.actualizarCategoriaEvento(evento, categoriasEvento);
} else {
throw AgendamlgException.sinPermisos(usuarioQueEdita.getNombre());
}
} catch (ConstraintViolationException e) {
throw AgendamlgException.eventoCamposInvalidos(e);
}
}
示例15: 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());
}
}