當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。