本文整理汇总了Java中javax.validation.ValidatorFactory类的典型用法代码示例。如果您正苦于以下问题:Java ValidatorFactory类的具体用法?Java ValidatorFactory怎么用?Java ValidatorFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ValidatorFactory类属于javax.validation包,在下文中一共展示了ValidatorFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: create
import javax.validation.ValidatorFactory; //导入依赖的package包/类
public void create(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if(constraintViolations.size() > 0){
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while(iterator.hasNext()){
ConstraintViolation<T> cv = iterator.next();
System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
System.err.println(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
}
}else{
getEntityManager().persist(entity);
}
}
示例2: main
import javax.validation.ValidatorFactory; //导入依赖的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);
}
示例3: validate
import javax.validation.ValidatorFactory; //导入依赖的package包/类
@Override
public void validate(Object entity) throws HttpException {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Object>> violations = validator.validate(entity);
if (!violations.isEmpty()) {
List<ConstraintViolationDescription> errors = new ArrayList<>();
ConstraintViolationResponseError error = new ConstraintViolationResponseError();
error.setMessage(UNPROCESSABLE_ENTITY_MESSAGE);
for (ConstraintViolation<Object> violation : violations) {
String attribute = violation.getPropertyPath().toString();
String message = violation.getMessage();
errors.add(new ConstraintViolationDescription(message, attribute));
}
error.setErrors(errors);
throw new UnprocessableEntityException(error);
}
}
示例4: loads
import javax.validation.ValidatorFactory; //导入依赖的package包/类
@Test
public void loads() {
Pessoa pessoa = new Pessoa();
pessoa.setNome("João da Silva");
pessoa.setCpf("12345678901");
pessoa.setTelefone("(11)3266-4455");
pessoa.setEndereco("Rua A, 123, Bananal, Guarulhos - SP");
Check check = new SafeguardCheck();
/*Validação manual usando a interface Check*/
Check resultados = check.elementOf(pessoa).validate();
int quantidadeDeElementosInvalidos = resultados.getInvalidElements().size();
boolean temErro = resultados.hasError();
/*Validação pelo provedor de validação, usando javax.validation*/
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
javax.validation.Validator validator = factory.getValidator();
Set<ConstraintViolation<Pessoa>> violacoes = validator.validate(pessoa, Default.class);
Assert.assertEquals(1, quantidadeDeElementosInvalidos);
Assert.assertEquals(true, temErro);
Assert.assertEquals(1, violacoes.size());
}
示例5: main
import javax.validation.ValidatorFactory; //导入依赖的package包/类
public static void main(String[] args) {
String src = "src.org/hack/controller";
src = src.replaceAll("/", File.separator + File.separator);
System.out.println(src);
System.out.println("src\\org\\hack\\controller");
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
System.out.println(factory.getMessageInterpolator().getClass());
Validator validator = factory.getValidator();
Blog blog = new Blog("1", "2121", "212", new Date(), 2);
Set<ConstraintViolation<Blog>> constraintViolations = validator.validate(blog);
System.out.println(validator.getClass());
for (ConstraintViolation<Blog> c : constraintViolations) {
System.out.println(c.getInvalidValue() + ":" + c.getMessage());
}
}
示例6: testMapElementAttributeNotNull
import javax.validation.ValidatorFactory; //导入依赖的package包/类
@Test
public void testMapElementAttributeNotNull() {
ProjectData data = new ProjectData();
data.setValue(null); // violation
Project project = new Project();
project.setId(1L);
project.setName("test");
project.setDataMap(new LinkedHashMap());
project.getDataMap().put("someKey", data);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
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("dataMap[someKey].value", violation.getPropertyPath().toString());
Assert.assertNotNull(violation.getMessage());
Assert.assertEquals("/data/attributes/dataMap/someKey/value", violation.getErrorData().getSourcePointer());
}
}
示例7: activate
import javax.validation.ValidatorFactory; //导入依赖的package包/类
@SuppressWarnings("UnusedDeclaration")
public static void activate(ActivationContext activationContext) {
final Properties properties = activationContext.getConfiguration().getProperties();
final ValidatorFactory factory;
try {
factory = getValidatorFactory( properties );
}
catch (IntegrationException e) {
if ( activationContext.getValidationModes().contains( ValidationMode.CALLBACK ) ) {
throw new IntegrationException( "Bean Validation provider was not available, but 'callback' validation was requested", e );
}
if ( activationContext.getValidationModes().contains( ValidationMode.DDL ) ) {
throw new IntegrationException( "Bean Validation provider was not available, but 'ddl' validation was requested", e );
}
LOG.debug( "Unable to acquire Bean Validation ValidatorFactory, skipping activation" );
return;
}
applyRelationalConstraints( factory, activationContext );
applyCallbackListeners( factory, activationContext );
}
示例8: applyRelationalConstraints
import javax.validation.ValidatorFactory; //导入依赖的package包/类
@SuppressWarnings({"unchecked", "UnusedParameters"})
private static void applyRelationalConstraints(ValidatorFactory factory, ActivationContext activationContext) {
final Properties properties = activationContext.getConfiguration().getProperties();
if ( ! ConfigurationHelper.getBoolean( BeanValidationIntegrator.APPLY_CONSTRAINTS, properties, true ) ){
LOG.debug( "Skipping application of relational constraints from legacy Hibernate Validator" );
return;
}
final Set<ValidationMode> modes = activationContext.getValidationModes();
if ( ! ( modes.contains( ValidationMode.DDL ) || modes.contains( ValidationMode.AUTO ) ) ) {
return;
}
applyRelationalConstraints(
factory,
activationContext.getConfiguration().createMappings().getClasses().values(),
properties,
activationContext.getServiceRegistry().getService( JdbcServices.class ).getDialect()
);
}
示例9: validateConfiguration
import javax.validation.ValidatorFactory; //导入依赖的package包/类
/**
* Validates the provided {@link StreamingAppConfiguration} against constraints provided to fields holding the
* configuration
* @param configuration
* @param outputStream
* @return
* @throws IOException
*/
protected boolean validateConfiguration(final StreamingAppConfiguration configuration, final OutputStream outputStream) throws IOException {
if(outputStream == null)
throw new IOException("Missing required output stream\n");
if(configuration == null) {
outputStream.write(MSG_MISSING_CFG_INSTANCE);
return false;
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<StreamingAppConfiguration>> violations = validator.validate(configuration);
if(violations.isEmpty())
return true;
for(ConstraintViolation<StreamingAppConfiguration> v : violations) {
StringBuffer error = new StringBuffer("Invalid configuration at: ");
error.append(v.getPropertyPath()).append(", error: ").append(v.getMessage()).append("\n");
outputStream.write(error.toString().getBytes());
outputStream.flush();
}
return false;
}
示例10: validateRequired
import javax.validation.ValidatorFactory; //导入依赖的package包/类
public List<ConstraintViolation> validateRequired() {
List<ConstraintViolation> returnListreturnList = new ArrayList();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
for (DatasetField dsf : this.getFlatDatasetFields()) {
dsf.setValidationMessage(null); // clear out any existing validation message
Set<ConstraintViolation<DatasetField>> constraintViolations = validator.validate(dsf);
for (ConstraintViolation<DatasetField> constraintViolation : constraintViolations) {
dsf.setValidationMessage(constraintViolation.getMessage());
returnListreturnList.add(constraintViolation);
break; // currently only support one message, so we can break out of the loop after the first constraint violation
}
}
return returnListreturnList;
}
开发者ID:pengchengluo,项目名称:Peking-University-Open-Research-Data-Platform,代码行数:17,代码来源:DatasetVersion.java
示例11: getConfiguration
import javax.validation.ValidatorFactory; //导入依赖的package包/类
@Override
public RestlerConfig getConfiguration() {
ObjectMapper objectMapper = Jackson.newObjectMapper();
ValidatorFactory validatorFactory = Validation
.byProvider(HibernateValidator.class)
.configure()
.addValidatedValueHandler(new OptionalValidatedValueUnwrapper())
.buildValidatorFactory();
final ConfigurationFactory<RestlerConfig> configurationFactory =
new DefaultConfigurationFactoryFactory<RestlerConfig>().create(RestlerConfig.class, validatorFactory.getValidator(), objectMapper, "dw");
try {
return configurationFactory.build(new FileConfigurationSourceProvider(), TEST_CONFIG_FILE);
} catch (Exception e) {
throw new RuntimeException("Cannot get test configuration", e);
}
}
示例12: create
import javax.validation.ValidatorFactory; //导入依赖的package包/类
/**
* Creates an entity in the facade
* @param entity the entity needed to be created
*/
public void create(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if(constraintViolations.size() > 0){
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while(iterator.hasNext()){
ConstraintViolation<T> cv = iterator.next();
System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
}
}else{
getEntityManager().persist(entity);
}
}
示例13: ValidatorProviderJsr303
import javax.validation.ValidatorFactory; //导入依赖的package包/类
public ValidatorProviderJsr303()
{
ValidatorFactory validatorFactory = null;
try {
validatorFactory = Validation.buildDefaultValidatorFactory();
if (validatorFactory.getValidator() == null) {
validatorFactory = null;
}
} catch (Throwable t) {
log.log(Level.WARNING, t.toString(), t);
}
_validatorFactory = validatorFactory;
}
示例14: init
import javax.validation.ValidatorFactory; //导入依赖的package包/类
/**
* We should be able to get a ValidatorFactory from the container in an Java EE environment.
* However, if we don't get the factory, we will will use a default one. This is especially
* useful for non Java EE environments and in the CDI tests
*/
@PostConstruct
public void init() {
// Prefer the ValidatorFactory provided by the container
Iterator<ValidatorFactory> iterator = validatorFactoryInstance.iterator();
if (iterator.hasNext()) {
this.validatorFactory = iterator.next();
}
// create a default factory if we didn't get one
else {
log.warning("Creating a ValidatorFactory because the container didn't provide one!");
this.validatorFactory = Validation.buildDefaultValidatorFactory();
}
}
示例15: main
import javax.validation.ValidatorFactory; //导入依赖的package包/类
public static void main(String[] args) {
Email email = new Email();
email.setFrom("[email protected]");
email.setTo("someone");
email.setSubject("");
email.setBody(null);
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<Email>> violations = validator.validate(email);
for (ConstraintViolation<Email> constraintViolation : violations) {
String propertyPath = constraintViolation.getPropertyPath().toString();
String message = constraintViolation.getMessage();
System.out.println("invalid value for: '" + propertyPath + "': " + message);
}
}