Java Code Examples for javax.validation.ValidatorFactory#getValidator()

The following examples show how to use javax.validation.ValidatorFactory#getValidator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ObjectValidator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String validate(Object obj) {
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Object>> violations = validator.validate(obj);

	String error = "";
	if (!violations.isEmpty()) {

		boolean firstIteration = true;
		for (ConstraintViolation<Object> violation : violations) {
			if (firstIteration)
				firstIteration = false;
			else
				error += ", ";

			error += violation.getPropertyPath().toString() + " " + violation.getMessage();
		}

		return error;
	}

	return null;
}
 
Example 2
Source File: WorkflowDefValidatorTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void testWorkflowOwnerValidEmail() {
	WorkflowDef workflowDef = new WorkflowDef();
	workflowDef.setName("test_env");
	workflowDef.setOwnerEmail("[email protected]");

	WorkflowTask workflowTask = new WorkflowTask();

	workflowTask.setName("t1");
	workflowTask.setWorkflowTaskType(TaskType.SIMPLE);
	workflowTask.setTaskReferenceName("t1");

	Map<String, Object> map = new HashMap<>();
	map.put("blabla", "");
	workflowTask.setInputParameters(map);

	workflowDef.getTasks().add(workflowTask);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Object>> result = validator.validate(workflowDef);
	assertEquals(0, result.size());
}
 
Example 3
Source File: IntegrationTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public IntegrationTest() {
    final JavaBeanHelper javaBeanHelper = new JavaBeanHelper(new DefaultGetterPropertySelectionStrategy(), new DefaultPropertyNodeNameProvider());
    final DefaultConstraintMapping mapping = new DefaultConstraintMapping(javaBeanHelper);

    mapping.constraintDefinition(NoDuplicateIntegration.class).validatedBy(UniqnenessValidator.class);
    final ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
        .addMapping(mapping).buildValidatorFactory();

    validator = validatorFactory.getValidator();
}
 
Example 4
Source File: SourceCatalogTest.java    From circus-train with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  ValidatorFactory config = Validation.buildDefaultValidatorFactory();
  validator = config.getValidator();

  sourceCatalog.setName("name");
}
 
Example 5
Source File: OpenAPIUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static <T> void validate(T obj) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
    if (constraintViolations.size() > 0) {
        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<T> contraintes : constraintViolations) {
            errors.append(String.format("%s.%s %s\n",
            contraintes.getRootBeanClass().getSimpleName(),
            contraintes.getPropertyPath(),
            contraintes.getMessage()));
        }
        throw new RuntimeException("Bean validation : " + errors);
    }
}
 
Example 6
Source File: ConstraintViolationsMvcBindingTest.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize our {@link Validator} instance.
 */
@BeforeClass
public static void initValidator() {

    final ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    validator = vf.getValidator();

}
 
Example 7
Source File: T212MapEntryNValidatorTest.java    From hj-t212-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<T212MapEntry>> e1 = validator.validate(T212MapEntry.of("N1","2"),TypeGroup.N1.class);
    assertTrue(e1.isEmpty());
    Set<ConstraintViolation<T212MapEntry>> e2 = validator.validate(T212MapEntry.of("N2","23"),TypeGroup.N2.class);
    assertTrue(e2.isEmpty());
    Set<ConstraintViolation<T212MapEntry>> e3 = validator.validate(T212MapEntry.of("N2.2","23.1"),TypeGroup.N2_2.class);
    assertTrue(e3.isEmpty());
    Set<ConstraintViolation<T212MapEntry>> e4 = validator.validate(T212MapEntry.of("N14","12345678901234"),TypeGroup.N14.class);
    assertTrue(e4.isEmpty());
}
 
Example 8
Source File: OpenAPIUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static <T> void validate(T obj) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
    if (constraintViolations.size() > 0) {
        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<T> contraintes : constraintViolations) {
            errors.append(String.format("%s.%s %s\n",
            contraintes.getRootBeanClass().getSimpleName(),
            contraintes.getPropertyPath(),
            contraintes.getMessage()));
        }
        throw new RuntimeException("Bean validation : " + errors);
    }
}
 
Example 9
Source File: HibernateValidation.java    From validator-web with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ValidationContext context) {
    context.setValidatorDelegate(this);
    
    HibernateValidatorConfiguration configure = javax.validation.Validation.byProvider(HibernateValidator.class).configure();
    if (context instanceof ValidationContext.Accessor) {
        configure.failFast(((ValidationContext.Accessor) context).isFailFast());
    }
    ValidatorFactory factory = configure.buildValidatorFactory();
    validator = factory.getValidator();
}
 
Example 10
Source File: TransportConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Bean
public Validator messageValidator() {
	// force hibernate validator to log to slf4j
	System.setProperty("org.jboss.logging.provider", "slf4j");
	
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	
    return factory.getValidator();
}
 
Example 11
Source File: ScanUploadTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    // Load the config.yaml file specified as the first argument.
    ConfigurationFactory<EmoConfiguration> configFactory = new ConfigurationFactory<>(
            EmoConfiguration.class, validatorFactory.getValidator(), Jackson.newObjectMapper(),
            "dw");
    File configFile = new File(args[0]);
    EmoConfiguration configuration = configFactory.build(configFile);
    String ddlFilePath = args[1];
    File scanUploadDir = new File(args[2]);

    checkArgument(scanUploadDir.isDirectory(), "Not a valid directory: %s", scanUploadDir);
    checkArgument(configuration.getServiceMode() == EmoServiceMode.SCANNER,
            "Not configured for scanner: %s", configuration.getServiceMode());

    // To prevent conflicting with EmoDB running on this same server adjust the host and admin ports.
    updatePortsToAvoidCollision(configuration.getServerFactory());

    HostAndPort hostAndPort = new SelfHostAndPortModule().provideSelfHostAndPort(configuration.getServerFactory());
    MetricRegistry metricRegistry = new MetricRegistry();
    configuration.getLoggingFactory().configure(metricRegistry, "scan");

    DataStore dataStore = null;

    try (CuratorFramework curator = configuration.getZooKeeperConfiguration().newCurator()) {
        curator.start();

        DataStoreClientFactory dataStoreFactory = DataStoreClientFactory.forClusterAndHttpConfiguration(
                configuration.getCluster(), configuration.getHttpClientConfiguration(), metricRegistry);
        dataStore = ServicePoolBuilder.create(DataStore.class)
                .withServiceFactory(dataStoreFactory.usingCredentials(configuration.getScanner().get().getScannerApiKey().get()))
                .withHostDiscovery(new ZooKeeperHostDiscovery(curator, dataStoreFactory.getServiceName(), metricRegistry))
                .withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
                .withMetricRegistry(metricRegistry)
                .buildProxy(new ExponentialBackoffRetry(5, 50, 1000, TimeUnit.MILLISECONDS));

        ScanUploadTest test = new ScanUploadTest(dataStore);
        test.createAndPopulateTestTables();
        test.scanToDirectory(configuration, ddlFilePath, configFile, scanUploadDir, hostAndPort, validatorFactory, metricRegistry);
        test.validateScanResults(scanUploadDir);
    } finally {
        if (dataStore != null) {
            ServicePoolProxies.close(dataStore);
        }
    }
}
 
Example 12
Source File: SshPropertyValidatorTest.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUpValidator() {
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	validator = factory.getValidator();
}
 
Example 13
Source File: HibernateValidatorService.java    From wisdom with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the validator, and registers it as an OSGi service (if the bundle context is set).
 *
 * @return the validator.
 */
@Validate
public Validator initialize() {
    // configure and build an instance of ValidatorFactory
    ProviderSpecificBootstrap<HibernateValidatorConfiguration> validationBootStrap = javax.validation.Validation
            .byProvider(HibernateValidator.class);

    // bootstrap to properly resolve in an OSGi environment
    validationBootStrap.providerResolver(new HibernateValidationProviderResolver());

    HibernateValidatorConfiguration configure = validationBootStrap.configure().messageInterpolator(interpolator);
    interpolator.setDefaultInterpolator(configure.getDefaultMessageInterpolator());

    // now that we've done configuring the ValidatorFactory, let's build it
    ValidatorFactory validatorFactory = configure.buildValidatorFactory();

    // retrieve a unique validator.
    Validator validator = validatorFactory.getValidator();

    // Register the validator.
    if (context != null) {
        registration = context.registerService(Validator.class, new WrappedValidator(validator), null);
        factoryRegistration = context.registerService(ValidatorFactory.class, validatorFactory, null);
    }

    return validator;
}
 
Example 14
Source File: StorageIdentityValidatorTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void setUp() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();
}
 
Example 15
Source File: TestTest.java    From Mario with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void before() throws Exception {
    Locale.setDefault(Locale.ENGLISH);
    ValidatorFactory config = Validation.buildDefaultValidatorFactory();
    validator = config.getValidator();
}
 
Example 16
Source File: ModelValidationTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
/**
 * Test validation of the version string regex
 * 
 * @throws Exception
 */
@Test
public void testVersionStringValidation() throws Exception {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Product product = Product.Builder.newBuilder().name("Test Product").build();
    ProductVersion productVersion = ProductVersion.Builder.newBuilder().product(product).version("1.0").build();

    // Test validation of product version
    Set<ConstraintViolation<ProductVersion>> productVersionViolations = validator.validate(productVersion);
    Assert.assertTrue(productVersionViolations.size() == 0);

    productVersion.setVersion("1.0.x");
    productVersionViolations = validator.validate(productVersion);
    Assert.assertTrue(productVersionViolations.size() == 1);

    productVersion.setVersion("foo");
    productVersionViolations = validator.validate(productVersion);
    Assert.assertTrue(productVersionViolations.size() == 1);

    // Test product milestone versions
    ProductMilestone milestone = ProductMilestone.Builder.newBuilder()
            .productVersion(productVersion)
            .version("1.0.0.ER1")
            .build();
    Set<ConstraintViolation<ProductMilestone>> milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 0);

    milestone.setVersion("1.0");
    milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 1);

    milestone.setVersion("1.0-DR1");
    milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 1);

    milestone.setVersion("1.0-x");
    milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 1);

    // Test product release versions
    ProductRelease release = ProductRelease.Builder.newBuilder()
            .productMilestone(milestone)
            .version("1.0.0.GA")
            .build();
    Set<ConstraintViolation<ProductRelease>> releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 0);

    release.setVersion("1.0");
    releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 1);

    release.setVersion("1.0-DR1");
    releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 1);

    release.setVersion("1.0-x");
    releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 1);

}
 
Example 17
Source File: DataLevelMapDeserializer.java    From hj-t212-parser with Apache License 2.0 4 votes vote down vote up
@Deprecated
    private void verify(Map<String, String> result) throws T212FormatException {
        if(!ALLOW_MISSING_FIELD.enabledIn(verifyFeature)){
            Stream<DataElement> stream = Stream.of(DataElement.values())
                    .filter(DataElement::isRequired);
            if(result.containsKey(DataElement.Flag.name())){
                String f = result.get(DataElement.Flag.name());
                int flag = Integer.valueOf(f);
                if(DataFlag.D.isMarked(flag)){
                    stream = Stream.concat(stream,Stream.of(DataElement.PNO, DataElement.PNUM));
                }
            }

            Optional<DataElement> missing = stream
                    .filter(e -> !result.containsKey(e.name()))
                    .findFirst();
            if(missing.isPresent()){
                T212FormatException.field_is_missing(PacketElement.DATA,missing.get().name());
            }
        }
//
//        if(!ALLOW_VALUE_NOT_IN_RANGE.enabledIn(verifyFeature)){
//            Optional<DataElement> notInRange = result.entrySet()
//                    .stream()
//                    .map(kv -> new AbstractMap.SimpleEntry<>(
//                            DataElement.valueOf(kv.getKey()),
//                            kv.getValue()
//                    ))
//                    .filter(kv -> kv.getKey() != null)
//                    .filter(kv -> !kv.getKey().isVerify(kv.getValue()))
//                    .map(AbstractMap.SimpleEntry::getKey)
//                    .findFirst();
//            if(notInRange.isPresent()){
//                DataElement dataSchema = notInRange.get();
//                String value = result.get(dataSchema.name());
//                int len = value == null ? 0 : value.length();
//                T212FormatException.length_not_range(PacketElement.DATA,len,dataSchema.getMin(),dataSchema.getMax());
//            }
//        }

        if(!ALLOW_VALUE_NOT_IN_RANGE.enabledIn(verifyFeature)){
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            Stream<Set<ConstraintViolation<T212MapEntry>>> v = result.entrySet()
                    .stream()
                    .map(kv -> T212MapEntry.of(kv.getKey(),kv.getValue()))
                    .map(e -> {
                        return validator.validate(e, DataElement.valueOf(e.getKey()).group());
                    });
            Set<ConstraintViolation<T212MapEntry>> constraintViolationSet;
            if(STRICT.enabledIn(verifyFeature)){
                constraintViolationSet = v
                        .flatMap(Collection::stream)
                        .collect(Collectors.toSet());
            }else{
                constraintViolationSet = v
                        .findAny()
                        .orElse(new HashSet<>());
            }

            if(!constraintViolationSet.isEmpty()){
                String msg = constraintViolationSet.stream()
                        .map(cv -> {
                            return cv.getRootBean().getKey()
                                    + ":"
                                    + cv.getInvalidValue().toString()
                                    + "_"
                                    + cv.getMessage();
                        })
                        .collect(Collectors.joining("\n"));
                throw new T212FormatException("Validate error\n\n" + msg);
            }
        }
    }
 
Example 18
Source File: MethodValidationPostProcessor.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Set the JSR-303 ValidatorFactory to delegate to for validating methods,
 * using its default Validator.
 * <p>Default is the default ValidatorFactory's default Validator.
 * @see javax.validation.ValidatorFactory#getValidator()
 */
public void setValidatorFactory(ValidatorFactory validatorFactory) {
	this.validator = validatorFactory.getValidator();
}
 
Example 19
Source File: BeanValidationPostProcessor.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Set the JSR-303 ValidatorFactory to delegate to for validating beans,
 * using its default Validator.
 * <p>Default is the default ValidatorFactory's default Validator.
 * @see javax.validation.ValidatorFactory#getValidator()
 */
public void setValidatorFactory(ValidatorFactory validatorFactory) {
	this.validator = validatorFactory.getValidator();
}
 
Example 20
Source File: BeanValidationPostProcessor.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Set the JSR-303 ValidatorFactory to delegate to for validating beans,
 * using its default Validator.
 * <p>Default is the default ValidatorFactory's default Validator.
 * @see javax.validation.ValidatorFactory#getValidator()
 */
public void setValidatorFactory(ValidatorFactory validatorFactory) {
	this.validator = validatorFactory.getValidator();
}