当前位置: 首页>>代码示例>>Java>>正文


Java ConstraintViolation类代码示例

本文整理汇总了Java中javax.validation.ConstraintViolation的典型用法代码示例。如果您正苦于以下问题:Java ConstraintViolation类的具体用法?Java ConstraintViolation怎么用?Java ConstraintViolation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ConstraintViolation类属于javax.validation包,在下文中一共展示了ConstraintViolation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: validateInterestDate

import javax.validation.ConstraintViolation; //导入依赖的package包/类
private boolean validateInterestDate(Object validateThis,
                                     ConstraintValidatorContext ctx,
                                     Field fieldObj,
                                     Field dependentFieldObj) throws IllegalAccessException {
    InterestDate interestDate = (InterestDate) fieldObj.get(validateThis);
    Interest interest = (Interest) dependentFieldObj.get(validateThis);
    if (interest != null && !interestTypeIsNoInterest(interest.getType())) {
        Set<ConstraintViolation<Object>> violations = validator.validate(interestDate);
        if (!violations.isEmpty()) {
            ctx.disableDefaultConstraintViolation();
            ctx.buildConstraintViolationWithTemplate(getViolationMessages(violations, ctx))
                .addPropertyNode(field)
                .addConstraintViolation();

            return false;
        }
    }
    return true;
}
 
开发者ID:hmcts,项目名称:cmc-claim-store,代码行数:20,代码来源:InterDependentFieldsConstraintValidator.java

示例2: main

import javax.validation.ConstraintViolation; //导入依赖的package包/类
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
	AutoRunHelper.run(App.class);
	
	// 测试参数校验
	App app = new App();
	
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	ExecutableValidator executableValidator = factory.getValidator().forExecutables();
	Method method = App.class.getMethod("showEmail", String.class);
	
	Object[] parameterValues = {"email"};
	Set<ConstraintViolation<App>> violations = executableValidator.validateParameters(app, method, parameterValues);
	String message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : "";
	System.out.println("values:" + parameterValues[0].toString() + " size: " + violations.size() + " msg:" + message);
	
	Object[] parameterValues2 = {"abc"};
	violations = executableValidator.validateParameters(app, method, parameterValues2);
	message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : "";
	System.out.println("values:" + parameterValues2[0].toString() + " size: " + violations.size() + " msg:" + message);

}
 
开发者ID:zhoukekestar,项目名称:java-notes,代码行数:22,代码来源:App.java

示例3: validateProperty

import javax.validation.ConstraintViolation; //导入依赖的package包/类
public static <T> ValidationResult validateProperty(T obj, String propertyName) {
    ValidationResult result = new ValidationResult();
    Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
    if (CollectionUtils.isNotEmpty(set)) {
        result.setHasErrors(true);
        Map<String, String> errorMsg = Maps.newHashMap();
        for (ConstraintViolation<T> cv : set) {
            errorMsg.put(propertyName, cv.getMessage());
        }
        result.setErrorMsg(errorMsg);
    }
    return result;
}
 
开发者ID:fanqinghui,项目名称:wish-pay,代码行数:14,代码来源:ValidationUtils.java

示例4: checkObjParamValidate

import javax.validation.ConstraintViolation; //导入依赖的package包/类
/**
 * 对象校验,依据validator
 * use case
 * 派单前做的工单校验
 *
 * @param t
 * @param <T>
 * @return
 */
public <T> T checkObjParamValidate(@NotNull T t, Class<?>... groups) {
    BusinessAssert.requireNonEmpty(t, MessageSourceUtil.getChinese(messageSource, "param.null"));
    //是否符合validator校验
    StringBuilder errorMsg = new StringBuilder();
    Set<ConstraintViolation<T>> constraintViolationSet = null;
    if (!Check.isNullObjects(groups)) {
        constraintViolationSet = validator.validate(t, groups);
    } else {
        constraintViolationSet = validator.validate(t);
    }
    if (!Check.isNullOrEmpty(constraintViolationSet)) {
        Iterator<ConstraintViolation<T>> iterator = constraintViolationSet.iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<T> constraint = iterator.next();
            errorMsg.append(constraint.getMessage()).append(",");
        }
        //设置错误信息
        if (errorMsg.length() != 0) {
            errorMsg.deleteCharAt(errorMsg.length() - 1);
            throw new ValidatorException(errorMsg.toString());
        }
    }
    return t;
}
 
开发者ID:AsuraTeam,项目名称:asura,代码行数:34,代码来源:ParamCheckLogic.java

示例5: handleValidation

import javax.validation.ConstraintViolation; //导入依赖的package包/类
@Override
protected void handleValidation(final Message message, final Object resourceInstance, final Method method,
		final List<Object> arguments) {
	super.handleValidation(message, resourceInstance, method, arguments);

	// Check each parameter
	final Set<ConstraintViolation<?>> validationErrors = new HashSet<>();
	for (int index = 0; index < arguments.size(); index++) {
		final Parameter parameter = method.getParameters()[index];
		if (hasToBeValidated(parameter)) {
			// This parameter is a not context, path or query parameter
			validate(arguments.get(index), method, parameter, index, validationErrors);
		}
	}

	// Check the veto
	if (!validationErrors.isEmpty()) {
		message.put(FaultListener.class.getName(), new NoOpFaultListener());
		throw new ConstraintViolationException(validationErrors);
	}
}
 
开发者ID:ligoj,项目名称:bootstrap,代码行数:22,代码来源:JAXRSBeanValidationImplicitInInterceptor.java

示例6: testNestedPropertyNotNull

import javax.validation.ConstraintViolation; //导入依赖的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());
	}
}
 
开发者ID:crnk-project,项目名称:crnk-framework,代码行数:22,代码来源:ValidationEndToEndTest.java

示例7: getAccounts

import javax.validation.ConstraintViolation; //导入依赖的package包/类
public List<Account> getAccounts() {
    final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    final ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    List<Account> accounts = null;
    try {
        accounts = mapper.readValue(rulesFile, 
                new TypeReference<List<Account>>() {});
        if (accounts != null) {
            accounts.forEach((account) -> {
                final Set<ConstraintViolation<Account>> accountViolations = validator.validate(account);
                if (accountViolations.size() > 0) {
                    throw new AccountValidationException(accountViolations);
                }
                account.getRules().sort((o1, o2) -> o1.getType().compareTo(o2.getType()));
            });
        }
    } catch (IOException ex) {
        Logger.getLogger(AccountService.class.getName()).log(Level.SEVERE, null, ex);
    }

    return accounts;
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Programming-Blueprints,代码行数:24,代码来源:AccountService.java

示例8: validateMapKeyContainerElementConstraint

import javax.validation.ConstraintViolation; //导入依赖的package包/类
@Test
public void validateMapKeyContainerElementConstraint() {
	//tag::validateMapKeyContainerElementConstraint[]
	Car car = new Car();
	car.setFuelConsumption( null, 5 );

	Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );

	assertEquals( 1, constraintViolations.size() );

	ConstraintViolation<Car> constraintViolation =
			constraintViolations.iterator().next();
	assertEquals(
			"must not be null",
			constraintViolation.getMessage()
	);
	assertEquals(
			"fuelConsumption<K>[].<map key>",
			constraintViolation.getPropertyPath().toString()
	);
	//end::validateMapKeyContainerElementConstraint[]
}
 
开发者ID:minijax,项目名称:minijax,代码行数:23,代码来源:CarTest.java

示例9: onConstraintViolationException

import javax.validation.ConstraintViolation; //导入依赖的package包/类
/**
 * The exception handler is trigger if a JSR303 {@link ConstraintViolationException}
 * is being raised.
 *
 * Log the exception message at warn level and stack trace as trace level.
 * Return response status HttpStatus.BAD_REQUEST (400).
 */
@ExceptionHandler({ConstraintViolationException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public VndErrors onConstraintViolationException(ConstraintViolationException e) {
	String logref = logWarnLevelExceptionMessage(e);
	if (logger.isTraceEnabled()) {
		logTraceLevelStrackTrace(e);
	}

	final StringBuilder errorMessage = new StringBuilder();
	boolean first = true;
	for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
		if (!first) {
			errorMessage.append("; ");
		}
		errorMessage.append(violation.getMessage());
		first = false;
	}

	return new VndErrors(logref, errorMessage.toString());
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-dashboard,代码行数:29,代码来源:RestControllerAdvice.java

示例10: testRelationProperty

import javax.validation.ConstraintViolation; //导入依赖的package包/类
@Test
public void testRelationProperty() {
	Task task = new Task();
	task.setId(1L);
	task.setName("test");
	taskRepo.create(task);
	task.setName(ComplexValidator.INVALID_NAME);

	Project project = new Project();
	project.setName("test");
	project.setTask(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("{complex.message}", violation.getMessageTemplate());
		Assert.assertEquals("task", violation.getPropertyPath().toString());
		Assert.assertEquals("/data/relationships/task", violation.getErrorData().getSourcePointer());
	}
}
 
开发者ID:crnk-project,项目名称:crnk-framework,代码行数:24,代码来源:ValidationEndToEndTest.java

示例11: validate

import javax.validation.ConstraintViolation; //导入依赖的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;
}
 
开发者ID:SafeChargeInternational,项目名称:safecharge-java,代码行数:32,代码来源:ValidationUtils.java

示例12: objectNull

import javax.validation.ConstraintViolation; //导入依赖的package包/类
/**
 * Check not valid parameter operation failed.
 */
@Test
public void objectNull() {
	final SystemUser userDto = null;
	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(NotNull.class, error1.getConstraintDescriptor().getAnnotation().annotationType());
		Assert.assertEquals("object.param", error1.getPropertyPath().toString());
	}
}
 
开发者ID:ligoj,项目名称:bootstrap,代码行数:23,代码来源:JAXRSBeanValidationImplicitInInterceptorTest.java

示例13: validate

import javax.validation.ConstraintViolation; //导入依赖的package包/类
protected void validate() {
	// Clear all validation errors
	propertyToBindingMap.values().stream().forEach(e -> e.clearValidationError());

	// Validate and set validation errors
	if (getBean() != null) {
		constraintViolations = validator.validate(getBean(), groups);
		constraintViolations.stream().forEach(e -> handleConstraintViolations(e, f -> f.getMessage()));
	} else {
		constraintViolations = new HashSet<ConstraintViolation<BEAN>>();
	}

	List<BindingValidationStatus<?>> binRes =
			getBindings().stream().map(e -> e.validate(false)).collect(Collectors.toList());

	List<ValidationResult> valRes =
			constraintViolations.stream()
			.filter(e -> e.getPropertyPath().toString().isEmpty())
			.map(e -> ValidationResult.error(e.getMessage()))
			.collect(Collectors.toList());

	status = new BasicBinderValidationStatus<BEAN>(this, binRes, valRes);

	getValidationStatusHandler().statusChange(status);
}
 
开发者ID:ljessendk,项目名称:easybinder,代码行数:26,代码来源:BasicBinder.java

示例14: validateIndividuBean

import javax.validation.ConstraintViolation; //导入依赖的package包/类
/** Valide un bean d'individu
 * @param ind
 * @throws CustomException
 */
public void validateIndividuBean(Individu ind) throws CustomException{
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Individu>> constraintViolations = validator.validate(ind);
	if (constraintViolations!=null && constraintViolations.size() > 0) {
		String erreur = ""; 
		for (ConstraintViolation<?> violation : constraintViolations) {
			erreur += (" *** "+ violation.getPropertyPath().toString() + " : " + violation.getMessage());
		  }
		throw new CustomException(applicationContext.getMessage("droitprofil.individu.error", null, UI.getCurrent().getLocale())+" : "+erreur);
	}
}
 
开发者ID:EsupPortail,项目名称:esup-ecandidat,代码行数:17,代码来源:IndividuController.java

示例15: validateTodoValid

import javax.validation.ConstraintViolation; //导入依赖的package包/类
@Test
public void validateTodoValid() {
    ToDo toDo = new ToDo("[email protected]","caption", "description 1", 6);
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<ToDo>> constraintViolations = validator.validate(toDo);
    assertTrue(constraintViolations.isEmpty());       
}
 
开发者ID:apssouza22,项目名称:java-microservice,代码行数:9,代码来源:TodoIT.java


注:本文中的javax.validation.ConstraintViolation类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。