本文整理了Java中javax.validation.ConstraintViolationException
类的一些代码示例,展示了ConstraintViolationException
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ConstraintViolationException
类的具体详情如下:
包路径:javax.validation.ConstraintViolationException
类名称:ConstraintViolationException
[英]Reports the result of constraint violations.
[中]报告违反约束的结果。
代码示例来源:origin: apache/incubator-dubbo
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();
}
}
代码示例来源:origin: apache/incubator-dubbo
violations.addAll(validator.validate(parameterBean, classgroups ));
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
代码示例来源:origin: ctripcorp/apollo
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Map<String, Object>> handleConstraintViolationException(
HttpServletRequest request, ConstraintViolationException ex
) {
return handleError(request, BAD_REQUEST, new BadRequestException(ex.getMessage()));
}
代码示例来源:origin: OAuth-Apis/apis
public Response buildErrorResponse(Exception e) {
final Throwable jpaException = exceptionTranslator.translate(e);
Response.Status s;
String reason;
if (jpaException instanceof EntityExistsException) {
s = Response.Status.BAD_REQUEST;
reason = "Violating unique constraints";
} else if (jpaException instanceof ConstraintViolationException) {
ConstraintViolationException constraintViolationException = (ConstraintViolationException) jpaException;
return buildViolationErrorResponse(constraintViolationException.getConstraintViolations());
} else {
s = Response.Status.INTERNAL_SERVER_ERROR;
reason = "Internal server error";
}
LOG.info("Responding with error '" + s + "', '" + reason + "'. Cause attached.", e);
return Response
.status(s)
.entity(reason)
.build();
}
代码示例来源:origin: cloudfoundry/uaa
@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
Assert.state(yaml != null, "Yaml document should not be null");
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
try {
logger.trace("Yaml document is\n" + yaml);
configuration = (T) (new Yaml(constructor)).load(yaml);
Set<ConstraintViolation<T>> errors = validator.validate(configuration);
if (!errors.isEmpty()) {
logger.error("YAML configuration failed validation");
for (ConstraintViolation<?> error : errors) {
logger.error(error.getPropertyPath() + ": " + error.getMessage());
}
if (exceptionIfInvalid) {
@SuppressWarnings("rawtypes")
ConstraintViolationException summary = new ConstraintViolationException((Set) errors);
throw summary;
}
}
} catch (YAMLException e) {
if (exceptionIfInvalid) {
throw e;
}
}
}
代码示例来源:origin: je-ge/spring-boot
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public AjaxResult handleServiceException(ConstraintViolationException e) {
logger.error("参数验证失败", e);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String message = violation.getMessage();
return new AjaxResult().failure("parameter:" + message);
}
代码示例来源:origin: hs-web/hsweb-framework
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
ResponseMessage handleConstraintViolationException(ConstraintViolationException e) {
SimpleValidateResults results = new SimpleValidateResults();
for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
results.addResult(violation.getPropertyPath().toString(), violation.getMessage());
}
List<ValidateResults.Result> errorResults = results.getResults();
return ResponseMessage
.error(400, errorResults.isEmpty() ? "" : errorResults.get(0).getMessage())
.result(errorResults);
}
代码示例来源:origin: rapidoid/rapidoid
Set<ConstraintViolation<?>> violations = ((ConstraintViolationException) cause).getConstraintViolations();
ConstraintViolation<?> v = it.next();
sb.append(v.getRootBeanClass().getSimpleName());
sb.append(".");
sb.append(v.getPropertyPath());
sb.append(" (");
sb.append(v.getMessage());
sb.append(")");
代码示例来源:origin: jersey/jersey
/**
* Extract {@link ConstraintViolation constraint violations} from given exception and transform them into a list of
* {@link ValidationError validation errors}.
*
* @param violation exception containing constraint violations.
* @return list of validation errors (not {@code null}).
*/
public static List<ValidationError> constraintViolationToValidationErrors(final ConstraintViolationException violation) {
return violation.getConstraintViolations().stream().map(violation1 -> new ValidationError(
violation1.getMessage(),
violation1.getMessageTemplate(),
getViolationPath(violation1),
getViolationInvalidValue(violation1.getInvalidValue())
)).collect(Collectors.toList());
}
代码示例来源:origin: javaee/glassfish
private void handleValidationException(Set constraintViolations) throws ConstraintViolationException {
if (constraintViolations != null && !constraintViolations.isEmpty()) {
Iterator<ConstraintViolation<ConfigBeanProxy>> it = constraintViolations.iterator();
StringBuilder sb = new StringBuilder();
sb.append(MessageFormat.format(i18n.getString("bean.validation.failure"), this.<ConfigBeanProxy>getProxyType().getSimpleName()));
String violationMsg = i18n.getString("bean.validation.constraintViolation");
while (it.hasNext()) {
ConstraintViolation cv = it.next();
sb.append(" ");
sb.append(MessageFormat.format(violationMsg, cv.getMessage(), cv.getPropertyPath()));
if (it.hasNext()) {
sb.append(i18n.getString("bean.validation.separator"));
}
}
bean.getLock().unlock();
throw new ConstraintViolationException(sb.toString(), constraintViolations);
}
}
代码示例来源:origin: Netflix/conductor
private static ErrorResponse constraintViolationExceptionToErrorResponse(ConstraintViolationException exception) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
errorResponse.setMessage("Validation failed, check below errors for detail.");
List<ValidationError> validationErrors = new ArrayList<>();
exception.getConstraintViolations().forEach(e ->
validationErrors.add(new ValidationError(getViolationPath(e), e.getMessage(), getViolationInvalidValue(e.getInvalidValue()))));
errorResponse.setValidationErrors(validationErrors);
return errorResponse;
}
代码示例来源:origin: Netflix/conductor
@Test(expected = ConstraintViolationException.class)
public void testGetTaskQueueSizes(){
try{
List<String> list = new ArrayList<>();
taskService.getTaskQueueSizes(list);
} catch (ConstraintViolationException ex){
assertEquals(1, ex.getConstraintViolations().size());
Set<String> messages = getConstraintViolationMessages(ex.getConstraintViolations());
assertTrue(messages.contains("List of taskType cannot be null or empty"));
throw ex;
}
}
代码示例来源:origin: hibernate/hibernate-orm
final Class<?>[] groups = groupsPerOperation.get( operation );
if ( groups.length > 0 ) {
final Set<ConstraintViolation<T>> constraintViolations = validator.validate( object, groups );
if ( constraintViolations.size() > 0 ) {
Set<ConstraintViolation<?>> propagatedViolations =
LOG.trace( violation );
propagatedViolations.add( violation );
classNames.add( violation.getLeafBean().getClass().getName() );
throw new ConstraintViolationException(
builder.toString(), propagatedViolations
);
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void testEmbeddedCollection() {
Session s = openSession();
Transaction tx = s.beginTransaction();
Screen screen = new Screen();
PowerSupply ps = new PowerSupply();
screen.setPowerSupply( ps );
DisplayConnector conn = new DisplayConnector();
conn.setNumber( 0 );
screen.getConnectors().add( conn );
try {
s.persist( screen );
s.flush();
fail( "Collection of embedded objects should be validated" );
}
catch ( ConstraintViolationException e ) {
assertEquals( 1, e.getConstraintViolations().size() );
final ConstraintViolation constraintViolation = e.getConstraintViolations().iterator().next();
assertEquals( Screen.class, constraintViolation.getRootBeanClass() );
// toString works since hibernate validator's Path implementation works accordingly. Should do a Path comparison though
assertEquals( "connectors[].number", constraintViolation.getPropertyPath().toString() );
}
tx.rollback();
s.close();
}
代码示例来源:origin: jersey/jersey
/**
* Determine the response status (400 or 500) from the given BV exception.
*
* @param violation BV exception.
* @return response status (400 or 500).
*/
public static Response.Status getResponseStatus(final ConstraintViolationException violation) {
final Iterator<ConstraintViolation<?>> iterator = violation.getConstraintViolations().iterator();
if (iterator.hasNext()) {
for (final Path.Node node : iterator.next().getPropertyPath()) {
final ElementKind kind = node.getKind();
if (ElementKind.RETURN_VALUE.equals(kind)) {
return Response.Status.INTERNAL_SERVER_ERROR;
}
}
}
return Response.Status.BAD_REQUEST;
}
代码示例来源:origin: spring-projects/spring-framework
ExecutableValidator execVal = this.validator.forExecutables();
Method methodToValidate = invocation.getMethod();
Set<ConstraintViolation<Object>> result;
throw new ConstraintViolationException(result);
throw new ConstraintViolationException(result);
代码示例来源:origin: jersey/jersey
@Override
public void validateResult(final Object resource, final Invocable resourceMethod, final Object result) {
if (configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) {
final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<>();
final Method handlingMethod = resourceMethod.getHandlingMethod();
final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass());
final MethodDescriptor methodDescriptor = beanDescriptor.getConstraintsForMethod(handlingMethod.getName(),
handlingMethod.getParameterTypes());
final Method definitionMethod = resourceMethod.getDefinitionMethod();
if (methodDescriptor != null
&& methodDescriptor.hasConstrainedReturnValue()
&& validateOnExecutionHandler.validateMethod(resource.getClass(), definitionMethod, handlingMethod)) {
constraintViolations.addAll(forExecutables().validateReturnValue(resource, handlingMethod, result));
if (result instanceof Response) {
constraintViolations.addAll(forExecutables().validateReturnValue(resource, handlingMethod,
((Response) result).getEntity()));
}
}
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
}
}
}
代码示例来源:origin: javaee/glassfish
/**
* Returns true of this Transaction can be committed on this object
*
* @param t is the transaction to commit, should be the same as the
* one passed during the join(Transaction t) call.
* @return true if the trsaction commiting would be successful
*/
public synchronized boolean canCommit(Transaction t) throws TransactionFailure {
if (!isDeleted) { // HK2-127: validate only if not marked for deletion
Set constraintViolations =
beanValidator.validate(this.getProxy(this.getProxyType()));
try {
handleValidationException(constraintViolations);
} catch (ConstraintViolationException constraintViolationException) {
throw new TransactionFailure(constraintViolationException.getMessage(), constraintViolationException);
}
}
return currentTx==t;
}
代码示例来源:origin: hibernate/hibernate-orm
@Test
public void testToOneAssocNotValidated() {
Session s = openSession();
Transaction tx = s.beginTransaction();
Screen screen = new Screen();
PowerSupply ps = new PowerSupply();
ps.setPosition( "1" );
ps.setPower( new BigDecimal( 350 ) );
screen.setPowerSupply( ps );
try {
s.persist( screen );
s.flush();
fail( "Associated objects should not be validated" );
}
catch ( ConstraintViolationException e ) {
assertEquals( 1, e.getConstraintViolations().size() );
final ConstraintViolation constraintViolation = e.getConstraintViolations().iterator().next();
assertEquals( PowerSupply.class, constraintViolation.getRootBeanClass() );
}
tx.rollback();
s.close();
}
代码示例来源:origin: rapidoid/rapidoid
public static void validate(Object bean) {
Set<ConstraintViolation<Object>> violations = getViolations(bean);
if (U.notEmpty(violations)) {
throw new ConstraintViolationException(violations);
}
}
内容来源于网络,如有侵权,请联系作者删除!